<?php
/**
 * GES Standard terminal report.
 *
 * Formal Ghana Education Service report-card format, sharing the design
 * language of the GES exam papers: crested letterhead closed by the
 * heavy/hairline rule pair, uppercase spaced section labels, boxed particulars,
 * per-subject position, and a Key to Grades panel beside the school stamp.
 *
 * Table-based throughout so it renders identically in the browser ('print')
 * and in DOMPDF ('pdf').
 */

function renderReport_ges_standard(array $data, string $mode = 'print'): string
{
    $student       = $data['student'];
    $classSize     = (int) $data['classSize'];
    $subjects      = $data['subjects'];
    $scores        = $data['scores'];
    $stats         = $data['subjectStats'] ?? [];
    $totalMarks    = $data['totalMarks'];
    $average       = $data['average'] ?? 0;
    $academicYear  = $data['academicYear'];
    $termFormatted = $data['termFormatted'];

    $e = static fn($v): string => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

    $logo = reportImageSrc($data['logoPath'], $mode);
    $sig = static function (string $key) use ($data, $mode): string {
        $src = reportImageSrc($data[$key], $mode);
        return $src
            ? '<img src="' . $src . '" style="max-height:38px;max-width:130px;display:block;margin:0 auto 2px;">'
            : '<div style="height:38px;"></div>';
    };

    $schoolName  = strtoupper($data['schoolName']);
    $studentName = strtoupper($student['first_name'] . ' ' . $student['last_name']);

    // Overall grade from the configured boundaries, using the average.
    $overallGrade = '';
    $overallRemark = '';
    foreach ($data['gradeBoundaries'] as $gb) {
        if ($average >= (float) $gb['min_score'] && $average <= (float) $gb['max_score']) {
            $overallGrade  = (string) $gb['grade'];
            $overallRemark = (string) $gb['remark'];
            break;
        }
    }

    $css = '
    * { margin:0; padding:0; box-sizing:border-box; }
    body { font-family:"Times New Roman", Times, serif; font-size:9.5pt; color:#000; background:#fff; }
    .pg { width:210mm; max-width:210mm; margin:0 auto; padding:9mm 9mm 7mm; background:#fff; }
    table { border-collapse:collapse; }
    .lh { width:100%; }
    .lh .lc { width:74px; vertical-align:middle; }
    .lh .lc img { width:66px; height:66px; }
    .lh .ic { text-align:center; vertical-align:middle; }
    .sn { font-size:16pt; font-weight:bold; text-transform:uppercase; letter-spacing:1px; line-height:1.1; }
    .sa { font-size:8pt; margin-top:2px; }
    .rule-a { border-bottom:2.4pt solid #0E5236; }
    .rule-b { border-bottom:0.8pt solid #0E5236; margin-top:2px; margin-bottom:7px; }
    .ttl { background:#0E5236; color:#fff; text-align:center; font-size:11.5pt; font-weight:bold;
           text-transform:uppercase; letter-spacing:3px; padding:5px 8px; }
    .ttl-sub { text-align:center; font-size:8pt; text-transform:uppercase; letter-spacing:1.2px;
               padding:3px 0 7px; color:#333; }
    .lbl { font-size:6.8pt; font-weight:bold; text-transform:uppercase; letter-spacing:0.5px; color:#0E5236; }
    .val { font-size:10pt; font-weight:bold; color:#000; margin-top:1px; }
    .part { width:100%; border:1pt solid #0E5236; margin-bottom:6px; }
    .part td { border:0.6pt solid #9ab5a8; padding:4px 7px; vertical-align:top; }
    .rt { width:100%; margin-bottom:6px; }
    .rt th { background:#0E5236; color:#fff; font-size:7pt; text-transform:uppercase; letter-spacing:0.3px;
             padding:5px 3px; border:0.7pt solid #0a3d28; text-align:center; font-weight:bold; }
    .rt td { border:0.6pt solid #b5b5b5; padding:3.5px 4px; text-align:center; font-size:9pt; }
    .rt td.sj { text-align:left; padding-left:7px; font-weight:500; }
    .rt tr.tot td { background:#dbe8e1; font-weight:bold; border-top:1.6pt solid #0E5236; }
    .ga { background:#cdeedd; font-weight:bold; }
    .gb { background:#d7e6f7; font-weight:bold; }
    .gc { background:#fdf0b8; font-weight:bold; }
    .gd { background:#fde0b0; }
    .ge { background:#fbd2d5; }
    .gw { background:#e2e2e2; }
    .sum { width:100%; margin-bottom:6px; }
    .sum td { border:1pt solid #0E5236; padding:5px 7px; text-align:center; background:#f2f7f4; }
    .cf { width:100%; margin-bottom:6px; }
    .cf td { border:0.6pt solid #9ab5a8; padding:4px 7px; }
    .rk { border:1pt solid #0E5236; margin-bottom:6px; }
    .rkh { background:#e4efe9; padding:3px 7px; font-size:7pt; font-weight:bold; text-transform:uppercase;
           letter-spacing:0.8px; color:#0E5236; border-bottom:0.7pt solid #0E5236; }
    .rkb { padding:5px 7px; font-size:9.5pt; min-height:22px; }
    .ruled { border-bottom:0.6pt dotted #777; height:14px; margin-top:3px; }
    .sig { width:100%; margin-bottom:6px; }
    .sig td { text-align:center; padding:3px 6px; vertical-align:bottom; width:33.33%; }
    .sig .sl { font-size:6.8pt; font-weight:bold; text-transform:uppercase; letter-spacing:0.5px;
               border-top:0.8pt solid #000; padding-top:2px; display:block; margin-top:1px; }
    .ftr { width:100%; }
    .ftr .stamp { width:36%; border:1pt solid #9ab5a8; padding:6px; text-align:center;
                  background:#fafcfb; vertical-align:top; }
    .ftr .gap { width:4%; }
    .ftr .keyc { vertical-align:top; }
    .stl { font-size:7pt; font-weight:bold; text-transform:uppercase; letter-spacing:0.8px; color:#0E5236; display:block; }
    .ssp { height:42px; border-bottom:0.8pt dashed #888; margin:5px 10px 3px; }
    .ssb { font-size:6.5pt; color:#777; font-style:italic; display:block; }
    .keyt-h { font-size:7pt; font-weight:bold; text-transform:uppercase; letter-spacing:0.8px; color:#0E5236;
              text-align:center; background:#e4efe9; border:0.7pt solid #9ab5a8; border-bottom:none; padding:3px; }
    .keyt { width:100%; }
    .keyt th { background:#f0f5f2; font-size:6.8pt; text-transform:uppercase; padding:2.5px 4px;
               border:0.6pt solid #9ab5a8; text-align:center; font-weight:bold; }
    .keyt td { border:0.6pt solid #c2c2c2; padding:2px 4px; text-align:center; font-size:8pt; }
    .endbar { background:#0E5236; color:#fff; text-align:center; font-size:7pt; text-transform:uppercase;
              letter-spacing:1.5px; padding:4px; margin-top:7px; }
    @page { margin:0.5cm; size:A4; }
    @media print { body { padding:0; } .pg { width:100%; padding:0; } }
    ';

    $h = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Terminal Report - '
       . $e($student['first_name'] . ' ' . $student['last_name']) . '</title><style>' . $css . '</style></head><body><div class="pg">';

    // ── Letterhead ───────────────────────────────────────────────────────
    $h .= '<table class="lh"><tr>';
    if ($logo) $h .= '<td class="lc"><img src="' . $logo . '"></td>';
    $h .= '<td class="ic"><div class="sn">' . $e($schoolName) . '</div>';
    if (trim((string) $data['schoolAddress']) !== '') {
        $h .= '<div class="sa">' . $e(strtoupper($data['schoolAddress'])) . '</div>';
    }
    $contact = array_filter([$data['schoolPhone'], $data['schoolEmail']]);
    if ($contact) $h .= '<div class="sa">' . implode(' &nbsp;|&nbsp; ', array_map($e, $contact)) . '</div>';
    $h .= '</td>';
    if ($logo) $h .= '<td class="lc"></td>';
    $h .= '</tr></table>';
    $h .= '<div class="rule-a"></div><div class="rule-b"></div>';

    // ── Title ────────────────────────────────────────────────────────────
    $h .= '<div class="ttl">Terminal Report</div>';
    $h .= '<div class="ttl-sub">Term ' . $e($termFormatted) . ' &nbsp;&bull;&nbsp; ' . $e($academicYear) . ' Academic Year</div>';

    // ── Candidate particulars ────────────────────────────────────────────
    $attTotal = (int) ($data['attendanceTotal'] ?? 0);
    $attText  = $e((string) $data['attendance']) . ($attTotal > 0 ? ' out of ' . $attTotal . ' days' : ' days present');

    $sexAge = trim(($data['sex'] ?? '') . (($data['sex'] ?? '') !== '' && ($data['age'] ?? '') !== '' ? ' / ' : '')
            . (($data['age'] ?? '') !== '' ? $data['age'] . ' yrs' : ''));

    $h .= '<table class="part"><tr>'
        . '<td width="40%"><div class="lbl">Name of Pupil</div><div class="val">' . $e($studentName) . '</div></td>'
        . '<td width="20%"><div class="lbl">Class</div><div class="val">' . $e($student['class']) . '</div></td>'
        . '<td width="20%"><div class="lbl">Admission No.</div><div class="val">' . ($data['admissionNo'] !== '' ? $e($data['admissionNo']) : '&mdash;') . '</div></td>'
        . '<td width="20%"><div class="lbl">Sex / Age</div><div class="val">' . ($sexAge !== '' ? $e($sexAge) : '&mdash;') . '</div></td>'
        . '</tr><tr>'
        . '<td><div class="lbl">Attendance</div><div class="val">' . $attText . '</div></td>'
        . '<td><div class="lbl">No. on Roll</div><div class="val">' . $classSize . '</div></td>'
        . '<td><div class="lbl">Position in Class</div><div class="val">' . $e($data['positionLabel']) . ' of ' . $classSize . '</div></td>'
        . '<td><div class="lbl">Vacation / Re-opening</div><div class="val">' . date('d M Y', strtotime($data['closingDate']))
        . ' &ndash; ' . date('d M Y', strtotime($data['reopeningDate'])) . '</div></td>'
        . '</tr></table>';

    // ── Subject results ──────────────────────────────────────────────────
    $h .= '<table class="rt"><thead><tr>'
        . '<th style="width:26%;text-align:left;padding-left:7px;">Subject</th>'
        . '<th style="width:11%;">Class Score (50%)</th>'
        . '<th style="width:11%;">Exam Score (50%)</th>'
        . '<th style="width:9%;">Total (100%)</th>'
        . '<th style="width:7%;">Grade</th>'
        . '<th style="width:8%;">Pos. in Subj.</th>'
        . '<th style="width:9%;">Class Avg.</th>'
        . '<th>Remarks</th>'
        . '</tr></thead><tbody>';

    foreach ($subjects as $subject) {
        $sid   = $subject['subject_id'];
        $score = $scores[$sid] ?? null;
        $st    = $stats[$sid] ?? null;

        $classScore = $score && $score['class_score'] !== null ? (string) round((float) $score['class_score']) : '&ndash;';
        $examScore  = $score && $score['exam_score']  !== null ? (string) round((float) $score['exam_score'])  : '&ndash;';
        $totalScore = $score && $score['total_score'] !== null ? (string) round((float) $score['total_score']) : '&ndash;';
        $grade      = $score ? strtoupper((string) $score['grade'])  : '&ndash;';
        $remark     = $score ? strtoupper((string) $score['remark']) : '';
        $gCls       = match ($grade) { 'A' => 'ga', 'B' => 'gb', 'C' => 'gc', 'D' => 'gd', 'E' => 'ge', default => 'gw' };

        $subjPos = ($st && $st['position'] !== null) ? getPositionSuffix((int) $st['position']) : '&ndash;';
        $subjAvg = $st ? (string) round((float) $st['average']) : '&ndash;';

        $h .= '<tr>'
            . '<td class="sj">' . $e(strtoupper($subject['subject_name'])) . '</td>'
            . '<td>' . $classScore . '</td>'
            . '<td>' . $examScore . '</td>'
            . '<td><strong>' . $totalScore . '</strong></td>'
            . '<td class="' . $gCls . '">' . $grade . '</td>'
            . '<td>' . $subjPos . '</td>'
            . '<td>' . $subjAvg . '</td>'
            . '<td>' . $e($remark) . '</td>'
            . '</tr>';
    }

    $h .= '<tr class="tot"><td class="sj" colspan="3" style="text-align:right;padding-right:10px;">AGGREGATE TOTAL</td>'
        . '<td>' . round((float) $totalMarks) . '</td><td colspan="4"></td></tr>';
    $h .= '</tbody></table>';

    // ── Summary strip ────────────────────────────────────────────────────
    $h .= '<table class="sum"><tr>'
        . '<td width="25%"><div class="lbl">Aggregate Total</div><div class="val">' . round((float) $totalMarks) . '</div></td>'
        . '<td width="25%"><div class="lbl">Average Score</div><div class="val">' . number_format((float) $average, 1) . '%</div></td>'
        . '<td width="25%"><div class="lbl">Overall Position</div><div class="val">' . $e($data['positionLabel']) . ' of ' . $classSize . '</div></td>'
        . '<td width="25%"><div class="lbl">Overall Grade</div><div class="val">' . ($overallGrade !== '' ? $e($overallGrade) . ' &mdash; ' . $e($overallRemark) : '&mdash;') . '</div></td>'
        . '</tr></table>';

    // ── Conduct / attitude ───────────────────────────────────────────────
    $h .= '<table class="cf"><tr>'
        . '<td width="33%"><div class="lbl">Conduct</div><div class="val">' . $e((string) $data['conduct']) . '</div></td>'
        . '<td width="34%"><div class="lbl">Interest / Attitude</div><div class="val">' . $e((string) $data['interest']) . '</div></td>'
        . '<td width="33%"><div class="lbl">Promoted To</div><div class="val">' . $e((string) $data['promotedTo']) . '</div></td>'
        . '</tr></table>';

    // ── Remarks ──────────────────────────────────────────────────────────
    $h .= '<div class="rk"><div class="rkh">Class Teacher&rsquo;s Remarks</div>'
        . '<div class="rkb">' . $e((string) $data['teacherRemark']) . '</div></div>';

    $headRemark = trim((string) ($data['headteacherRemark'] ?? ''));
    $h .= '<div class="rk"><div class="rkh">Head Teacher&rsquo;s Remarks</div>'
        . '<div class="rkb">'
        . ($headRemark !== '' ? $e($headRemark) : '<div class="ruled"></div><div class="ruled"></div>')
        . '</div></div>';

    // ── Signatures ───────────────────────────────────────────────────────
    $h .= '<table class="sig"><tr>'
        . '<td>' . $sig('classTeacherSignature') . '<span class="sl">Class Teacher</span></td>'
        . '<td>' . $sig('headteacherSignature') . '<span class="sl">Head Teacher</span></td>'
        . '<td>' . $sig('directorSignature') . '<span class="sl">Proprietor / Director</span></td>'
        . '</tr></table>';

    // ── Stamp + Key to Grades ────────────────────────────────────────────
    $keyRows = '';
    foreach ($data['gradeBoundaries'] as $gb) {
        $mx = (int) $gb['max_score'];
        $mn = (int) $gb['min_score'];
        $range = $mn === 0 ? $mx . ' &amp; below' : $mn . ' &ndash; ' . $mx;
        $keyRows .= '<tr><td>' . $range . '</td><td><strong>' . $e($gb['grade']) . '</strong></td><td>' . $e($gb['remark']) . '</td></tr>';
    }

    $stampSrc = reportImageSrc((string) ($data['schoolStamp'] ?? ''), $mode);
    $stampBody = $stampSrc
        ? '<img src="' . $stampSrc . '" style="max-height:46px;max-width:150px;display:block;margin:5px auto 3px;">'
        : '<div class="ssp"></div>';

    $h .= '<table class="ftr"><tr>'
        . '<td class="stamp"><span class="stl">School Stamp</span>' . $stampBody . '<span class="ssb">Valid only when stamped</span></td>'
        . '<td class="gap"></td>'
        . '<td class="keyc"><div class="keyt-h">Key to Grades</div>'
        . '<table class="keyt"><thead><tr><th>Mark Range</th><th>Grade</th><th>Interpretation</th></tr></thead>'
        . '<tbody>' . $keyRows . '</tbody></table></td>'
        . '</tr></table>';

    $h .= '<div class="endbar">' . $e($schoolName) . ' &nbsp;&mdash;&nbsp; Confidential &nbsp;&mdash;&nbsp; ' . $e($academicYear) . '</div>';

    $h .= '</div></body></html>';

    return $h;
}
