<?php

namespace App\Http\Controllers;

use App\Models\FyearMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class FyearMasterController extends Controller
{
    public function index(Request $request)
    {
        try {
            $query = FyearMaster::query();

            if ($request->filled('status')) {
                $query->where('Status', $request->status);
            }

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

            $years = $query->orderBy('St_Date', 'desc')->get();

            return response()->json([
                'success' => true,
                'data'    => $years
            ]);
        } catch (\Exception $e) {
            Log::error($e);
            return response()->json(['success' => false, 'message' => 'Server error'], 500);
        }
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'FY_Code'              => 'required|string|max:9|unique:fyear_master,FY_Code',
            'FY_Name'              => 'nullable|string|max:20',
            'St_Date'              => 'required|date',
            'Ed_Date'              => 'required|date|after:St_Date',
            'is_current_year'      => 'boolean',
            'is_budget_open'       => 'boolean',
            'is_transaction_open'  => 'boolean',
            'PY_Id'                => 'nullable|exists:fyear_master,FY_id',
            'NY_Id'                => 'nullable|exists:fyear_master,FY_id',
            'Remarks'              => 'nullable|string|max:255',
            'Status'               => 'in:ACTIVE,CLOSED,LOCKED',
        ]);

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

        $data = $request->all();

        // Only one current year allowed
        if ($request->boolean('is_current_year')) {
            FyearMaster::where('is_current_year', true)->update(['is_current_year' => false]);
        }

        $year = FyearMaster::create($data);

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

    public function show($id)
    {
        $year = FyearMaster::with(['previousYear', 'nextYear'])->find($id);

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

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

    public function update(Request $request, $id)
    {
        $year = FyearMaster::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'FY_Code' => [
                'sometimes',
                'string',
                'max:9',
                Rule::unique('fyear_master', 'FY_Code')->ignore($id, 'FY_id')
            ],
            'FY_Name'              => 'nullable|string|max:20',
            'St_Date'              => 'sometimes|date',
            'Ed_Date'              => 'sometimes|date|after:St_Date',
            'is_current_year'      => 'boolean',
            'is_budget_open'       => 'boolean',
            'is_transaction_open'  => 'boolean',
            'PY_Id'                => 'nullable|exists:fyear_master,FY_id',
            'NY_Id'                => 'nullable|exists:fyear_master,FY_id',
            'Remarks'              => 'nullable|string|max:255',
            'Status'               => 'sometimes|in:ACTIVE,CLOSED,LOCKED',
        ]);

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

        $data = $request->all();

        if ($request->has('is_current_year') && $request->boolean('is_current_year')) {
            FyearMaster::where('is_current_year', true)
                ->where('FY_id', '!=', $id)
                ->update(['is_current_year' => false]);
        }

        $year->update($data);

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

    public function destroy($id)
    {
        $year = FyearMaster::find($id);

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

        // Prevent delete if referenced
        if (FyearMaster::where('PY_Id', $id)->orWhere('NY_Id', $id)->exists()) {
            return response()->json(['success' => false, 'message' => 'Cannot delete - referenced by other years'], 400);
        }

        $year->delete();

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

    // Extra useful method
    public function current()
    {
        $current = FyearMaster::current()->first();

        if (!$current) {
            return response()->json(['success' => false, 'message' => 'No current year found'], 404);
        }

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