<?php
declare(strict_types=1);

namespace App\Support;

use Dompdf\Dompdf;
use Dompdf\Options;

final class PdfReportService
{
    public function generate(array $report): string
    {
        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');

        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($this->renderHtml($report));
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return $dompdf->output();
    }

    public function save(array $report): string
    {
        $binary = $this->generate($report);
        $path = $this->pathFor((string) $report['reference']);
        file_put_contents($path, $binary);

        return $path;
    }

    public function existingPath(string $reference): ?string
    {
        $path = $this->pathFor($reference);

        return is_file($path) ? $path : null;
    }

    public function delete(string $reference): void
    {
        $path = $this->pathFor($reference);

        if (is_file($path)) {
            unlink($path);
        }
    }

    private function renderHtml(array $report): string
    {
        $template = BASE_PATH . '/app/Views/pdf/report.php';
        $brandLogoPath = BASE_PATH . '/public/assets/' . ltrim((string) config('brand.logo', ''), '/');
        $brandLogoDataUri = null;

        if (is_file($brandLogoPath)) {
            $contents = file_get_contents($brandLogoPath);
            if ($contents !== false) {
                $extension = strtolower((string) pathinfo($brandLogoPath, PATHINFO_EXTENSION));
                $mimeType = match ($extension) {
                    'png' => 'image/png',
                    'jpg', 'jpeg' => 'image/jpeg',
                    'svg' => 'image/svg+xml',
                    default => 'application/octet-stream',
                };

                $brandLogoDataUri = 'data:' . $mimeType . ';base64,' . base64_encode($contents);
            }
        }

        ob_start();
        require $template;
        return (string) ob_get_clean();
    }

    private function pathFor(string $reference): string
    {
        $safeReference = preg_replace('/[^A-Za-z0-9\-]/', '', $reference) ?: 'report';
        return rtrim((string) config('storage.pdfs'), '/\\') . '/' . $safeReference . '.pdf';
    }
}