<?php

namespace App\Http\Controllers;

use App\Models\InvoiceChargeMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Throwable;

class InvoiceChargeMasterController extends Controller
{
    // 🔹 INDEX
public function index(Request $request)
{
    try {

        $search  = $request->search;
        $perPage = $request->per_page ?? 10;   // default 10 records

        $query = InvoiceChargeMaster::with('ledger')
                    ->orderBy('IC_Id', 'desc');

        // 🔎 Search Filter
        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('IC_Code', 'like', "%{$search}%")
                  ->orWhere('IC_Name', 'like', "%{$search}%")
                  ->orWhere('Percentage', 'like', "%{$search}%");
            });
        }

        // 📄 Pagination
        $data = $query->paginate($perPage);

        return response()->json([
            'success' => true,
            'message' => 'Invoice charges fetched successfully',
            'data'    => $data
        ], 200);

    } catch (Throwable $e) {

        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch invoice charges',
            'error'   => $e->getMessage()
        ], 500);
    }
}

public function all()
{
    try {

        $data = InvoiceChargeMaster::with('ledger')
                    ->orderBy('IC_Name', 'asc')
                    ->get();

        return response()->json([
            'success' => true,
            'message' => 'All invoice charges fetched successfully',
            'data' => $data
        ], 200);

    } catch (Throwable $e) {

        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch invoice charges',
            'error' => $e->getMessage()
        ], 500);
    }
}



    // 🔹 STORE
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'IC_Code'      => 'nullable|string|max:20|unique:invoice_charge_master,IC_Code',
                'IC_Name'      => 'required|string|max:100',
                'Percentage'   => 'nullable|numeric|min:0|max:100',
                'Lg_Id'        => 'nullable|exists:ledger_master,Lg_Id',   // ← important
            ]);

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

            $charge = InvoiceChargeMaster::create($request->all());

            return response()->json([
                'success' => true,
                'message' => 'Invoice charge created successfully',
                'data'    => $charge
            ], 201);
        } catch (Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create invoice charge',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // 🔹 SHOW
   public function show($id)
{
    try {

        $charge = InvoiceChargeMaster::with('ledger')->find($id);

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

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

    } catch (Throwable $e) {

        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch invoice charge',
            'error'   => $e->getMessage()
        ], 500);
    }
}

    // 🔹 UPDATE
    public function update(Request $request, $id)
    {
        try {
            $charge = InvoiceChargeMaster::find($id);
            if (!$charge) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice charge not found'
                ], 404);
            }

            $validator = Validator::make($request->all(), [
                'IC_Code'      => 'sometimes|nullable|string|max:20|unique:invoice_charge_master,IC_Code,' . $id . ',IC_Id',
                'IC_Name'      => 'sometimes|required|string|max:100',
                'Percentage'   => 'sometimes|nullable|numeric|min:0|max:100',
                'Lg_Id'        => 'sometimes|nullable|exists:ledger_master,Lg_Id',
            ]);

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

            $charge->update($request->only([
                'IC_Code',
                'IC_Name',
                'Percentage',
                'Lg_Id',
            ]));

            return response()->json([
                'success' => true,
                'message' => 'Invoice charge updated successfully',
                'data'    => $charge
            ], 200);
        } catch (Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update invoice charge',
                'error'   => $e->getMessage()
            ], 500);
        }
    }

    // 🔹 DELETE (soft delete)
    public function destroy($id)
    {
        try {
            $charge = InvoiceChargeMaster::find($id);
            if (!$charge) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invoice charge not found'
                ], 404);
            }

            $charge->delete();

            return response()->json([
                'success' => true,
                'message' => 'Invoice charge deleted successfully'
            ], 200);
        } catch (Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete invoice charge',
                'error'   => $e->getMessage()
            ], 500);
        }
    }
}
