<?php

declare(strict_types=1);

session_start();

require_once '../config.php';

require_once __DIR__ . '/helpers.php';



// Parent auth gate

if (!isset($_SESSION['parent_id'])) {

    http_response_code(403);

    die('Access denied. Please log in to the parent portal.');

}



$conn      = portalGetConnection();

$parentId  = (int) $_SESSION['parent_id'];

$studentId = (int) ($_GET['student_id'] ?? 0);

$term      = trim((string) ($_GET['term'] ?? ''));

$year      = trim((string) ($_GET['academic_year'] ?? ''));



if (!$studentId || !$term || !$year) {

    http_response_code(400);

    die('Missing required parameters.');

}



// Verify parent owns this student

if (!portalParentOwnsStudent($conn, $parentId, $studentId)) {

    http_response_code(403);

    die('Access denied.');

}



// Verify report is published

$pubStmt = $conn->prepare(

    "SELECT is_published FROM report_details WHERE student_id = ? AND term = ? AND academic_year = ? LIMIT 1"

);

$pubStmt->bind_param('iss', $studentId, $term, $year);

$pubStmt->execute();

$pubRow = $pubStmt->get_result()->fetch_assoc();

$pubStmt->close();



if (!$pubRow || empty($pubRow['is_published'])) {

    http_response_code(403);

    die('This report card has not been released yet. Please contact the school or check back later.');

}



// ── PDF generation (same logic as report_pdf.php, adapted for parent-portal path context) ──



require_once '../vendor/autoload.php';

require_once '../config.php';



$settings = [];

$r = $conn->query("SELECT * FROM settings");

if ($r) { while ($row = $r->fetch_assoc()) $settings[$row['setting_key']] = $row['setting_value']; }



// Student

$stStmt = $conn->prepare("SELECT * FROM students WHERE id = ?");

$stStmt->bind_param('i', $studentId);

$stStmt->execute();

$student = $stStmt->get_result()->fetch_assoc();

$stStmt->close();



if (!$student) { http_response_code(404); die('Student record not found.'); }



// Class size

$classSize = 0;

$csStmt = $conn->prepare("SELECT COUNT(*) AS total FROM students WHERE class = ? AND status = 'active'");

$csStmt->bind_param('s', $student['class']);

$csStmt->execute();

$csRow = $csStmt->get_result()->fetch_assoc();

$classSize = (int) ($csRow['total'] ?? 0);

$csStmt->close();



// Subjects

$subjects = [];

$subStmt = $conn->prepare("

    SELECT cs.*, s.subject_name, s.subject_code

    FROM class_subjects cs

    JOIN subjects s ON cs.subject_id = s.id

    WHERE cs.class_name = ?

    ORDER BY cs.display_order, s.subject_name

");

$subStmt->bind_param('s', $student['class']);

$subStmt->execute();

$subResult = $subStmt->get_result();

while ($row = $subResult->fetch_assoc()) $subjects[] = $row;

$subStmt->close();



// Scores

$scores = [];

$scStmt = $conn->prepare("SELECT * FROM scores WHERE student_id = ? AND term = ? AND academic_year = ?");

$scStmt->bind_param('iss', $studentId, $term, $year);

$scStmt->execute();

$scResult = $scStmt->get_result();

while ($row = $scResult->fetch_assoc()) $scores[$row['subject_id']] = $row;

$scStmt->close();



$totalMarks = 0;

foreach ($scores as $sc) $totalMarks += $sc['total_score'];



// Position

$position = 1;

$posStmt = $conn->prepare("

    SELECT s.id, COALESCE(SUM(sc.total_score), 0) AS total

    FROM students s

    LEFT JOIN scores sc ON s.id = sc.student_id AND sc.term = ? AND sc.academic_year = ?

    WHERE s.class = ? AND s.status = 'active'

    GROUP BY s.id

    ORDER BY total DESC

");

$posStmt->bind_param('sss', $term, $year, $student['class']);

$posStmt->execute();

$posResult = $posStmt->get_result();

while ($posRow = $posResult->fetch_assoc()) {

    if ($posRow['id'] == $studentId) break;

    $position++;

}

$posStmt->close();



function portalGetPositionSuffix(int $pos): string {

    if ($pos % 100 >= 11 && $pos % 100 <= 13) return $pos . 'TH';

    return match($pos % 10) { 1 => $pos . 'ST', 2 => $pos . 'ND', 3 => $pos . 'RD', default => $pos . 'TH' };

}



// Report details

$rdStmt = $conn->prepare("SELECT * FROM report_details WHERE student_id = ? AND term = ? AND academic_year = ? LIMIT 1");

$rdStmt->bind_param('iss', $studentId, $term, $year);

$rdStmt->execute();

$reportDetails = $rdStmt->get_result()->fetch_assoc();

$rdStmt->close();



$closingDate   = $reportDetails['closing_date']   ?? date('Y-m-d');

$reopeningDate = $reportDetails['reopening_date'] ?? date('Y-m-d', strtotime('+30 days'));

$attendance    = $reportDetails['attendance_out_of'] ?? '_____';

$promotedTo    = $reportDetails['promoted_to']    ?? $student['class'];

$conduct       = $reportDetails['conduct']        ?? 'SATISFACTORY';

$interest      = $reportDetails['interest']       ?? 'FOCUSED ON STUDIES';

$teacherRemark = $reportDetails['teacher_remark'] ?? 'GOOD PERFORMANCE';



// Grade boundaries

$gradeBoundaries = [];

$gbClass = $student['class'];

$gbStmt = $conn->prepare("

    SELECT * FROM grade_boundaries WHERE class_name = ?

    UNION

    SELECT * FROM grade_boundaries WHERE class_name = 'ALL'

      AND grade NOT IN (SELECT grade FROM grade_boundaries WHERE class_name = ?)

    ORDER BY CASE grade WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 WHEN 'D' THEN 4 WHEN 'E' THEN 5 ELSE 6 END

");

$gbStmt->bind_param('ss', $gbClass, $gbClass);

$gbStmt->execute();

$gbResult = $gbStmt->get_result();

while ($gbRow = $gbResult->fetch_assoc()) $gradeBoundaries[] = $gbRow;

$gbStmt->close();



// Persistent signatures

$directorSigPath = $reportDetails['director_signature'] ?? '';

$headteacherSigPath = $reportDetails['headteacher_signature'] ?? '';

$classTeacherSigPath = $reportDetails['class_teacher_signature'] ?? '';



if (empty($directorSigPath)) {

    $s = $conn->prepare("SELECT signature_path FROM users WHERE role = 'director' AND signature_path IS NOT NULL AND signature_path != '' LIMIT 1");

    $s->execute(); $r2 = $s->get_result()->fetch_assoc(); if ($r2) $directorSigPath = $r2['signature_path']; $s->close();

}

if (empty($headteacherSigPath)) {

    $s = $conn->prepare("SELECT signature_path FROM users WHERE role = 'headteacher' AND signature_path IS NOT NULL AND signature_path != '' LIMIT 1");

    $s->execute(); $r2 = $s->get_result()->fetch_assoc(); if ($r2) $headteacherSigPath = $r2['signature_path']; $s->close();

}

if (empty($classTeacherSigPath)) {

    $s = $conn->prepare("SELECT st.signature_path FROM staff st JOIN classes c ON c.class_teacher_id = st.id WHERE c.class_name = ? AND c.is_active = 1 AND st.signature_path IS NOT NULL AND st.signature_path != '' LIMIT 1");

    $s->bind_param('s', $student['class']); $s->execute(); $r2 = $s->get_result()->fetch_assoc(); if ($r2) $classTeacherSigPath = $r2['signature_path']; $s->close();

}



$conn->close();



// Build sig HTML (base64-embed for DOMPDF)

function parentBuildSigHtml(string $relPath): string {

    $fallback = '<div style="border-bottom:1px solid #000;height:30px;margin-bottom:5px;"></div>';

    if (empty($relPath)) return $fallback;

    $abs = __DIR__ . '/../' . ltrim($relPath, '/');

    if (!file_exists($abs)) return $fallback;

    $ext  = strtolower(pathinfo($abs, PATHINFO_EXTENSION));

    $mime = in_array($ext, ['jpg','jpeg']) ? 'image/jpeg' : 'image/png';

    $b64  = base64_encode((string) file_get_contents($abs));

    return '<img src="data:' . $mime . ';base64,' . $b64 . '" style="max-height:40px;max-width:140px;display:block;margin:0 auto 5px;">';

}

$directorSigHtml     = parentBuildSigHtml($directorSigPath);

$headteacherSigHtml  = parentBuildSigHtml($headteacherSigPath);

$classTeacherSigHtml = parentBuildSigHtml($classTeacherSigPath);



// Logo

$logoPath = __DIR__ . '/../uploads/logos/logo.png';

$logoSrc  = '';

if (file_exists($logoPath)) {

    $b64     = base64_encode((string) file_get_contents($logoPath));

    $logoSrc = 'data:image/png;base64,' . $b64;

}



// Grade rows

$gradeRowsHtml = '';

if (!empty($gradeBoundaries)) {

    foreach ($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>';

    }

} else {

    $gradeRowsHtml = '<tr><td>100-90</td><td>A</td><td>EXCELLENT</td></tr><tr><td>89-80</td><td>B</td><td>VERY GOOD</td></tr><tr><td>79-70</td><td>C</td><td>GOOD</td></tr><tr><td>69-60</td><td>D</td><td>SATISFACTORY</td></tr><tr><td>59-50</td><td>E</td><td>PASS</td></tr><tr><td>49-below</td><td>W</td><td>WEAK</td></tr>';

}



$schoolName    = $settings['school_name']    ?? 'SCHOOL NAME';

$schoolAddress = $settings['school_address'] ?? 'ADDRESS';

$schoolPhone   = $settings['school_phone']   ?? '';

$schoolEmail   = $settings['school_email']   ?? '';



$termFormatted = strtoupper($term);

if ($term === 'First Term')  $termFormatted = 'ONE(1)';

elseif ($term === 'Second Term') $termFormatted = 'TWO(2)';

elseif ($term === 'Third Term')  $termFormatted = 'THREE(3)';



// ─── Professional PDF design (table-based layout — DOMPDF compatible) ───

$_css  = '*{margin:0;padding:0;box-sizing:border-box;}';

$_css .= 'body{font-family:Arial,sans-serif;font-size:10px;color:#111;}';

$_css .= 'table{border-collapse:collapse;}';

$_css .= '.pg{padding:8px;}';

$_css .= '.ht{width:100%;}';

$_css .= '.ht .lc{width:72px;vertical-align:middle;padding-right:8px;}';

$_css .= '.ht .lc img{width:65px;height:65px;}';

$_css .= '.ht .ic{vertical-align:middle;text-align:center;}';

$_css .= '.sn{font-size:16px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.5px;}';

$_css .= '.sa{font-size:8.5px;color:#555;margin-top:2px;}';

$_css .= '.sc{font-size:8px;color:#666;margin-top:1px;}';

$_css .= '.dv{width:100%;margin:6px 0;}';

$_css .= '.dv td{background:#1e3a5f;height:3px;padding:0;font-size:0;line-height:0;}';

$_css .= '.tb{background:#1e3a5f;color:#fff;text-align:center;font-size:12px;font-weight:bold;letter-spacing:3px;padding:7px 10px;margin-bottom:7px;}';

$_css .= '.it{width:100%;margin-bottom:5px;}';

$_css .= '.it td{border:1px solid #b0c4de;padding:5px 9px;}';

$_css .= '.il{font-size:7.5px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.3px;}';

$_css .= '.iv{font-size:11px;font-weight:600;color:#000;margin-top:2px;}';

$_css .= '.rt{width:100%;margin-bottom:8px;}';

$_css .= '.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;}';

$_css .= '.rt td{border:1px solid #ccc;padding:4px;text-align:center;font-size:9.5px;}';

$_css .= '.rt .sj{text-align:left!important;padding-left:8px!important;font-weight:500;}';

$_css .= '.trt td{background:#dce8f5;font-weight:bold;border-top:2px solid #1e3a5f;}';

$_css .= '.ga{background:#c3f0d4;color:#0d5c2e;font-weight:bold;}';

$_css .= '.gb{background:#c3dcf8;color:#0a3466;font-weight:bold;}';

$_css .= '.gc{background:#fff0b0;color:#705000;font-weight:bold;}';

$_css .= '.gd{background:#ffdea0;color:#6e2c00;}';

$_css .= '.ge{background:#f8cdd0;color:#840010;}';

$_css .= '.gw{background:#ddd;color:#444;}';

$_css .= '.ct{width:100%;margin-bottom:6px;}';

$_css .= '.ct td{border:1px solid #b0c4de;padding:5px 9px;}';

$_css .= '.ch{background:#e8f0fa!important;font-size:8px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.5px;text-align:center;padding:4px 9px!important;}';

$_css .= '.rk{border:1px solid #1e3a5f;margin-bottom:10px;}';

$_css .= '.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;}';

$_css .= '.rkb{padding:7px 9px;min-height:26px;font-size:10px;}';

$_css .= '.st{width:100%;margin-bottom:10px;}';

$_css .= '.st td{text-align:center;padding:5px 8px;border:1px solid #ddd;background:#f9f9f9;width:33%;vertical-align:bottom;}';

$_css .= '.sl{border-bottom:1px solid #555;height:36px;width:75%;margin:0 auto 4px;}';

$_css .= '.slb{font-size:7.5px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;letter-spacing:0.5px;padding-top:3px;display:block;}';

$_css .= '.ft{width:100%;margin-top:6px;}';

$_css .= '.ft .sm{width:36%;border:1px solid #ccc;padding:8px;text-align:center;background:#fafafa;vertical-align:top;}';

$_css .= '.ft .gp{width:8%;}';

$_css .= '.ft .gr{vertical-align:top;}';

$_css .= '.stl{font-size:8.5px;font-weight:bold;color:#1e3a5f;text-transform:uppercase;display:block;}';

$_css .= '.ssp{height:44px;border-bottom:1px dashed #aaa;margin:6px 12px;}';

$_css .= '.ssb{font-size:7.5px;color:#888;font-style:italic;margin-top:4px;display:block;}';

$_css .= '.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;}';

$_css .= '.gt{width:100%;}';

$_css .= '.gt th{background:#e8f0fa;color:#1e3a5f;padding:3px 5px;border:1px solid #bbb;font-weight:bold;text-align:center;font-size:8px;}';

$_css .= '.gt td{border:1px solid #ccc;padding:2px 5px;text-align:center;font-size:8.5px;}';

$_css .= '.fs{background:#1e3a5f;color:#fff;text-align:center;padding:5px 8px;font-size:8px;letter-spacing:1.5px;text-transform:uppercase;margin-top:10px;}';

$_css .= 'img{display:block;}';

$_css .= '@page{margin:0.8cm;}';



$html  = '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>' . $_css . '</style></head><body><div class="pg">';



// Header

$html .= '<table class="ht"><tr>';

if (!empty($logoSrc)) $html .= '<td class="lc"><img src="' . $logoSrc . '"></td>';

$html .= '<td class="ic"><div class="sn">' . htmlspecialchars($schoolName) . '</div>';

if (!empty($schoolAddress)) $html .= '<div class="sa">' . htmlspecialchars($schoolAddress) . '</div>';

$_cp = array_filter([$schoolPhone, $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">' . htmlspecialchars(strtoupper($student['first_name'] . ' ' . $student['last_name'])) . '</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($year) . '</div></td>';

$html .= '<td><div class="il">Position</div><div class="iv">' . portalGetPositionSuffix($position) . ' 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($closingDate)) . '</div></td>';

$html .= '<td><div class="il">Re-opening Date</div><div class="iv">' . date('d F Y', strtotime($reopeningDate)) . '</div></td>';

$html .= '<td><div class="il">Aggregate Total</div><div class="iv">' . $totalMarks . '</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) {

    $sc         = $scores[$subject['subject_id']] ?? null;

    $classScore = $sc ? ($sc['class_score'] !== null ? (string)$sc['class_score'] : '-') : '-';

    $examScore  = $sc ? ($sc['exam_score']  !== null ? (string)$sc['exam_score']  : '-') : '-';

    $totalScore = $sc ? ($sc['total_score'] !== null ? (string)$sc['total_score'] : '-') : '-';

    $grade      = $sc ? strtoupper((string)$sc['grade'])  : '-';

    $remark     = $sc ? strtoupper((string)$sc['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>' . $totalMarks . '</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)$attendance) . ' / ' . $classSize . '</div></td>';

$html .= '<td style="width:25%;"><div class="il">Promoted To</div><div class="iv">' . htmlspecialchars((string)$promotedTo) . '</div></td>';

$html .= '<td style="width:25%;"><div class="il">Conduct</div><div class="iv">' . htmlspecialchars((string)$conduct) . '</div></td>';

$html .= '<td style="width:25%;"><div class="il">Interest</div><div class="iv">' . htmlspecialchars((string)$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)$teacherRemark) . '</div></div>';



// Signatures

$html .= '<table class="st"><tr>';

$html .= '<td>' . $directorSigHtml . '<span class="slb">Director</span></td>';

$html .= '<td>' . $headteacherSigHtml . '<span class="slb">Head Teacher</span></td>';

$html .= '<td>' . $classTeacherSigHtml . '<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">' . htmlspecialchars($schoolName) . ' &mdash; CONFIDENTIAL &mdash; ' . htmlspecialchars($year) . '</div>';

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



use Dompdf\Dompdf;

use Dompdf\Options;



$options = new Options();

$options->set('isHtml5ParserEnabled', true);

$options->set('isRemoteEnabled', false);



$dompdf = new Dompdf($options);

$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'portrait');

$dompdf->render();

$pdfContent = $dompdf->output();



$filename = str_replace(' ', '_', $student['first_name'] . '_' . $student['last_name']) . '_Report_' . str_replace(' ', '_', $term) . '.pdf';



header('Content-Type: application/pdf');

header('Content-Disposition: attachment; filename="' . $filename . '"');

header('Cache-Control: no-cache, must-revalidate');

echo $pdfContent;

exit;

