<?php
require_once 'config/constants.php';
require_once 'services/MessageService.php';

echo "Testing PDF Generation...\n";

$service = new MessageService(null);

$templateDir = __DIR__ . '/uploads/templates/';
$outputDir = __DIR__ . '/uploads/temp_pdfs/';

if (!file_exists($outputDir)) {
    mkdir($outputDir, 0777, true);
}

// Pick the first jpeg file found in templates
$files = glob($templateDir . '*.jpeg');
if (empty($files)) {
    $files = glob($templateDir . '*.jpg');
}

if (empty($files)) {
    die("No template file found in $templateDir. Please upload a jpeg/jpg file to test.\n");
}

$templatePath = $files[0];
echo "Using template: $templatePath\n";

$outputPath = $outputDir . 'test_output_' . time() . '.pdf';
echo "Output path: $outputPath\n";

$contactName = "John Doe";

$result = $service->generateBirthdayPdf($templatePath, $contactName, $outputPath);

if ($result) {
    echo "PDF Generation Successful!\n";
    echo "Filesize: " . filesize($outputPath) . " bytes\n";

    // Check if file is actually a PDF (magic number)
    $handle = fopen($outputPath, 'rb');
    $header = fread($handle, 4);
    fclose($handle);

    if ($header === '%PDF') {
        echo "Valid PDF header found.\n";
    } else {
        echo "INVALID PDF header: " . bin2hex($header) . "\n";
    }

} else {
    echo "PDF Generation FAILED.\n";
}
?>
