<?php

namespace App\Http\Controllers\admin;

use App\Models\Agent;
use App\Models\Contact;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class ContactController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $draw = $request->get('draw');

            $start = $request->get("start");
            $rowperpage = $request->get("length"); // Rows display per page
            $search_arr = $request->get('search');
            $searchValue = $search_arr['value']; // Search value
            $totalRecords = Contact::select('count(*) as allcount')->count();
                        $totalRecordswithFilter = Contact::select('count(*) as allcount')->where('name', 'like', '%' . $searchValue . '%')->orwhere('phone', 'like', '%' . $searchValue . '%')->count();
            $agent_id= $request->agent_id;

            $contacts = Contact::select('contacts.*')
                ->when($searchValue != null, function ($q) use ($searchValue) {
                    $q->where('name', 'like', '%' . $searchValue . '%')
                    ->orwhere('phone', 'like', '%' . $searchValue . '%') ;
                })
                ->when($agent_id != null, function ($q) use ($agent_id) {
                    $q->where('agent_id', $agent_id);
                })
                ->skip($start)
                ->take($rowperpage)
                ->orderBy('contacts.id', 'desc')
                ->get();

            $records = [];

            foreach($contacts as $contact)
            {

                $records[] = [
                       'record_select' => '<div class="animated-checkbox"><label class="m-0"><input type="checkbox" class="record__select" value="'. $contact->id .'"><span class="label-text"></span></label></div>',
                       'name' => $contact->name ,
                       'phone' =>'<a href="tel:'. $contact->phone .'" class="form-label">'. $contact->phone .'</a>' ,
                       'agent'=>$contact->agent->name ?? '',
                       'actions' => view('admin.contact.buttons',[ 'contact' => $contact ])->render() ,
                    ];
            }

            $response = [
                        "draw" => intval($draw),
                        "iTotalRecords" => $totalRecords,
                        "iTotalDisplayRecords" => $totalRecordswithFilter,
                        "aaData" => $records
                    ];

            return response()->json($response);

        }
        $contacts = Contact::latest()->get();
        $agents = Agent::active()->orderBy('name')->pluck('name', 'id')->toArray();
        $total = Contact::select('count(*) as allcount')->count();
        return view('admin.contact.contacts',[
            'contacts' => $contacts,
            'total' => $total,
            'agents' => $agents,
        ]);

        // $contacts = Contact::latest()->get();
        // return view('admin.contact.contacts',compact('contacts'));
    }


    public function create()
    {
        $agents = Agent::active()->orderBy('name')->pluck('name', 'id')->toArray();

        $modalContent = view('admin.contact.create_contact',compact('agents'))->render();

        return response()->json(['modalContent' => $modalContent]);
    }


    public function store(Request $request)
    {

        // التحقق من المدخلات
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:13|min:10|unique:contacts,phone',
            'email' => 'nullable|email|unique:contacts,email',
            'notes' => 'nullable|string',
            'agent_id' => 'required|exists:agents,id',

        ] );

        // إنشاء خدمة جديد
        Contact::create($validated);

        $notification = trans('dash.Created Successfully');
        return response()->json(['redirect_url' => route('admin.contact.index'),
        'notification' => $notification ]
    );
    }

    public function edit($id)
    {
        $contact = contact::find($id);
        $agents = Agent::active()->orderBy('name')->pluck('name', 'id')->toArray();

            $modalContent = view('admin.contact.edit_contact',compact('contact','agents'))->render();
            return response()->json(['modalContent' => $modalContent]);

    }


    public function update(Request $request,$id)
    {
        $contact = contact::find($id);


        // التحقق من المدخلات
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:13|min:10|unique:contacts,phone,'. $contact->id,
            'email' => 'nullable|email|unique:contacts,email,'. $contact->id,
            'notes' => 'nullable|string',
            'agent_id' => 'required|exists:agents,id',
        ] );

        // تحديث بيانات الخدمة
        $contact->update($validated);

        $notification = trans('dash.Updated Successfully');
        return response()->json(['redirect_url' => route('admin.contact.index'),
        'notification' => $notification ]
    );
    }

    public function destroy($id)
    {
        $contact =Contact::find($id);
        $contact->delete();
        $notification = trans('dash.Delete Successfully');
        $notification = array('messege'=>$notification,'alert-type'=>'success');
        return redirect()->route('admin.contact.index')->with($notification);
    }


}
