<?php
declare(strict_types=1);

/**
 * Classic — the plain, lightly-styled exam layout the generator shipped with,
 * kept for continuity and now including the school crest in the header.
 *
 * Simple centred heading, an info table, a boxed instruction block and plainly
 * numbered questions. No candidate particulars or examiner grid.
 */
function renderExam_classic(array $doc): string
{
    $isKey  = !empty($doc['is_key']);
    $school = $doc['school'];
    $e = static fn($v): string => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

    $html = '<htmlpagefooter name="cl_ftr">'
          . '<table width="100%" style="border-top:0.5pt solid #ddd;font-size:8pt;color:#777;padding-top:3px;"><tr>'
          . '<td align="left">' . $e($school['name']) . '</td>'
          . '<td align="right">Page {PAGENO} of {nbpg}</td>'
          . '</tr></table></htmlpagefooter>'
          . '<sethtmlpagefooter name="cl_ftr" value="on" />';

    $html .= '<style>
      body { font-family: "Times New Roman", Times, serif; font-size: 12pt; line-height: 1.45; }
      .hdr { text-align: center; margin-bottom: 10px; }
      .sname { font-size: 20px; font-weight: bold; }
      .saddr { font-size: 10pt; color: #666; }
      .ptitle { font-size: 15pt; font-weight: bold; margin-top: 8px; }
      .info { width: 100%; border-collapse: collapse; margin: 12px 0; font-size: 10.5pt; }
      .info td { padding: 5px; border: 1px solid #ddd; }
      .instructions { background: #f8f9fa; border-left: 4px solid #3498db; padding: 10px 12px; margin: 12px 0; font-size: 10.5pt; }
      .section-title { font-size: 12pt; font-weight: bold; background: #34495e; color: #fff; padding: 7px 11px; margin: 16px 0 9px; }
      .question { margin: 12px 0; }
      .qnum { font-weight: bold; }
      .marks { float: right; color: #b8620a; font-weight: bold; font-size: 10pt; }
      .options { margin-left: 32px; margin-top: 5px; }
      .option { margin: 2px 0; }
      .passage { background: #eef2f5; padding: 10px; margin: 8px 0; font-size: 10.5pt; }
      .answer-line { border-bottom: 0.7pt dashed #999; height: 19px; margin: 3px 0; }
      .teacher-block { background: #fff8e1; border: 1pt solid #f0d58c; padding: 8px 10px; margin-top: 5px; font-size: 10.5pt; }
      .footer { margin-top: 30px; text-align: center; font-size: 10pt; color: #777; border-top: 1px solid #ddd; padding-top: 10px; }
      svg { display: block !important; }
      table.mt { width:100%; border-collapse:collapse; margin-top:5px; font-size:10.5pt; }
      table.mt td { vertical-align: top; padding-right: 10px; }
    </style>';

    // Header
    $html .= '<div class="hdr">';
    if (!empty($school['logo'])) {
        $html .= '<img src="' . $school['logo'] . '" width="60" style="margin-bottom:4px;">';
    }
    $html .= '<div class="sname">' . $e($school['name']) . '</div>';
    if (trim((string) $school['address']) !== '') {
        $html .= '<div class="saddr">' . $e($school['address']) . '</div>';
    }
    $contact = array_filter([$school['phone'], $school['email']]);
    if ($contact) {
        $html .= '<div class="saddr">' . implode(' | ', array_map($e, $contact)) . '</div>';
    }
    $html .= '<hr style="margin:12px 0">';
    $html .= '<div class="ptitle">' . $e($doc['title']) . ($isKey ? ' &mdash; Answer Key' : '') . '</div>';
    $html .= '</div>';

    // Info table
    $html .= '<table class="info"><tr>'
          . '<td><b>Class:</b> ' . $e($doc['class_name']) . '</td>'
          . '<td><b>Subject:</b> ' . $e($doc['subject_name']) . '</td>'
          . '<td><b>Term:</b> ' . $e($doc['term']) . '</td>'
          . '</tr><tr>'
          . '<td><b>Date:</b> _______________</td>'
          . '<td><b>Time Allowed:</b> ' . (int) $doc['duration_minutes'] . ' minutes</td>'
          . '<td><b>Total Marks:</b> ' . (int) $doc['total_marks'] . '</td>'
          . '</tr></table>';

    $instr = trim((string) $doc['instructions']);
    if ($instr !== '') {
        $html .= '<div class="instructions"><b>INSTRUCTIONS TO CANDIDATES</b><br>' . nl2br($e($instr)) . '</div>';
    }

    foreach ($doc['sections'] as $section) {
        $marks = (int) $section['marks'];
        $html .= '<div class="section-title">Section ' . $e($section['letter']) . ' &mdash; ' . $e($section['label'])
               . ' <span style="float:right;">[' . $marks . ' marks]</span></div>';
        if (trim((string) $section['instruction']) !== '') {
            $html .= '<div style="font-style:italic;font-size:10.5pt;margin-bottom:7px;">' . $e($section['instruction']) . '</div>';
        }
        if (trim((string) $section['passage']) !== '') {
            $html .= '<div class="passage"><b>Passage:</b><br>' . nl2br($e($section['passage'])) . '</div>';
        }

        foreach ($section['questions'] as $q) {
            $type = $section['type'];
            $marksQ = (int) $q['marks'];
            $html .= '<div class="question"><span class="marks">[' . $marksQ . ' mark' . ($marksQ !== 1 ? 's' : '') . ']</span>'
                   . '<span class="qnum">' . (int) $q['number'] . '.</span> ' . $e($q['text']);

            if ($q['diagram_html'] !== '') {
                $html .= $q['diagram_html'];
            }
            if (trim((string) ($q['passage'] ?? '')) !== '') {
                $html .= '<div class="passage">' . nl2br($e($q['passage'])) . '</div>';
            }

            if ($type === 'mcq' && $q['options']) {
                $html .= '<div class="options">';
                foreach ($q['options'] as $letter => $text) {
                    $html .= '<div class="option">' . $e($letter) . '. ' . $e($text) . '</div>';
                }
                $html .= '</div>';
            } elseif ($type === 'true_false') {
                $html .= '<div class="options">True / False &nbsp;&nbsp; ( ____________ )</div>';
            } elseif ($type === 'matching' && is_array($q['matching'])) {
                $html .= '<table class="mt"><tr><td width="50%"><b>Column A</b>';
                foreach ($q['matching']['left'] as $i => $lt) {
                    $html .= '<div class="option">' . ($i + 1) . '. ' . $e($lt) . ' ( ____ )</div>';
                }
                $html .= '</td><td width="50%"><b>Column B</b>';
                foreach ($q['matching']['right'] as $r) {
                    $html .= '<div class="option">' . $e($r['letter']) . '. ' . $e($r['text']) . '</div>';
                }
                $html .= '</td></tr></table>';
            } elseif ($type === 'comprehension') {
                foreach ($q['subs'] as $si => $sq) {
                    $sm = (int) $sq['marks'];
                    $html .= '<div style="margin:5px 0 2px 20px;">(' . chr(97 + ($si % 26)) . ') ' . $e($sq['text']) . ' <em>(' . $sm . ' marks)</em></div>';
                    if (!$isKey) {
                        for ($k = 0, $lines = max(2, $sm * 2); $k < $lines; $k++) {
                            $html .= '<div class="answer-line"></div>';
                        }
                    }
                }
            } elseif (!$isKey && ($type === 'theory' || $type === 'fill_blank')) {
                for ($i = 0, $lines = $type === 'fill_blank' ? 1 : max(3, $marksQ * 2); $i < $lines; $i++) {
                    $html .= '<div class="answer-line"></div>';
                }
            }

            if ($isKey) {
                $bits = [];
                if ($type === 'mcq' && $q['correct'] !== '') {
                    $letter = strtoupper($q['correct']);
                    $bits[] = '<b>Correct Option:</b> ' . $e($letter) . (isset($q['options'][$letter]) ? '. ' . $e($q['options'][$letter]) : '');
                }
                if ($type === 'true_false' && $q['correct'] !== '') {
                    $bits[] = '<b>Answer:</b> ' . $e($q['correct']);
                }
                if ($type === 'matching' && is_array($q['matching'])) {
                    $pairs = [];
                    foreach ($q['matching']['answer'] as $num => $letter) {
                        $pairs[] = $num . '&rarr;' . $e($letter);
                    }
                    if ($pairs) $bits[] = '<b>Matches:</b> ' . implode(', ', $pairs);
                }
                if ($type === 'comprehension') {
                    foreach ($q['subs'] as $si => $sq) {
                        if (trim((string) $sq['model_answer']) === '') continue;
                        $bits[] = '(' . chr(97 + ($si % 26)) . ') ' . $e($sq['model_answer']);
                    }
                } elseif (trim((string) $q['model_answer']) !== '') {
                    $bits[] = '<b>Model Answer:</b> ' . nl2br($e($q['model_answer']));
                }
                if ($q['marking_guide']) {
                    $li = '';
                    foreach ($q['marking_guide'] as $p) $li .= '<li>' . $e($p) . '</li>';
                    $bits[] = '<b>Marking Guide:</b><ul style="margin:2px 0 0 16px;padding:0;">' . $li . '</ul>';
                }
                if ($bits) {
                    $html .= '<div class="teacher-block">' . implode('<br>', $bits) . '</div>';
                }
            }

            $html .= '</div>';
        }
    }

    $html .= '<div class="footer"><b>END OF ' . ($isKey ? 'ANSWER KEY' : 'EXAMINATION') . '</b><br>'
           . 'Generated on: ' . date('F j, Y') . '<br>' . $e($school['name']) . '</div>';

    return $html;
}
