<?php

namespace App\Services\Reports;

use App\Models\GeneratedReport;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ReportFileGenerator
{
    public function __construct(
        private readonly ReportCsvWriter $csvWriter,
        private readonly ReportTemplateDefaults $templateDefaults,
    ) {
    }

    /**
     * @return array{html_path: string, pdf_path: ?string, excel_path: string, csv_path: string}
     */
    public function generate(GeneratedReport $report, array $dataset, array $summary): array
    {
        $report->loadMissing(['client', 'template']);

        $directory = 'dw-reports/' . $report->id;
        Storage::disk('public')->makeDirectory($directory);

        $baseName = Str::slug(($report->client?->company_name ?? 'musteri') . '-' . $report->report_type . '-' . now()->format('Ymd-His'));
        $templateSettings = $this->templateDefaults->settingsFor($report->template, $report->client);
        $templateSections = $this->templateDefaults->sectionsFor($report->template);

        $htmlPath = $directory . '/' . $baseName . '.html';
        $html = view('admin.reports.print.report', compact('report', 'dataset', 'summary', 'templateSettings', 'templateSections'))->render();
        Storage::disk('public')->put($htmlPath, $html);

        $excelPath = $directory . '/' . $baseName . '.xls';
        $excelHtml = view('admin.reports.print.excel', compact('report', 'dataset', 'summary', 'templateSettings', 'templateSections'))->render();
        Storage::disk('public')->put($excelPath, $excelHtml);

        $csvPath = $directory . '/' . $baseName . '.csv';
        Storage::disk('public')->put($csvPath, $this->csvWriter->build($dataset, $summary));

        $pdfPath = null;
        if (class_exists(\Barryvdh\DomPDF\Facade\Pdf::class)) {
            $pdfPath = $directory . '/' . $baseName . '.pdf';
            $absolutePath = Storage::disk('public')->path($pdfPath);
            \Barryvdh\DomPDF\Facade\Pdf::loadHTML($html)->setPaper('a4')->save($absolutePath);
        }

        return [
            'html_path' => $htmlPath,
            'pdf_path' => $pdfPath,
            'excel_path' => $excelPath,
            'csv_path' => $csvPath,
        ];
    }
}
