<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Admin\PageController;
use App\Http\Requests\Finance\StoreBudgetRequest;
use App\Models\AcademicYear;
use App\Models\Account;
use App\Models\Budget;
use App\Services\Finance\BudgetService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class BudgetController extends PageController
{
    public function __construct(
        private readonly BudgetService $budgetService,
    ) {}

    public function index(): View
    {
        $budgets = Budget::query()
            ->with('lines')
            ->latest()
            ->paginate(20);

        return $this->page('admin.budgets.index', [
            'crumbTitle' => 'Budgeting',
            'crumbSub' => 'Budget variance & year-end forecast',
            'budgets' => $budgets,
        ]);
    }

    public function create(): View
    {
        return $this->page('admin.budgets.create', [
            'crumbTitle' => 'Budgeting',
            'crumbSub' => 'Set up budget',
            'academicYears' => AcademicYear::query()->orderByDesc('starts_on')->get(),
            'accounts' => Account::query()->orderBy('code')->get(),
        ]);
    }

    public function store(StoreBudgetRequest $request): RedirectResponse
    {
        try {
            $budget = $this->budgetService->create(
                $request->safe()->except('lines'),
                $request->validated('lines'),
            );
        } catch (\Throwable $e) {
            return back()->withInput()->with('error', $e->getMessage());
        }

        return redirect()
            ->route('finance.budgets.show', $budget)
            ->with('success', "Budget \"{$budget->name}\" created successfully.");
    }

    public function show(Budget $budget): View
    {
        $variance = $this->budgetService->budgetVsActual($budget);
        $forecast = $this->budgetService->forecast($budget);

        return $this->page('admin.budgets.show', [
            'crumbTitle' => 'Budgeting',
            'crumbSub' => $budget->name,
            'budget' => $budget->load('lines.account', 'academicYear'),
            'variance' => $variance,
            'forecast' => $forecast,
        ]);
    }
}
