<?php

namespace App\Services;

use App\Models\FeasibilityReport;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;

class ReportGeneratorService
{
    /**
     * Generate a PDF for the given report and return the PDF content as a string.
     */
    public function generate(FeasibilityReport $report): string
    {
        $report->load(['state', 'city', 'zone', 'zoneRule']);

        $pdf = Pdf::loadView('reports.feasibility-pdf', compact('report'))
            ->setPaper('a4', 'portrait')
            ->setOptions([
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled'      => false,
                'defaultFont'          => 'DejaVu Sans',
                'dpi'                  => 150,
            ]);

        return $pdf->output();
    }

    /**
     * Generate and store PDF to disk, returning its storage path.
     */
    public function generateAndStore(FeasibilityReport $report): string
    {
        $content  = $this->generate($report);
        $filename = 'feasibility-reports/report-'.$report->id.'-'.time().'.pdf';

        Storage::disk('public')->put($filename, $content);

        $report->update(['report_pdf_path' => $filename]);

        return $filename;
    }

    /**
     * Stream PDF directly to browser.
     */
    public function stream(FeasibilityReport $report): \Illuminate\Http\Response
    {
        $report->load(['state', 'city', 'zone', 'zoneRule']);

        $pdf = Pdf::loadView('reports.feasibility-pdf', compact('report'))
            ->setPaper('a4', 'portrait')
            ->setOptions([
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled'      => false,
                'defaultFont'          => 'DejaVu Sans',
                'dpi'                  => 150,
            ]);

        $filename = 'LandFeasibility-Report-'.$report->id.'.pdf';

        return $pdf->stream($filename);
    }

    /**
     * Download PDF as attachment.
     */
    public function download(FeasibilityReport $report): \Illuminate\Http\Response
    {
        $report->load(['state', 'city', 'zone', 'zoneRule']);

        $pdf = Pdf::loadView('reports.feasibility-pdf', compact('report'))
            ->setPaper('a4', 'portrait')
            ->setOptions([
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled'      => false,
                'defaultFont'          => 'DejaVu Sans',
                'dpi'                  => 150,
            ]);

        $filename = 'LandFeasibility-Report-'.$report->id.'.pdf';

        return $pdf->download($filename);
    }
}
