<?php

namespace App\Http\Controllers;

use App\Models\PayrollBill;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class PayrollBillController extends Controller
{

    /**
     * List with Search & Pagination
     */
    public function index(Request $request): JsonResponse
    {
        try {

            $perPage = $request->get('per_page', 20);
            $search  = $request->get('search');

            $query = PayrollBill::with('ledger');


            if (!empty($search)) {

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

                    $q->where('PayBill_Code', $search)
                        ->orWhere('Description', $search)
                        ->orWhereHas('ledger', function ($sub) use ($search) {
                            $sub->where('Lg_Name', $search);
                        });
                });
            }

            $data = $query->orderBy('PRB_id', 'desc')
                ->paginate($perPage);

            return response()->json([
                'success' => true,
                'message' => 'Payroll bill list fetched successfully',
                'data'    => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    /**
     * Store
     */
    public function store(Request $request): JsonResponse
    {
        try {

            $validated = $request->validate([
                'PayBill_Code' => 'required|unique:payroll_bills,PayBill_Code',
                'Description'  => 'nullable|string|max:255',
                'Lg_Id'        => 'nullable|exists:ledger_master,Lg_Id'
            ]);

            $data = PayrollBill::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Payroll bill created successfully',
                'data'    => $data
            ]);
        } catch (\Illuminate\Validation\ValidationException $ve) {

            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors'  => $ve->errors()
            ], 422);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    /**
     * Show Single Record
     */
    public function show($id): JsonResponse
    {
        try {

            $data = PayrollBill::with('ledger')->find($id);

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

            return response()->json([
                'success' => true,
                'data'    => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    /**
     * Update
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {

            $data = PayrollBill::find($id);

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

            $validated = $request->validate([
                'PayBill_Code' => 'sometimes|required|unique:payroll_bills,PayBill_Code,' . $id . ',PRB_id',
                'Description'  => 'sometimes|nullable|string|max:255',
                'Lg_Id'        => 'sometimes|nullable|exists:ledger_master,Lg_Id'
            ]);

            $data->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Payroll bill updated successfully',
                'data'    => $data
            ]);
        } catch (\Illuminate\Validation\ValidationException $ve) {

            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors'  => $ve->errors()
            ], 422);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }


    /**
     * Delete
     */
    public function destroy($id): JsonResponse
    {
        $data = PayrollBill::find($id);

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

        $data->delete(); // ✅ Soft Delete

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


    /**
     * All Records (Without Pagination)
     */
    public function all(): JsonResponse
    {
        try {

            $data = PayrollBill::with('ledger')
                ->orderBy('PRB_id', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'message' => 'All payroll bills fetched successfully',
                'data'    => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }
}
