<?php

namespace Shm\ShmUtils\Terms;

use Dompdf\Dompdf;
use Dompdf\Options;

class TermsPdf
{
    /**
     * @param list<array{category: ?string, title: string, contentHtml: string}> $entries
     */
    public static function render(string $mainTitle, array $entries): string
    {
        $options = new Options();
        $options->set('isRemoteEnabled', false);
        $options->set('defaultFont', 'DejaVu Sans');

        $dompdf = new Dompdf($options);
        $dompdf->loadHtml(self::buildHtml($mainTitle, $entries), 'UTF-8');
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return $dompdf->output();
    }

    /**
     * @param list<array{category: ?string, title: string, contentHtml: string}> $entries
     */
    private static function buildHtml(string $mainTitle, array $entries): string
    {
        $parts = [
            '<!DOCTYPE html><html><head><meta charset="UTF-8">',
            '<style>',
            'body { font-family: DejaVu Sans, sans-serif; font-size: 11pt; color: #111; line-height: 1.45; }',
            'h1 { font-size: 18pt; margin: 0 0 20px; }',
            '.pdf-doc { margin-bottom: 28px; padding-bottom: 20px; border-bottom: 1px solid #ddd; }',
            '.pdf-doc:last-child { border-bottom: none; }',
            '.pdf-category { font-size: 10pt; color: #555; margin: 0 0 6px; }',
            '.pdf-doc-title { font-size: 14pt; font-weight: bold; margin: 0 0 12px; }',
            '.pdf-content h1, .pdf-content h2, .pdf-content h3 { margin-top: 14px; margin-bottom: 8px; }',
            '.pdf-content p { margin: 0 0 10px; }',
            '.pdf-content ul, .pdf-content ol { margin: 0 0 10px 18px; padding: 0; }',
            '.pdf-content table { border-collapse: collapse; width: 100%; margin-bottom: 10px; }',
            '.pdf-content th, .pdf-content td { border: 1px solid #ccc; padding: 4px 6px; }',
            '</style></head><body>',
            '<h1>', self::escape($mainTitle), '</h1>',
        ];

        foreach ($entries as $entry) {
            $parts[] = '<section class="pdf-doc">';
            if (($entry['category'] ?? null) !== null && $entry['category'] !== '') {
                $parts[] = '<div class="pdf-category">' . self::escape($entry['category']) . '</div>';
            }
            $parts[] = '<div class="pdf-doc-title">' . self::escape($entry['title']) . '</div>';
            $parts[] = '<div class="pdf-content">' . ($entry['contentHtml'] ?? '') . '</div>';
            $parts[] = '</section>';
        }

        $parts[] = '</body></html>';

        return implode('', $parts);
    }

    private static function escape(string $value): string
    {
        return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}
