<?php

namespace App\Http\Controllers\Company\Reports;

use App\Http\Controllers\Controller;
use App\Services\{LedgerReportService, VoucherNumberService};
use Illuminate\Http\Request;

class JournalReportController 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']);
        $voucherType = $request->input('voucher_type') ?: null;
        $search = $request->input('search') ?: null;
        $fiscalYears = $this->reports->fiscalYears($companyId);
        $voucherTypes = VoucherNumberService::voucherTypes();
        $report = $this->reports->journalReport($companyId, $dateFrom, $dateTo, $voucherType, $search);

        return view('reports.journal.index', [
            'entries' => $report['entries'],
            'groups' => $report['groups'],
            'totals' => $report['totals'],
            'fiscalYears' => $fiscalYears,
            'selectedFiscalYearId' => $request->integer('fiscal_year_id') ?: optional($defaults['fiscal_year'])->id,
            'dateFrom' => $dateFrom,
            'dateTo' => $dateTo,
            'voucherType' => $voucherType,
            'voucherTypes' => $voucherTypes,
            'search' => $search,
        ]);
    }

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