<?php

namespace App\Http\Controllers;

use App\Models\LedgerMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class LedgerMasterController extends Controller
{
    
    public function index(Request $request)
{
    try {
        $query = LedgerMaster::with(['ledgerGroup', 'budgetHead', 'grantType']);

        // ✅ Status filter
        if ($request->filled('status')) {
            $query->where('Lg_Status', $request->boolean('status'));
        }

        // ✅ Search (WORKING for 2.5)
        if ($request->filled('search')) {

            $search = $request->search;

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

                $q->where('Lg_Name', 'LIKE', "%{$search}%")
                  ->orWhere('Lg_Eng_Name', 'LIKE', "%{$search}%")
                  ->orWhere('Lg_Code', 'LIKE', "%{$search}%");

                // 🔥 dot ignore (2.5 → 25)
                $searchNoDot = str_replace('.', '', $search);

                $q->orWhereRaw("REPLACE(Lg_Name, '.', '') LIKE ?", ["%{$searchNoDot}%"])
                  ->orWhereRaw("REPLACE(Lg_Eng_Name, '.', '') LIKE ?", ["%{$searchNoDot}%"]);
            });
        }

        // ✅ Group filter
        if ($request->filled('gr_id')) {
            $query->where('Gr_Id', $request->gr_id);
        }

        // ✅ FIXED: include NULL also
        if ($request->boolean('filter_deleted_buk_y')) {
            $query->where(function ($q) {
                $q->whereHas('ledgerGroup', function ($sub) {
                    $sub->where('Gr_Buk', 'Y');
                });
            });
        }

        if ($request->boolean('filter_deleted_buk_n')) {
            $query->where(function ($q) {
                $q->whereHas('ledgerGroup', function ($sub) {
                    $sub->where('Gr_Buk', 'N');
                })
                ->orWhereDoesntHave('ledgerGroup'); // 🔥 THIS IS IMPORTANT
            });
        }

        if ($request->filled('Lg_Buk')) {
    $query->where('Lg_Buk', strtoupper($request->Lg_Buk));
} 


        // ✅ Sorting
        $sortBy = $request->get('sort_by', 'Lg_Code');
        $sortOrder = $request->get('sort_order', 'asc');

        $query->orderBy($sortBy, $sortOrder);

        // ✅ Pagination
        $ledgers = $query->paginate($request->get('per_page', 10));

        return response()->json([
            'success' => true,
            'data' => $ledgers,
            'message' => 'Ledgers retrieved successfully'
        ]);

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


    /*
    |--------------------------------------------------------------------------
    | STORE
    |--------------------------------------------------------------------------
    */

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

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

        $ledger = LedgerMaster::create($request->all());
        $ledger->load(['ledgerGroup', 'budgetHead']);
        return response()->json([
            'success' => true,
            'message' => 'Ledger created successfully',
            'data' => $ledger
        ], 201);
    }

    /*
    |--------------------------------------------------------------------------
    | SHOW
    |--------------------------------------------------------------------------
    */

    public function show($id)
    {
        $ledger = LedgerMaster::with(['ledgerGroup', 'budgetHead', 'grantType'])->find($id);
        if (!$ledger) {
            return response()->json([
                'success' => false,
                'message' => 'Ledger not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $ledger,
            'message' => 'Ledger retrieved successfully'
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | UPDATE
    |--------------------------------------------------------------------------
    */

    public function update(Request $request, $id)
    {
        $ledger = LedgerMaster::find($id);

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

        $validator = Validator::make(
            $request->all(),
            LedgerMaster::updateRules($id)
        );

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

        $ledger->update($request->all());
        $ledger->load(['ledgerGroup', 'budgetHead']);
        return response()->json([
            'success' => true,
            'message' => 'Ledger updated successfully',
            'data' => $ledger
        ]);
    }

    /*
    |--------------------------------------------------------------------------
    | DELETE (Soft Delete)
    |--------------------------------------------------------------------------
    */

    public function destroy($id)
    {
        $ledger = LedgerMaster::find($id);

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

        $ledger->delete();

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

    /*
    |--------------------------------------------------------------------------
    | ACTIVATE / DEACTIVATE
    |--------------------------------------------------------------------------
    */

    public function deactivate($id)
    {
        $ledger = LedgerMaster::find($id);

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

        $ledger->deactivate();

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

    public function activate($id)
    {
        $ledger = LedgerMaster::find($id);

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

        $ledger->activate();

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

    /*
|--------------------------------------------------------------------------
| ALL DATA (Without Pagination)
|--------------------------------------------------------------------------
*/

    /*
|--------------------------------------------------------------------------
| ALL DATA (Without Pagination)
|--------------------------------------------------------------------------
*/

    public function all(Request $request)
    {
                $query = LedgerMaster::with([
            'ledgerGroup',
            'budgetHead',
            'grantType'
        ]);

        // Lg_Buk filter
        if ($request->filled('Lg_Buk')) {
            $query->where('Lg_Buk', strtoupper($request->Lg_Buk));
        }

        $data = $query->get();

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

    }
}
