<?php

namespace App\Http\Controllers\Admin;

use App\Models\Company;
use App\Services\Gstr1ExcelExporter;
use App\Services\Gstr1ReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class Gstr1ReportController extends AdminController
{
    public function __construct(
        private readonly Gstr1ReportService $reportService,
        private readonly Gstr1ExcelExporter $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.gstr1', [
            'company' => $company,
            'periodFrom' => $periodFrom,
            'periodTo' => $periodTo,
            'activeReport' => 'gstr1',
        ]);
    }

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

        $report = $this->reportService->build($this->companyId(), $periodFrom, $periodTo);
        $filename = $this->filename($report['company']->name, 'xls');

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

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

        $report = $this->reportService->build($this->companyId(), $periodFrom, $periodTo);
        $filename = $this->filename($report['company']->name, 'json');

        return response()->streamDownload(function () use ($report) {
            echo json_encode($report['json'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        }, $filename, [
            'Content-Type' => 'application/json',
        ]);
    }

    private function filename(string $companyName, string $ext): string
    {
        $slug = Str::slug($companyName) ?: 'company';
        $date = now()->format('Y-m-d');

        return "{$date}_GST__R1Gov_{$slug}.{$ext}";
    }
}
