<?php

namespace App\Services\ListinoPrezzi;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use RuntimeException;
use Symfony\Component\Process\Process;

class ListinoPubblicoPdfExporter
{
    public function exportFromHtml(string $html): string
    {
        $chrome = $this->resolveChromePath();
        if ($chrome === null) {
            throw new RuntimeException('Chrome/Edge non trovato: impossibile generare un PDF fedele alla pagina.');
        }

        $dir = storage_path('app/listino_prezzi');
        File::ensureDirectoryExists($dir);

        $token = (string) Str::uuid();
        $htmlPath = $dir.DIRECTORY_SEPARATOR.'listino-'.$token.'.html';
        $pdfPath = $dir.DIRECTORY_SEPARATOR.'listino-'.$token.'.pdf';

        File::put($htmlPath, $html);

        $fileUrl = 'file:///'.str_replace('\\', '/', $htmlPath);

        $process = new Process([
            $chrome,
            '--headless=new',
            '--disable-gpu',
            '--allow-file-access-from-files',
            '--no-pdf-header-footer',
            '--hide-scrollbars',
            '--run-all-compositor-stages-before-draw',
            '--virtual-time-budget=10000',
            // Viewport larga: evita che le media query mobile mettano le card in colonna unica
            '--window-size=1280,2000',
            '--force-device-scale-factor=1',
            '--print-to-pdf='.$pdfPath,
            $fileUrl,
        ]);
        $process->setTimeout(90);
        $process->run();

        File::delete($htmlPath);

        if (! File::exists($pdfPath) || File::size($pdfPath) < 1000) {
            $error = trim($process->getErrorOutput().' '.$process->getOutput());
            throw new RuntimeException('Generazione PDF fallita.'.($error !== '' ? ' '.$error : ''));
        }

        return $pdfPath;
    }

    public function renderPageHtml($listinoPrezzi): string
    {
        $root = rtrim((string) env('LISTINO_PDF_BASE_URL', config('app.url')), '/');
        if ($root !== '') {
            URL::forceRootUrl($root);
        }

        request()->merge(['pdf' => 1]);

        return view('listino_prezzi.pubblico.show', [
            'listino_prezzi' => $listinoPrezzi,
        ])->render();
    }

    private function resolveChromePath(): ?string
    {
        $candidates = array_filter([
            env('CHROME_PATH'),
            'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
            'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
            'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
            'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
            '/usr/bin/google-chrome',
            '/usr/bin/google-chrome-stable',
            '/usr/bin/chromium',
            '/usr/bin/chromium-browser',
            '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
        ]);

        foreach ($candidates as $path) {
            if (is_string($path) && $path !== '' && File::exists($path)) {
                return $path;
            }
        }

        return null;
    }
}
