<?php

namespace App\Http\Controllers\Company\Reports;

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

class TrialBalanceController 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);
        $dateFrom = $request->input('date_from', $defaults['date_from']);
        $dateTo = $request->input('date_to', $defaults['date_to']);
        $includeZero = $request->boolean('include_zero');
        $fiscalYears = $this->reports->fiscalYears($companyId);

        $report = $this->reports->trialBalance($companyId, $dateFrom, $dateTo, $includeZero);

        return view('reports.trial-balance.index', [
            'rows' => $report['rows'],
            'totals' => $report['totals'],
            'fiscalYears' => $fiscalYears,
            'selectedFiscalYearId' => $request->integer('fiscal_year_id') ?: optional($defaults['fiscal_year'])->id,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'includeZero' => $includeZero,
        ]);
    }

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