<?php

namespace App\Http\Controllers;

use App\Models\ComplaintCell;
use App\Models\ComplaintStatus;
use App\Models\District;
use App\Models\User;
use App\Models\ComplaintType;
use App\Models\ComplaintAgainst;

use App\Exports\ComplaintsExport;
use Maatwebsite\Excel\Facades\Excel;

use Illuminate\Http\Request;

class ComplaintCellController extends Controller
{

    public function create()
    {
        $districts = District::where('status',1)
                        ->orderBy('district_name')
                        ->get();

        $types = ComplaintType::where('status',1)
                    ->orderBy('type_name')
                    ->get();

        return view(
            'complaint.create',
            compact(
                'districts',
                'types'
            )
        );
    }



    public function getAgainst($id)
    {
        $data = ComplaintAgainst::where(
                    'complaint_type_id',
                    $id
                )
                ->where('status',1)
                ->orderBy('name')
                ->get();

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





    public function store(Request $request)
    {
        // dd($request->all());
        $request->validate([

            'complainant_name'     => 'required|string|max:150',
            'cnic_number'          => 'required|string|max:20',
            'contact_number'       => 'required|string|max:20',

            'district_id'          => 'required|exists:districts,id',
            'complaint_type_id'    => 'required|exists:complaint_types,id',
            'complaint_against_id' => 'required|exists:complaint_against,id',

            'address'              => 'required|string',
            'complaint'            => 'required|string',

        ]);

        ComplaintCell::create([

        'user_id'=>auth()->id(),

        'complainant_name'=>$request->complainant_name,

        'cnic_number'=>$request->cnic_number,

        'contact_number'=>$request->contact_number,

        'district_id'=>$request->district_id,

        'complaint_type_id'=>$request->complaint_type_id,

        'complaint_against_id'=>$request->complaint_against_id,

        'address'=>$request->address,

        'complaint'=>$request->complaint,


        'verification_status'=>'Pending'

        ]);

        return redirect()
            ->route('complaint.index')
            // ->back()
            ->with('success', 'Complaint Submitted Successfully.');
    }


    public function index()
    {

    $user = auth()->user();



    $query = ComplaintCell::with([

    'district',
    'complaintType',
    'complaintAgainst',
    'latestStatus'

    ]);




    // Admin sees everything

    if($user->is_admin == 1)
    {

    }


    // Operator sees only own complaints

    elseif($user->role == 'operator')
    {

    // $query->where(
    // 'user_id',
    // $user->id
    // );

    }


    // Coordinator sees pending verification

    elseif($user->role == 'coordinator')
    {

    $query->where(
    'verification_status',
    'Pending'
    );

    }


    // Department user

    elseif($user->role == 'department')
    {

    $query->where(
    'assigned_to',
    $user->id
    );

    }


    $complaints =
    $query->latest()
    ->paginate(20);



    return view(
    'complaint.index',
    compact('complaints')
    );


    }





    public function edit($id)
    {
        $complaint = ComplaintCell::findOrFail($id);

        $districts = District::where('status',1)
                        ->orderBy('district_name')
                        ->get();

        $types = ComplaintType::where('status',1)
                    ->orderBy('type_name')
                    ->get();

        return view(
            'complaint.edit',
            compact(
                'complaint',
                'districts',
                'types'
            )
        );
    }









    public function update(Request $request, $id)
    {
        $request->validate([

            'complainant_name'      => 'required|string|max:150',
            'cnic_number'           => 'required|string|max:20',
            'contact_number'        => 'required|string|max:20',

            'district_id'           => 'required|exists:districts,id',
            'complaint_type_id'     => 'required|exists:complaint_types,id',
            'complaint_against_id'  => 'required|exists:complaint_against,id',

            'address'               => 'required|string',
            'complaint'             => 'required|string',

        ]);

        $complaint = ComplaintCell::findOrFail($id);

        $complaint->update([

            'complainant_name'      => $request->complainant_name,
            'cnic_number'           => $request->cnic_number,
            'contact_number'        => $request->contact_number,

            'district_id'           => $request->district_id,
            'complaint_type_id'     => $request->complaint_type_id,
            'complaint_against_id'  => $request->complaint_against_id,

            'address'               => $request->address,
            'complaint'             => $request->complaint,

        ]);

        return redirect()
                ->route('complaint.index')
                ->with(
                    'success',
                    'Complaint updated successfully.'
                );
    }



    // public function storeStatus(Request $request)
    // {

    //     ComplaintStatus::create([

    //         'complaint_id' => $request->complaint_id,

    //         'status' => $request->status,

    //         'remarks' => $request->remarks,

    //         'updated_by' => auth()->id()

    //     ]);

    //     return back()->with(

    //         'success',

    //         'Complaint status updated successfully.'

    //     );

    // }

    public function storeStatus(Request $request)
    {
        $request->validate([
            'complaint_id' => 'required|exists:complaint_cells,id',
            'status'       => 'required',
            'remarks'      => 'nullable'
        ]);

        ComplaintStatus::create([

            'complaint_id' => $request->complaint_id,

            'status'       => $request->status,

            'remarks'      => $request->remarks,

            'updated_by'   => auth()->id(),

        ]);

        return back()->with(
            'success',
            'Complaint status updated successfully.'
        );
    }


    public function print($id)
    {
        $complaint = ComplaintCell::with([
                'district',
                'complaintType',
                'complaintAgainst',
                'statuses.user'
            ])
            ->findOrFail($id);


        return view(
            'complaint.print',
            compact('complaint')
        );
    }






public function exportView()
{
    return view('complaint.export');
}



public function export(Request $request)
{

    $request->validate([

        'from_date'=>'required|date',
        'to_date'=>'required|date|after_or_equal:from_date'

    ]);


    return Excel::download(

        new ComplaintsExport(
            $request->from_date,
            $request->to_date
        ),

        'complaints_'.$request->from_date.'_to_'.$request->to_date.'.xlsx'

    );

}






public function verifyComplaint(Request $request,$id)
{


$complaint =
ComplaintCell::findOrFail($id);



$request->validate([

'action'=>'required',

]);



$user = auth()->user();





// Genuine Complaint

$departmentUser = User::where('complaint_against_id',
    $complaint->complaint_against_id
)
->where('role','department')
->first();


if(!$departmentUser)
{
    return back()->with(
        'error',
        'No department user assigned for this complaint category.'
    );
}


$complaint->update([

    'verification_status'=>'Genuine',

    'verified_by'=>auth()->id(),

    'verified_at'=>now(),

    'assigned_to'=>$departmentUser->id

]);





// Irrelevant

if($request->action=="Irrelevant")
{


$complaint->update([


'verification_status'=>'Irrelevant',

'verified_by'=>$user->id,

'verified_at'=>now(),

'assigned_to'=>null


]);


}



return back()->with(

'success',

'Complaint verified successfully'

);


}








public function irrelevant()
{

$complaints =
ComplaintCell::where(
'verification_status',
'Irrelevant'
)
->latest()
->paginate(20);


return view(
'complaint.irrelevant',
compact('complaints')
);

}





}