<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\TransGrievance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

// use Validator;

class TransGrievanceController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->per_page ?? 10;
        $search = $request->search;

        $query = TransGrievance::with([
            'property',
            'owner',
            'demand',
            'demand.property',
            'demand.owner',
            'demand.taxType',
            'demand.financialYear',
            'status',
            'generatedBy',
            'approvedBy',
            'rStatus'
        ]);

        if ($search) {
            $query->where('Grvnc_No', 'like', "%$search%")
                  ->orWhere('Description', 'like', "%$search%")

                   ->orWhereHas('owner', function ($sub) use ($search) {
                $sub->where('Full_Name', 'like', "%$search%");
            })
                ->orWhereHas('property', function ($sub) use ($search) {
                $sub->where('Prop_Name', 'like', "%$search%");
            });
        }

        $data = $query->latest()->paginate($perPage);

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

    public function all()
{
    $data = TransGrievance::with([
        'property',
        'owner',
        'demand',
        'status',
        'generatedBy',
        'approvedBy',
        'rStatus'
    ])
    ->latest()
    ->get();

    return response()->json([
        'success' => true,
        'message' => 'All Records Fetch Successfully',
        'data' => $data
    ]);
}

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [

            'Prop_Id' => 'nullable|exists:property_master,Prop_Id',
            'Owner_ID' => 'nullable|exists:owner_master,Owner_ID',
            'Dmd_Id' => 'nullable|exists:trans_demand,Dmd_Id',

            // 'Grvnc_No' => 'required|unique:trans_grievances,Grvnc_No',
             'Grvnc_No' => [
            'nullable',
            \Illuminate\Validation\Rule::unique('trans_grievances', 'Grvnc_No')
                ->whereNull('deleted_at')
        ],
            'Grvnc_Date' => 'required|date',

            'Category' => 'required|in:Wrong Assessment,Wrong Usage,Ownership Dispute,Duplicate Demand,Payment Not Updated,Exemption Claim,Other',
            'Description' => 'required',

            'Status' => 'nullable|exists:action_master,Act_Id',
            'R_Status'          => 'nullable|exists:action_master,Act_Id',
            'Status_Remarks'          => 'nullable|string',
            'Generated_By' => 'nullable|exists:user_master,Usr_Id',
            'Approved_By' => 'nullable|exists:user_master,Usr_Id',
            'Resolution' => 'nullable|string',
            'Resolved_At' => 'nullable|date',

        ]);

        if($validator->fails()){
            return response()->json($validator->errors(),422);
        }

        $data = TransGrievance::create($request->all());

        return response()->json([
            'success' => true,
            'message' => 'Created Successfully',
            'data' => $data
        ]);
    }

    public function show($id)
    {
        $data = TransGrievance::with([
            'property',
            'owner',
            'demand',
            'demand.property',
            'demand.owner',
            'demand.taxType',
            'demand.financialYear',
            'status',
            'generatedBy',
            'approvedBy',
            'rStatus'

        ])->find($id);

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

        return response()->json([
            'status' => true,
            'message' => 'Record fetched successfully',
            'data' => $data
        ], 200);
    }

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

    if (!$data) {
        return response()->json([
            'success' => false,
            'message' => 'Not Found'
        ], 404);
    }

    $validator = Validator::make($request->all(), [

        'Prop_Id' => 'nullable|exists:property_master,Prop_Id',
        'Owner_ID' => 'nullable|exists:owner_master,Owner_ID',
        'Dmd_Id' => 'nullable|exists:trans_demand,Dmd_Id',

        // 'Grvnc_No' => 'required|string|max:30|unique:trans_grievances,Grvnc_No,' . $id . ',Grvnc_Id',
         'Grvnc_No' => [
                'nullable',
                \Illuminate\Validation\Rule::unique('trans_grievances', 'Grvnc_No')
                    ->ignore($id, 'Grvnc_Id')
                    ->whereNull('deleted_at')
            ],
        'Grvnc_Date' => 'nullable|date',

        'Category' => 'nullable|in:Wrong Assessment,Wrong Usage,Ownership Dispute,Duplicate Demand,Payment Not Updated,Exemption Claim,Other',

        'Description' => 'nullable|string',

        'Status' => 'nullable|exists:action_master,Act_Id',
        'R_Status' => 'nullable|exists:action_master,Act_Id',
        'Status_Remarks' => 'nullable|string',
        'Generated_By' => 'nullable|exists:user_master,Usr_Id',
        'Approved_By' => 'nullable|exists:user_master,Usr_Id',
        'Resolution' => 'nullable|string',
        'Resolved_At' => 'nullable|date',

    ]);

    if ($validator->fails()) {
        return response()->json([
            'success' => false,
            'errors' => $validator->errors()
        ], 422);
    }

    $data->update($request->all());

    return response()->json([
        'success' => true,
        'message' => 'Updated Successfully',
        'data' => $data
    ]);
}
    public function destroy($id)
    {
        $data = TransGrievance::find($id);

        if(!$data){
            return response()->json([
                'message'=>'Not Found'
            ],404);
        }

        $data->delete();

        return response()->json([
            'success'=>true,
            'message'=>'Deleted Successfully'
        ]);
    }
}
