<?php

namespace App\Http\Controllers;

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

class GrantEntryController extends Controller
{
   
    public function index(Request $request): JsonResponse
    {
        try {

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

            $query = GrantEntry::with([
                'financialYear',
                'department',
                'grantType',
                'budgetHead',
                'action',
                'hod'
            ]);

            if (!empty($search)) {
                $query->where(function ($q) use ($search) {
                    $q->where('GrTrn_Id', 'like', "%$search%")
                        ->orWhere('Amount', 'like', "%$search%");
                });
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Grant entries 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);
        }
    }

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

            $validated = $request->validate([
                'FY_Id'   => 'required|exists:fyear_master,FY_Id',
                'Dpt_Id'  => 'required|exists:dept_master,Dpt_id',
                'GT_Id'   => 'required|exists:grant_type_master,GT_Id',
                'Bh_Id'   => 'required|exists:budget_head,Bh_Id',
                'Amount'  => 'required|numeric',
                'Date'    => 'nullable|date',
                'Status'  => 'required|exists:action_master,Act_Id',
                'GE_HOD' => 'nullable|exists:user_master,Usr_Id',
                'Remarks' => 'nullable|string',
            ]);

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

            $data->load([
                'financialYear',
                'department',
                'grantType',
                'budgetHead',
                'action',
                'hod'
            ]);

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

            return response()->json([
                'success' => false,
                '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);
        }
    }

    public function show($id): JsonResponse
    {
        try {

            $data = GrantEntry::with([
                'financialYear',
                'department',
                'grantType',
                'budgetHead',
                'action',
                'hod'
            ])->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);
        }
    }

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

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

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

            $validated = $request->validate([
                'FY_Id'   => 'sometimes|exists:fyear_master,FY_Id',
                'Dpt_Id'  => 'sometimes|exists:dept_master,Dpt_id',
                'GT_Id'   => 'sometimes|exists:grant_type_master,GT_Id',
                'Bh_Id'   => 'sometimes|exists:budget_head,Bh_Id',
                'Amount'  => 'sometimes|numeric',
                'Date'    => 'sometimes|nullable|date',
                'Status'  => 'sometimes|exists:action_master,Act_Id',
                'GE_HOD' => 'sometimes|nullable|exists:user_master,Usr_Id',
                'Remarks' => 'sometimes|nullable|string',
            ]);

            $data->update($validated);

            $data->load([
                'financialYear',
                'department',
                'grantType',
                'budgetHead',
                'action'
            ]);

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

            return response()->json([
                'success' => false,
                '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);
        }
    }


    public function destroy($id): JsonResponse
    {
        try {

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

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

            $data->delete();

            return response()->json([
                'success' => true,
                'message' => 'Deleted successfully'
            ]);
        } 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);
        }
    }

    public function all(): JsonResponse
    {
        try {

            $data = GrantEntry::with([
                'financialYear',
                'department',
                'grantType',
                'budgetHead',
                'action',
                'hod'
            ])->orderBy('GrTrn_Id', 'desc')->get();

            return response()->json([
                'success' => true,
                'message' => 'All grant entries 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);
        }
    }
}
