<?php
/**
 * Compact terminal report template.
 *
 * Space-efficient single-page layout: smaller type, tight padding and a
 * condensed footer so classes with long subject lists still fit on one A4 page.
 * Table-based so it renders the same in the browser (print) and DOMPDF (pdf).
 */

function renderReport_compact(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);
    $sig = function (string $key) use ($data, $mode): string {
        $src = reportImageSrc($data[$key], $mode);
        return $src
            ? '<img src="' . $src . '" style="max-height:28px;max-width:110px;display:inline-block;">'
            : '<span style="display:inline-block;border-bottom:1px solid #666;width:110px;height:16px;"></span>';
    };

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

    // Grading scale as one inline line
    $gradeParts = [];
    foreach ($data['gradeBoundaries'] as $gb) {
        $gbMax = (int) $gb['max_score'];
        $gbMin = (int) $gb['min_score'];
        $range = $gbMin === 0 ? $gbMax . '&amp;below' : $gbMax . '-' . $gbMin;
        $gradeParts[] = htmlspecialchars($gb['grade']) . ' (' . $range . ' ' . htmlspecialchars($gb['remark']) . ')';
    }
    $gradeLine = implode(' &nbsp;&bull;&nbsp; ', $gradeParts);

    $css = '*{margin:0;padding:0;box-sizing:border-box;}'
        . 'body{font-family:Arial,Helvetica,sans-serif;font-size:8.5px;color:#000;background:#fff;}'
        . '.pg{padding:6px;max-width:210mm;margin:0 auto;}'
        . '.hd{width:100%;border-bottom:2px solid #000;padding-bottom:3px;margin-bottom:4px;}'
        . '.hd .lc{width:46px;vertical-align:middle;}'
        . '.hd .lc img{width:42px;height:42px;object-fit:contain;}'
        . '.hd .ic{text-align:center;vertical-align:middle;}'
        . '.sn{font-size:14px;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;}'
        . '.sa{font-size:7.5px;color:#333;}'
        . '.ttl{text-align:center;font-size:10px;font-weight:bold;text-transform:uppercase;background:#222;color:#fff;padding:3px;margin-bottom:4px;letter-spacing:1px;}'
        . '.meta{width:100%;margin-bottom:4px;font-size:8.5px;}'
        . '.meta td{border:1px solid #999;padding:2px 5px;}'
        . '.meta b{text-transform:uppercase;font-size:7.5px;color:#333;}'
        . '.rt{width:100%;border-collapse:collapse;margin-bottom:4px;}'
        . '.rt th{background:#333;color:#fff;font-size:7.5px;text-transform:uppercase;padding:3px;border:1px solid #000;text-align:center;}'
        . '.rt td{border:1px solid #999;padding:2px 3px;text-align:center;font-size:8.5px;}'
        . '.rt .sj{text-align:left;padding-left:5px;}'
        . '.rt .tot td{background:#e5e5e5;font-weight:bold;border-top:2px solid #000;}'
        . '.gcell{font-weight:bold;}'
        . '.cf{width:100%;margin-bottom:4px;font-size:8.5px;}'
        . '.cf td{border:1px solid #999;padding:2px 5px;}'
        . '.cf b{text-transform:uppercase;font-size:7.5px;color:#333;}'
        . '.rmk{border:1px solid #000;padding:3px 5px;margin-bottom:4px;font-size:8.5px;}'
        . '.rmk b{text-transform:uppercase;font-size:7.5px;}'
        . '.sig{width:100%;margin-bottom:4px;}'
        . '.sig td{text-align:center;width:33%;padding:2px;vertical-align:bottom;}'
        . '.sig .lb{font-size:7px;text-transform:uppercase;font-weight:bold;border-top:1px solid #000;padding-top:2px;display:block;margin-top:2px;}'
        . '.scale{font-size:7px;color:#333;border-top:1px solid #999;padding-top:3px;text-align:center;}'
        . 'img{display:inline-block;}'
        . '@page{margin:0.5cm;}'
        . '@media print{body{padding:0;} .pg{padding:0;}}';

    $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="hd"><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="sa">' . implode(' | ', array_map('htmlspecialchars', $cp)) . '</div>';
    $html .= '</td></tr></table>';

    // Title
    $html .= '<div class="ttl">Terminal Report &mdash; ' . htmlspecialchars(strtoupper($student['class'])) . '</div>';

    // Meta grid (2 rows × 4)
    $html .= '<table class="meta"><tr>';
    $html .= '<td><b>Name</b><br>' . $studentName . '</td>';
    $html .= '<td><b>Class</b><br>' . htmlspecialchars($student['class']) . '</td>';
    $html .= '<td><b>Term</b><br>' . $termFormatted . '</td>';
    $html .= '<td><b>Year</b><br>' . htmlspecialchars($academic_year) . '</td>';
    $html .= '</tr><tr>';
    $html .= '<td><b>No. on Roll</b><br>' . $classSize . '</td>';
    $html .= '<td><b>Position</b><br>' . $data['positionLabel'] . ' of ' . $classSize . '</td>';
    $html .= '<td><b>Total Marks</b><br>' . round($totalMarks, 0) . '</td>';
    $html .= '<td><b>Closing / Re-open</b><br>' . date('d/m/y', strtotime($data['closingDate'])) . ' - ' . date('d/m/y', strtotime($data['reopeningDate'])) . '</td>';
    $html .= '</tr></table>';

    // Results
    $html .= '<table class="rt"><thead><tr>'
           . '<th style="width:30%;text-align:left;padding-left:5px;">Subject</th>'
           . '<th style="width:13%;">Class (50%)</th>'
           . '<th style="width:13%;">Exam (50%)</th>'
           . '<th style="width:10%;">Total</th>'
           . '<th style="width:8%;">Grade</th>'
           . '<th>Remarks</th>'
           . '</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']) : '';
        $html .= '<tr>'
               . '<td class="sj">' . htmlspecialchars(strtoupper($subject['subject_name'])) . '</td>'
               . '<td>' . $classScore . '</td>'
               . '<td>' . $examScore . '</td>'
               . '<td><strong>' . $totalScore . '</strong></td>'
               . '<td class="gcell">' . htmlspecialchars($grade) . '</td>'
               . '<td>' . htmlspecialchars($remark) . '</td>'
               . '</tr>';
    }
    $html .= '<tr class="tot"><td class="sj" colspan="3" style="text-align:right;">TOTAL</td>'
           . '<td><strong>' . round($totalMarks, 0) . '</strong></td><td colspan="2"></td></tr>';
    $html .= '</tbody></table>';

    // Conduct row
    $html .= '<table class="cf"><tr>';
    $html .= '<td><b>Attendance</b> ' . htmlspecialchars((string) $data['attendance']) . ' / ' . $classSize . '</td>';
    $html .= '<td><b>Promoted To</b> ' . htmlspecialchars((string) $data['promotedTo']) . '</td>';
    $html .= '<td><b>Conduct</b> ' . htmlspecialchars((string) $data['conduct']) . '</td>';
    $html .= '<td><b>Interest</b> ' . htmlspecialchars((string) $data['interest']) . '</td>';
    $html .= '</tr></table>';

    // Remark
    $html .= '<div class="rmk"><b>Class Teacher\'s Remarks:</b> ' . htmlspecialchars((string) $data['teacherRemark']) . '</div>';

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

    // Grading scale inline
    $html .= '<div class="scale"><b>Grading:</b> ' . $gradeLine . '</div>';

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

    return $html;
}
