<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/feca_mailshots_plugin/src/autoload.php';

use FecaMailshots\Application\MailshotRunService;

if (!class_exists('Dompdf\\Dompdf')) {
    fwrite(STDERR, "Dompdf is not available\n");
    exit(1);
}
if (!function_exists('shell_exec') || trim((string) shell_exec('command -v pdftotext 2>/dev/null')) === '') {
    echo "Dompdf unicode symbol test skipped: pdftotext is not available\n";
    exit(0);
}

$service = (new ReflectionClass(MailshotRunService::class))->newInstanceWithoutConstructor();
$method = new ReflectionMethod(MailshotRunService::class, 'renderPdfBytesFromHtml');
$method->setAccessible(true);

$html = <<<'HTML'
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Helvetica, sans-serif; }
</style>
</head>
<body>
<p>✉ advertising@fenedge.co.uk</p>
<p>📞 01954 250082</p>
</body>
</html>
HTML;

$pdfBytes = $method->invoke($service, $html);
if (!is_string($pdfBytes) || strpos($pdfBytes, '%PDF') !== 0) {
    fwrite(STDERR, "Expected rendered PDF bytes\n");
    exit(1);
}

$pdfPath = tempnam(sys_get_temp_dir(), 'feca_dompdf_unicode_');
if (!is_string($pdfPath) || $pdfPath === '') {
    fwrite(STDERR, "Failed to create temporary PDF path\n");
    exit(1);
}
$pdfFile = $pdfPath . '.pdf';
@rename($pdfPath, $pdfFile);

try {
    if (@file_put_contents($pdfFile, $pdfBytes) === false) {
        fwrite(STDERR, "Failed to write temporary PDF\n");
        exit(1);
    }
    $text = (string) shell_exec('pdftotext ' . escapeshellarg($pdfFile) . ' - 2>/dev/null');
    if (strpos($text, '✉ advertising@fenedge.co.uk') === false) {
        fwrite(STDERR, "Expected email symbol in PDF text, got: " . $text . "\n");
        exit(1);
    }
    if (strpos($text, '☎ 01954 250082') === false) {
        fwrite(STDERR, "Expected normalized phone symbol in PDF text, got: " . $text . "\n");
        exit(1);
    }
} finally {
    @unlink($pdfFile);
}

echo "Dompdf unicode symbol regression test passed\n";
