<?php
declare(strict_types=1);

/**
 * Exam PDF entry points for curated `exam_papers` exports.
 *
 * The layout itself now lives in ../templates/ — this file only adapts the
 * flat question rows into the normalized exam document and hands it to the
 * school's chosen template. Public signatures are unchanged so callers
 * (ajax/export_pdf.php) need no modification.
 */

require_once dirname(__DIR__, 2) . '/vendor/autoload.php';
require_once dirname(__DIR__) . '/lib/exam_document.php';
require_once dirname(__DIR__) . '/templates/registry.php';

/**
 * School identity + chosen exam template, read from the settings table.
 * Falls back to safe defaults when no DB connection is available.
 */
function examPdfSchoolInfo(): array
{
    $conn = function_exists('getDBConnection') ? getDBConnection() : null;
    if ($conn instanceof mysqli) {
        return examSchoolInfo($conn);
    }
    return [
        'name'     => 'SCHOOL NAME',
        'address'  => '',
        'phone'    => '',
        'email'    => '',
        'logo'     => '',
        'template' => 'ges_standard',
    ];
}

function generateExamPDF(array $questions, array $config, string $exportDir): string
{
    $school = examPdfSchoolInfo();
    $doc    = examDocFromPaper($questions, $config, false, $school);

    return renderExamPdfToFile($doc, $school['template'], $exportDir, 'exam_');
}

function generateAnswerKeyPDF(array $questions, array $config, string $exportDir): string
{
    $school = examPdfSchoolInfo();
    $doc    = examDocFromPaper($questions, $config, true, $school);

    return renderExamPdfToFile($doc, $school['template'], $exportDir, 'answer_key_');
}
