<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Models\FinancialYear;
use App\Services\AuditLogService;
use Illuminate\Http\Request;

class FinancialYearController extends Controller
{
    public function index()
    {
        $financialYears = FinancialYear::latest()->get();
        return view('settings.financial_years.index', compact('financialYears'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'status' => 'required|in:open,closed',
            'is_default' => 'boolean',
            'lock_date' => 'nullable|date',
        ]);

        if (!empty($validated['is_default'])) {
            FinancialYear::query()->update(['is_default' => false]);
        }

        $fy = FinancialYear::create($validated);

        AuditLogService::log('FINANCIAL_YEAR_CREATED', 'FinancialYear', $fy->id, null, $fy->toArray());

        return redirect()->route('financial-years.index')->with('success', 'Financial year created successfully.');
    }

    public function update(Request $request, FinancialYear $financialYear)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'status' => 'required|in:open,closed',
            'is_default' => 'boolean',
            'lock_date' => 'nullable|date',
        ]);

        $oldData = $financialYear->toArray();

        if (!empty($validated['is_default'])) {
            FinancialYear::where('id', '!=', $financialYear->id)->update(['is_default' => false]);
        }

        $financialYear->update($validated);

        AuditLogService::log('FINANCIAL_YEAR_UPDATED', 'FinancialYear', $financialYear->id, $oldData, $financialYear->fresh()->toArray());

        return redirect()->route('financial-years.index')->with('success', 'Financial year updated successfully.');
    }
}
