<?php
declare(strict_types=1);

/**
 * Exam paper template registry.
 *
 * Maps a template key (stored in settings['exam_template']) to its label,
 * description and renderer. Consumed by the Settings picker and by both PDF
 * export paths.
 *
 * Every renderer has the signature:
 *     function (array $doc): string     // $doc = normalized exam document
 * and returns mPDF-ready HTML.
 */

require_once __DIR__ . '/ges_standard.php';
require_once __DIR__ . '/ges_compact.php';
require_once __DIR__ . '/classic.php';

function examTemplateRegistry(): array
{
    return [
        'ges_standard' => [
            'label'       => 'GES Standard',
            'description' => 'Official Ghanaian examination format: crested letterhead, paper title block, candidate particulars, "For Examiner\'s Use Only" grid, boxed instructions and "Turn over" page footers.',
            'render'      => 'renderExam_ges_standard',
        ],
        'ges_compact' => [
            'label'       => 'GES Compact',
            'description' => 'The same official GES format at reduced type and line spacing — saves paper on long papers and mock exams.',
            'render'      => 'renderExam_ges_compact',
        ],
        'classic' => [
            'label'       => 'Classic',
            'description' => 'The plain original generator layout: simple centred heading, info table and numbered questions. Now includes the school crest.',
            'render'      => 'renderExam_classic',
        ],
    ];
}

/**
 * Return the renderer callable for a template key, falling back to GES Standard.
 */
function resolveExamRenderer(?string $key): callable
{
    $registry = examTemplateRegistry();
    $key = $key !== null && isset($registry[$key]) ? $key : 'ges_standard';
    return $registry[$key]['render'];
}

/**
 * Render a normalized exam document to a PDF file via mPDF.
 *
 * @return string The filename written into $exportDir.
 */
function renderExamPdfToFile(array $doc, ?string $templateKey, string $exportDir, string $prefix): string
{
    $mpdf = new \Mpdf\Mpdf([
        'format'        => 'A4',
        'margin_left'   => 15,
        'margin_right'  => 15,
        'margin_top'    => 14,
        'margin_bottom' => 16,
    ]);
    $mpdf->SetTitle((string) $doc['title']);

    $render = resolveExamRenderer($templateKey);
    $mpdf->WriteHTML($render($doc));

    $filename = $prefix . preg_replace('/[^a-z0-9]/i', '_', (string) $doc['title']) . '_' . date('Ymd_His') . '.pdf';
    $path = rtrim($exportDir, '/\\') . DIRECTORY_SEPARATOR . $filename;
    $mpdf->Output($path, 'F');

    return $filename;
}
