<?php
/**
 * Modern terminal report template.
 *
 * Navy-accented, professionally styled design. Uses table-based layout so it
 * renders identically in the browser (print) and in DOMPDF (pdf).
 */

function renderReport_modern(array $data, string $mode = 'print'): string
{
    $student       = $data['student'];
    $classSize     = $data['classSize'];
    $subjects      = $data['subjects'];
    $scores        = $data['scores'];
    $totalMarks    = $data['totalMarks'];
    $academic_year = $data['academicYear'];
    $termFormatted = $data['termFormatted'];

    $logo = reportImageSrc($data['logoPath'], $mode);
    $sigFallback = '<div style="border-bottom:1px solid #888;height:30px;margin-bottom:5px;"></div>';
    $sig = function (string $key) use ($data, $mode, $sigFallback): string {
        $src = reportImageSrc($data[$key], $mode);
        return $src ? '<img src="' . $src . '" style="max-height:40px;max-width:140px;display:block;margin:0 auto 5px;">' : $sigFallback;
    };

    $schoolName = htmlspecialchars($data['schoolName']);

    // Grade rows
    $gradeRowsHtml = '';
    foreach ($data['gradeBoundaries'] as $gb) {
        $gbMax = (int) $gb['max_score'];
        $gbMin = (int) $gb['min_score'];
        $gbRange = $gbMin === 0 ? $gbMax . ' &amp; Below' : $gbMax . '-' . $gbMin;
        $gradeRowsHtml .= '<tr><td>' . $gbRange . '</td><td>' . htmlspecialchars($gb['grade']) . '</td><td>' . htmlspecialchars($gb['remark']) . '</td></tr>';
    }

    $css = '*{margin:0;padding:0;box-sizing:border-box;}'
        . 'body{font-family:Arial,sans-serif;font-size:10px;color:#111;background:#fff;}'
        . 'table{border-collapse:collapse;}'
        . '.pg{padding:8px;max-width:210mm;margin:0 auto;}'
        . '.ht{width:100%;}'
        . '.ht .lc{width:72px;vertical-align:middle;padding-right:8px;}'
        . '.ht .lc img{width:65px;height:65px;}'
        . '.ht .ic{vertical-align:middle;text-align:center;}'
        . '.sn{font-size:16px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.5px;}'
        . '.sa{font-size:8.5px;color:#555;margin-top:2px;}'
        . '.sc{font-size:8px;color:#666;margin-top:1px;}'
        . '.dv{width:100%;margin:6px 0;}'
        . '.dv td{background:#1e3a5f;height:3px;padding:0;font-size:0;line-height:0;}'
        . '.tb{background:#1e3a5f;color:#fff;text-align:center;font-size:12px;font-weight:bold;letter-spacing:3px;padding:7px 10px;margin-bottom:7px;}'
        . '.it{width:100%;margin-bottom:5px;}'
        . '.it td{border:1px solid #b0c4de;padding:5px 9px;}'
        . '.il{font-size:7.5px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.3px;}'
        . '.iv{font-size:11px;font-weight:600;color:#000;margin-top:2px;}'
        . '.rt{width:100%;margin-bottom:8px;}'
        . '.rt th{background:#1e3a5f;color:#fff;font-size:8px;text-transform:uppercase;padding:5px 4px;border:1px solid #152d4a;text-align:center;font-weight:bold;}'
        . '.rt td{border:1px solid #ccc;padding:4px;text-align:center;font-size:9.5px;}'
        . '.rt .sj{text-align:left;padding-left:8px;font-weight:500;}'
        . '.trt td{background:#dce8f5;font-weight:bold;border-top:2px solid #1e3a5f;}'
        . '.ga{background:#c3f0d4;color:#0d5c2e;font-weight:bold;}'
        . '.gb{background:#c3dcf8;color:#0a3466;font-weight:bold;}'
        . '.gc{background:#fff0b0;color:#705000;font-weight:bold;}'
        . '.gd{background:#ffdea0;color:#6e2c00;}'
        . '.ge{background:#f8cdd0;color:#840010;}'
        . '.gw{background:#ddd;color:#444;}'
        . '.ct{width:100%;margin-bottom:6px;}'
        . '.ct td{border:1px solid #b0c4de;padding:5px 9px;}'
        . '.rk{border:1px solid #1e3a5f;margin-bottom:10px;}'
        . '.rkh{background:#e8f0fa;padding:4px 9px;font-size:8px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.5px;border-bottom:1px solid #1e3a5f;}'
        . '.rkb{padding:7px 9px;min-height:26px;font-size:10px;}'
        . '.st{width:100%;margin-bottom:10px;}'
        . '.st td{text-align:center;padding:5px 8px;border:1px solid #ddd;background:#f9f9f9;width:33%;vertical-align:bottom;}'
        . '.slb{font-size:7.5px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.5px;padding-top:3px;display:block;}'
        . '.ft{width:100%;margin-top:6px;}'
        . '.ft .sm{width:36%;border:1px solid #ccc;padding:8px;text-align:center;background:#fafafa;vertical-align:top;}'
        . '.ft .gp{width:8%;}'
        . '.ft .gr{vertical-align:top;}'
        . '.stl{font-size:8.5px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;display:block;}'
        . '.ssp{height:44px;border-bottom:1px dashed #aaa;margin:6px 12px;}'
        . '.ssb{font-size:7.5px;color:#888;font-style:italic;margin-top:4px;display:block;}'
        . '.gtt{font-size:8px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;text-align:center;padding:3px;background:#e8f0fa;border:1px solid #bbb;border-bottom:none;letter-spacing:0.5px;}'
        . '.gt{width:100%;}'
        . '.gt th{background:#e8f0fa;color:#1e3a5f;padding:3px 5px;border:1px solid #bbb;font-weight:bold;text-align:center;font-size:8px;}'
        . '.gt td{border:1px solid #ccc;padding:2px 5px;text-align:center;font-size:8.5px;}'
        . '.fs{background:#1e3a5f;color:#fff;text-align:center;padding:5px 8px;font-size:8px;letter-spacing:1.5px;text-transform:uppercase;margin-top:10px;}'
        . 'img{display:block;}'
        . '@page{margin:0.8cm;}'
        . '@media print{body{padding:0;} .pg{padding:0;}}';

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

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

    // Header
    $html .= '<table class="ht"><tr>';
    if ($logo) $html .= '<td class="lc"><img src="' . $logo . '"></td>';
    $html .= '<td class="ic"><div class="sn">' . $schoolName . '</div>';
    if ($data['schoolAddress'] !== '') $html .= '<div class="sa">' . htmlspecialchars($data['schoolAddress']) . '</div>';
    $cp = array_filter([$data['schoolPhone'], $data['schoolEmail']]);
    if ($cp) $html .= '<div class="sc">' . implode(' &nbsp;|&nbsp; ', array_map('htmlspecialchars', $cp)) . '</div>';
    $html .= '</td></tr></table>';
    $html .= '<table class="dv"><tr><td></td></tr></table>';

    // Title band
    $html .= '<div class="tb">TERMINAL REPORT &mdash; ' . htmlspecialchars(strtoupper($student['class'])) . '</div>';

    // Student info 3×3 grid
    $html .= '<table class="it"><tr>';
    $html .= '<td><div class="il">Student Name</div><div class="iv">' . $studentName . '</div></td>';
    $html .= '<td><div class="il">Class</div><div class="iv">' . htmlspecialchars($student['class']) . '</div></td>';
    $html .= '<td><div class="il">Term</div><div class="iv">' . $termFormatted . '</div></td>';
    $html .= '</tr><tr>';
    $html .= '<td><div class="il">Academic Year</div><div class="iv">' . htmlspecialchars($academic_year) . '</div></td>';
    $html .= '<td><div class="il">Position</div><div class="iv">' . $data['positionLabel'] . ' out of ' . $classSize . '</div></td>';
    $html .= '<td><div class="il">No. on Roll</div><div class="iv">' . $classSize . '</div></td>';
    $html .= '</tr><tr>';
    $html .= '<td><div class="il">Closing Date</div><div class="iv">' . date('d F Y', strtotime($data['closingDate'])) . '</div></td>';
    $html .= '<td><div class="il">Re-opening Date</div><div class="iv">' . date('d F Y', strtotime($data['reopeningDate'])) . '</div></td>';
    $html .= '<td><div class="il">Aggregate Total</div><div class="iv">' . round($totalMarks, 0) . '</div></td>';
    $html .= '</tr></table>';

    // Results table
    $html .= '<table class="rt"><thead><tr>';
    $html .= '<th style="width:27%;text-align:left;padding-left:8px;">Subject</th>';
    $html .= '<th style="width:12%;">Class Score (50%)</th>';
    $html .= '<th style="width:12%;">Exam Score (50%)</th>';
    $html .= '<th style="width:9%;">Total</th>';
    $html .= '<th style="width:8%;">Grade</th>';
    $html .= '<th>Remarks</th>';
    $html .= '</tr></thead><tbody>';

    foreach ($subjects as $subject) {
        $score      = $scores[$subject['subject_id']] ?? null;
        $classScore = $score && $score['class_score'] !== null ? (string) round($score['class_score'], 0) : '-';
        $examScore  = $score && $score['exam_score']  !== null ? (string) round($score['exam_score'], 0)  : '-';
        $totalScore = $score && $score['total_score'] !== null ? (string) round($score['total_score'], 0) : '-';
        $grade      = $score ? strtoupper((string) $score['grade'])  : '-';
        $remark     = $score ? strtoupper((string) $score['remark']) : '';
        $gCls       = match ($grade) { 'A' => 'ga', 'B' => 'gb', 'C' => 'gc', 'D' => 'gd', 'E' => 'ge', default => 'gw' };
        $html .= '<tr>'
               . '<td class="sj">' . htmlspecialchars(strtoupper($subject['subject_name'])) . '</td>'
               . '<td>' . $classScore . '</td>'
               . '<td>' . $examScore . '</td>'
               . '<td><strong>' . $totalScore . '</strong></td>'
               . '<td class="' . $gCls . '">' . htmlspecialchars($grade) . '</td>'
               . '<td>' . htmlspecialchars($remark) . '</td>'
               . '</tr>';
    }

    $html .= '<tr class="trt"><td class="sj" colspan="3" style="text-align:right;padding-right:12px;">AGGREGATE TOTAL</td>'
           . '<td colspan="3"><strong>' . round($totalMarks, 0) . '</strong></td></tr>';
    $html .= '</tbody></table>';

    // Attendance / promoted / conduct / interest
    $html .= '<table class="ct"><tr>';
    $html .= '<td style="width:25%;"><div class="il">Attendance</div><div class="iv">' . htmlspecialchars((string) $data['attendance']) . ' / ' . $classSize . '</div></td>';
    $html .= '<td style="width:25%;"><div class="il">Promoted To</div><div class="iv">' . htmlspecialchars((string) $data['promotedTo']) . '</div></td>';
    $html .= '<td style="width:25%;"><div class="il">Conduct</div><div class="iv">' . htmlspecialchars((string) $data['conduct']) . '</div></td>';
    $html .= '<td style="width:25%;"><div class="il">Interest</div><div class="iv">' . htmlspecialchars((string) $data['interest']) . '</div></td>';
    $html .= '</tr></table>';

    // Teacher remarks
    $html .= '<div class="rk"><div class="rkh">Class Teacher\'s Remarks</div><div class="rkb">' . htmlspecialchars((string) $data['teacherRemark']) . '</div></div>';

    // Signatures
    $html .= '<table class="st"><tr>';
    $html .= '<td>' . $sig('directorSignature') . '<span class="slb">Director</span></td>';
    $html .= '<td>' . $sig('headteacherSignature') . '<span class="slb">Head Teacher</span></td>';
    $html .= '<td>' . $sig('classTeacherSignature') . '<span class="slb">Class Teacher</span></td>';
    $html .= '</tr></table>';

    // Footer: school stamp + grading scale
    $html .= '<table class="ft"><tr>';
    $html .= '<td class="sm"><span class="stl">School Stamp</span><div class="ssp"></div><span class="ssb">Authenticated Seal</span></td>';
    $html .= '<td class="gp"></td>';
    $html .= '<td class="gr"><div class="gtt">Grading Scale</div><table class="gt"><thead><tr><th>Marks</th><th>Grade</th><th>Remark</th></tr></thead><tbody>' . $gradeRowsHtml . '</tbody></table></td>';
    $html .= '</tr></table>';

    $html .= '<div class="fs">' . $schoolName . ' &mdash; CONFIDENTIAL &mdash; ' . htmlspecialchars($academic_year) . '</div>';
    $html .= '</div></body></html>';

    return $html;
}
