<?php

namespace App\Http\Controllers;

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

class LedgerMasterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | INDEX
    |--------------------------------------------------------------------------
    */

    public function index(Request $request)
    {
        try {
            $query = LedgerMaster::with('ledgerGroup');

            if ($request->has('status')) {
                $query->where('Lg_Status', $request->boolean('status'));
            }

            if ($request->has('search')) {
                $query->search($request->search);
            }

            if ($request->has('gr_id')) {
                $query->where('Gr_Id', $request->gr_id);
            }

    if ($request->has('filter_deleted_buk_y') && $request->boolean('filter_deleted_buk_y')) {
                $query->whereHas('ledgerGroup', function ($q) {
                    $q->where('Gr_Buk', 'Y');
                });
            }

            // New filter 2: ledger_group.is_del === "Y" AND ledger_group.gr_buk === "N"
            if ($request->has('filter_deleted_buk_n') && $request->boolean('filter_deleted_buk_n')) {
                $query->whereHas('ledgerGroup', function ($q) {
                    $q->where('Gr_Buk', 'N');
                });
            }

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

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

            $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' => $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');

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

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

    public function show($id)
    {
        $ledger = LedgerMaster::with('ledgerGroup')->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');

        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()
{
    $data = LedgerMaster::with('ledgerGroup')->get();

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

}
