<?php

namespace App\Http\Controllers;

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

class PayDetailController extends Controller
{

    // ================= LIST =================
    public function index(Request $request)
    {
        $query = PayDetail::with([
            'payVoucher',
            'tenderType',
            'vendorParameter',
            'invoiceCharge',
            'ledger',
            'challanType',
            'ChlnvParameter'
        ]);

        // ================= SEARCH =================

        if ($request->search) {

            $search = $request->search;

            $query->where(function ($q) use ($search) {

                $q->where('Formula', 'like', "%{$search}%")
                    ->orWhere('Percent', 'like', "%{$search}%")
                    ->orWhere('IC_Amt', 'like', "%{$search}%");

                // Search in relations

                $q->orWhereHas('payVoucher', function ($sub) use ($search) {
                    $sub->where('PV_No', 'like', "%{$search}%");
                });

                $q->orWhereHas('ledger', function ($sub) use ($search) {
                    $sub->where('Lg_Name', 'like', "%{$search}%");
                });
            });
        }


        // ================= FILTERS (Optional) =================

        if ($request->PV_Id) {
            $query->where('PV_Id', $request->PV_Id);
        }

        if ($request->Lg_Id) {
            $query->where('Lg_Id', $request->Lg_Id);
        }

        // ================= PAGINATION =================

        $perPage = $request->per_page ?? 10;

        $data = $query->latest()->paginate($perPage);
        return response()->json([
            'success' => true,
            'message' => 'Pay Details List',
            'data' => $data->items(),

            'pagination' => [
                'current_page' => $data->currentPage(),
                'last_page' => $data->lastPage(),
                'per_page' => $data->perPage(),
                'total' => $data->total()
            ]
        ]);
    }


    // ================= STORE =================
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'PV_Id' => 'required|exists:pay_vouchers,PV_Id',
            'TnT_ID' => 'required|exists:tender_type,TnT_ID',
            'PVD_Sr' => 'required|integer',
            'VIP_Id' => 'required|exists:vendinv_parameter,VIP_Id',
            'IC_Id' => 'required|exists:invoice_charge_master,IC_Id',
            'Lg_Id' => 'required|exists:ledger_master,Lg_Id',
            'Cht_Id' => 'nullable|exists:challan_types,Cht_Id',
            'CIP_Id' => 'nullable|exists:chlnv_parameter,CIP_Id',
        ]);

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

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

        return response()->json([
            'success' => true,
            'message' => 'Created successfully',
            'data' => $data->load([
                'payVoucher',
                'tenderType',
                'vendorParameter',
                'invoiceCharge',
                'ledger',
                'challanType',
                'ChlnvParameter'
            ])
        ]);
    }


    // ================= SHOW =================
    public function show($id)
    {
        $data = PayDetail::with([
            'payVoucher',
            'tenderType',
            'vendorParameter',
            'invoiceCharge',
            'ledger',
            'challanType',
            'ChlnvParameter'

        ])->find($id);

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

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


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

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

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

        return response()->json([
            'success' => true,
            'message' => 'Updated successfully',
            'data' => $data->load([
                'payVoucher',
                'tenderType',
                'vendorParameter',
                'invoiceCharge',
                'ledger',
                'challanType',
                'ChlnvParameter'
            ])
        ]);
    }


    // ================= DELETE =================
    public function destroy($id)
    {
        $data = PayDetail::find($id);

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

        $data->delete();

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