<?php

namespace App\Http\Controllers\Admin;

use App\Models\Company;
use App\Services\Gstr3bExcelExporter;
use App\Services\Gstr3bReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class Gstr3bReportController extends AdminController
{
    public function __construct(
        private readonly Gstr3bReportService $reportService,
        private readonly Gstr3bExcelExporter $excelExporter,
    ) {}

    public function index(Request $request)
    {
        $company = Company::findOrFail($this->companyId());
        $periodFrom = $request->query('period_from', now()->format('Y-m'));
        $periodTo = $request->query('period_to', $periodFrom);

        return view('admin.reports.gstr3b', [
            'company' => $company,
            'periodFrom' => $periodFrom,
            'periodTo' => $periodTo,
            'activeReport' => 'gstr3b',
        ]);
    }

    public function export(Request $request)
    {
        $validated = $request->validate([
            'period_from' => ['required', 'date_format:Y-m'],
            'period_to' => ['required', 'date_format:Y-m'],
        ]);

        $report = $this->reportService->build(
            $this->companyId(),
            $validated['period_from'],
            $validated['period_to'],
        );

        $slug = Str::slug($report['company']->name) ?: 'company';
        $filename = now()->format('Y-m-d')."_GST__R3bExport_{$slug}.xls";

        return $this->excelExporter->download($report, $filename);
    }
}
