<?php

namespace App\Http\Controllers\Company\Reports;

use App\Http\Controllers\Controller;
use App\Services\LedgerReportService;
use Illuminate\Http\Request;

class BalanceSheetController extends Controller
{
    public function __construct(private readonly LedgerReportService $reports)
    {
    }

    public function index(Request $request)
    {
        $this->gate();

        $companyId = auth()->user()->company_id;
        $defaults = $this->reports->defaultDateRange($companyId, $request->integer('fiscal_year_id') ?: null);
        $asOfDate = $request->input('as_of_date', $defaults['date_to']);
        $includeZero = $request->boolean('include_zero');
        $fiscalYears = $this->reports->fiscalYears($companyId);
        $report = $this->reports->balanceSheet($companyId, $asOfDate, $defaults['date_from'], $includeZero);

        return view('reports.balance-sheet.index', [
            'groups' => $report['groups'],
            'totals' => $report['totals'],
            'fiscalYears' => $fiscalYears,
            'selectedFiscalYearId' => $request->integer('fiscal_year_id') ?: optional($defaults['fiscal_year'])->id,
            'fiscalYearStart' => $defaults['date_from'],
            'asOfDate' => $asOfDate,
            'includeZero' => $includeZero,
        ]);
    }

    private function gate(): void
    {
        if (!auth()->user()->hasPermission('reports', 'view')) {
            abort(403);
        }
    }
}
