<?php
require_once '../../config.php';
$conn = getDBConnection();

// Ensure publish columns exist (idempotent)
$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS is_published TINYINT(1) NOT NULL DEFAULT 0");
$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS published_at DATETIME NULL DEFAULT NULL");
$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS attendance_total_days INT NOT NULL DEFAULT 0");
$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS headteacher_remark TEXT NULL DEFAULT NULL");

// Get settings
$settings = [];
$result = $conn->query("SELECT * FROM settings");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}

$student_id = $_GET['student_id'] ?? 0;
$term = $_GET['term'] ?? getCurrentTerm();
$academic_year = $_GET['academic_year'] ?? getAcademicYear();
$edit_mode = isset($_GET['edit']) ? true : false;

// Get student info FIRST
$stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    die("Student not found");
}

// Get student photo
$studentPhoto = null;
if (!empty($student['photo'])) {
    $studentPhoto = '../../' . $student['photo'];
    if (!file_exists($studentPhoto)) {
        $studentPhoto = null;
    }
}

// Get total number of students in the class (NO ON ROLL)
$classSize = 0;
$stmt = $conn->prepare("SELECT COUNT(*) as total FROM students WHERE class = ? AND status = 'active'");
$stmt->bind_param("s", $student['class']);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
    $classSize = $row['total'] ?? 0;
}
$stmt->close();

// Get subjects for this class
$subjects = [];
$stmt = $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
");
$stmt->bind_param("s", $student['class']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $subjects[] = $row;
}
$stmt->close();

// Get scores
$scores = [];
$stmt = $conn->prepare("SELECT * FROM scores WHERE student_id = ? AND term = ? AND academic_year = ?");
$stmt->bind_param("iss", $student_id, $term, $academic_year);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $scores[$row['subject_id']] = $row;
}
$stmt->close();

// Calculate total marks
$totalMarks = 0;
$totalWeightedMarks = 0;
foreach ($scores as $score) {
    $totalMarks += $score['total_score'];
    $totalWeightedMarks += ($score['weighted_class_score'] + $score['weighted_exam_score']);
}

// Calculate position in class
$position = 1;
$stmt = $conn->prepare("
    SELECT s.id, SUM(sc.total_score) 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
");
$stmt->bind_param("sss", $term, $academic_year, $student['class']);
$stmt->execute();
$result = $stmt->get_result();
$classTotal = 0;
while ($row = $result->fetch_assoc()) {
    $classTotal++;
    if ($row['id'] == $student_id) {
        break;
    }
    $position++;
}
$stmt->close();

// Get position suffix
function getPositionSuffix($pos) {
    if ($pos % 100 >= 11 && $pos % 100 <= 13) return $pos . 'TH';
    switch ($pos % 10) {
        case 1: return $pos . 'ST';
        case 2: return $pos . 'ND';
        case 3: return $pos . 'RD';
        default: return $pos . 'TH';
    }
}

// Get report details
$reportDetails = null;
$stmt = $conn->prepare("SELECT * FROM report_details WHERE student_id = ? AND term = ? AND academic_year = ?");
$stmt->bind_param("iss", $student_id, $term, $academic_year);
$stmt->execute();
$result = $stmt->get_result();
$reportDetails = $result->fetch_assoc();
$stmt->close();

// Attendance: auto-calculate from attendance table if no saved value
$savedAttendance = $reportDetails['attendance_out_of'] ?? null;
if ($savedAttendance !== null && (int)$savedAttendance > 0) {
    $attendance = (int)$savedAttendance;
} else {
    // Guarded: the helper queries `attendance`/`school_terms`, which some
    // installs lack. PHP 8 mysqli throws rather than returning false.
    $attendance = '_____';
    try {
        $days = getStudentTermDaysPresent($conn, $student_id, $academic_year, $term);
        if ((int)$days > 0) $attendance = (int)$days;
    } catch (Throwable $e) {
        // leave blank for hand entry
    }
}

// Total school days: from saved value, then from calendar, then fallback 56
$savedTotalDays = isset($reportDetails['attendance_total_days']) ? (int)$reportDetails['attendance_total_days'] : 0;
if ($savedTotalDays > 0) {
    $totalSchoolDays = $savedTotalDays;
} else {
    $totalSchoolDays = 0;
    try {
        $totalSchoolDays = (int) getTermSchoolDays($conn, $academic_year, $term, 0);
    } catch (Throwable $e) {
        // no term calendar configured — leave 0
    }
}
$promotedTo = $reportDetails['promoted_to'] ?? $student['class'];
$conduct = $reportDetails['conduct'] ?? 'SATISFACTORY';
$interest = $reportDetails['interest'] ?? 'HE IS INTERESTED IN READING';
$teacherRemark = $reportDetails['teacher_remark'] ?? 'HE FOLLOWS CLASSROOM RULES';
$headteacherRemark = $reportDetails['headteacher_remark'] ?? '';
$closingDate = $reportDetails['closing_date'] ?? date('Y-m-d');
$reopeningDate = $reportDetails['reopening_date'] ?? date('Y-m-d', strtotime('+30 days'));

// Get signatures
$directorSignature = $reportDetails['director_signature'] ?? '';
$headteacherSignature = $reportDetails['headteacher_signature'] ?? '';
$classTeacherSignature = $reportDetails['class_teacher_signature'] ?? '';
$schoolStamp  = $reportDetails['school_stamp'] ?? '';
$isPublished  = (bool) ($reportDetails['is_published'] ?? false);
$publishedAt  = $reportDetails['published_at'] ?? null;

// Fall back to persistent signatures when no per-report signature has been drawn
// yet -- or when the stored per-report path points at a file that no longer
// exists, which would otherwise render a blank signature box forever.
require_once __DIR__ . '/lib/report_data.php';
if (reportAssetMissing($directorSignature)) {
    $stmt = $conn->prepare("SELECT signature_path FROM users WHERE role = 'director' AND signature_path IS NOT NULL AND signature_path != '' LIMIT 1");
    $stmt->execute();
    $r = $stmt->get_result()->fetch_assoc();
    if ($r) $directorSignature = $r['signature_path'];
    $stmt->close();
}
if (reportAssetMissing($headteacherSignature)) {
    $stmt = $conn->prepare("SELECT signature_path FROM users WHERE role = 'headteacher' AND signature_path IS NOT NULL AND signature_path != '' LIMIT 1");
    $stmt->execute();
    $r = $stmt->get_result()->fetch_assoc();
    if ($r) $headteacherSignature = $r['signature_path'];
    $stmt->close();
}
if (reportAssetMissing($classTeacherSignature)) {
    $stmt = $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
    ");
    $stmt->bind_param('s', $student['class']);
    $stmt->execute();
    $r = $stmt->get_result()->fetch_assoc();
    if ($r) $classTeacherSignature = $r['signature_path'];
    $stmt->close();
}

// Format dates like the template
$closingDateFormatted = date('jS F Y', strtotime($closingDate));
$reopeningDateFormatted = date('jS F Y', strtotime($reopeningDate));

// Fetch grade boundaries from DB (class-specific, fallback to ALL)
$gradeBoundaries = [];
$gbClass = $student['class'] ?? 'ALL';
$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 WHEN 'W' THEN 6 ELSE 7 END"
);
$gbStmt->bind_param('ss', $gbClass, $gbClass);
$gbStmt->execute();
$gbResult = $gbStmt->get_result();
while ($gbRow = $gbResult->fetch_assoc()) { $gradeBoundaries[] = $gbRow; }
$gbStmt->close();
if (empty($gradeBoundaries)) {
    $gradeBoundaries = [
        ['grade' => 'A', 'min_score' => 90, 'max_score' => 100, 'remark' => 'EXCELLENT'],
        ['grade' => 'B', 'min_score' => 80, 'max_score' => 89,  'remark' => 'VERY GOOD'],
        ['grade' => 'C', 'min_score' => 70, 'max_score' => 79,  'remark' => 'GOOD'],
        ['grade' => 'D', 'min_score' => 60, 'max_score' => 69,  'remark' => 'SATISFACTORY'],
        ['grade' => 'E', 'min_score' => 50, 'max_score' => 59,  'remark' => 'PASS'],
        ['grade' => 'W', 'min_score' => 0,  'max_score' => 49,  'remark' => 'WEAK'],
    ];
}

$conn->close();

// School logo path
$logoPath = $settings['school_logo'] ?? 'uploads/logos/logo.png';
if (!file_exists('../../' . $logoPath)) {
    $logoPath = 'https://via.placeholder.com/100x100?text=Logo';
} else {
    $logoPath = '../../' . $logoPath;
}

// Format term like the template
$termFormatted = strtoupper(str_replace(' ', ' ', $term));
if ($term == 'First Term') $termFormatted = 'ONE(1)';
elseif ($term == 'Second Term') $termFormatted = 'TWO(2)';
elseif ($term == 'Third Term') $termFormatted = 'THREE(3)';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Terminal Report - <?php echo $student['first_name'] . ' ' . $student['last_name']; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Times New Roman', Times, serif;
            font-size: 11px;
            line-height: 1.3;
            color: #000;
            background: #f5f5f5;
            padding: 10px;
            display: flex;
            justify-content: center;
        }
        
        .report-card {
            max-width: 210mm;
            width: 210mm;
            min-height: 297mm;
            margin: 0 auto;
            background: #fff;
            padding: 10mm 8mm;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            position: relative;
        }
        
        /* Watermark */
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            opacity: 0.03;
            z-index: 0;
            pointer-events: none;
        }
        
        .watermark img {
            width: 400px;
            height: 400px;
            object-fit: contain;
        }
        
        /* Header */
        .report-header {
            text-align: center;
            margin-bottom: 5px;
            position: relative;
            z-index: 1;
            border-bottom: 2px solid #000;
            padding-bottom: 5px;
        }
        
        .school-logo {
            width: 70px;
            height: 70px;
            object-fit: contain;
            position: absolute;
            left: 0;
            top: 0;
        }
        
        .school-name {
            font-size: 18px;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 2px;
            letter-spacing: 1px;
        }
        
        .school-address {
            font-size: 9px;
            margin-bottom: 1px;
            font-weight: 500;
        }
        
        .school-contact {
            font-size: 8px;
            margin-bottom: 2px;
        }
        
        .school-email {
            font-size: 8px;
            font-style: italic;
        }
        
        /* Title */
        .report-title {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
            text-transform: uppercase;
            margin: 8px 0;
            padding: 4px;
            background: #f0f0f0;
            border: 1px solid #000;
        }
        
        /* Student Info Row - Like template */
        .student-info-row {
            display: flex;
            justify-content: space-between;
            border: 1px solid #000;
            margin-bottom: 8px;
            background: #f9f9f9;
        }
        
        .info-item {
            padding: 4px 8px;
            border-right: 1px solid #000;
            flex: 1;
        }
        
        .info-item:last-child {
            border-right: none;
        }
        
        .info-label {
            font-weight: bold;
            display: inline;
        }
        
        /* Dates Row */
        .dates-row {
            display: flex;
            justify-content: space-between;
            border: 1px solid #000;
            margin-bottom: 8px;
        }
        
        .date-item {
            padding: 4px 8px;
            border-right: 1px solid #000;
            flex: 1;
        }
        
        .date-item:last-child {
            border-right: none;
        }
        
        /* Results Table */
        .results-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 8px;
            font-size: 10px;
        }
        
        .results-table th,
        .results-table td {
            padding: 4px 3px;
            border: 1px solid #000;
            text-align: center;
            vertical-align: middle;
        }
        
        .results-table th {
            background: #333;
            color: #fff;
            font-weight: bold;
            font-size: 9px;
            text-transform: uppercase;
        }
        
        .results-table .subject-col {
            text-align: left;
            font-weight: 500;
            padding-left: 5px;
        }
        
        .results-table .grade-a { background: #d4edda; font-weight: bold; }
        .results-table .grade-b { background: #cce5ff; font-weight: bold; }
        .results-table .grade-c { background: #fff3cd; font-weight: bold; }
        .results-table .grade-d { background: #ffeeba; }
        .results-table .grade-e { background: #f8d7da; }
        .results-table .grade-w { background: #f5c6cb; }
        
        .total-row {
            font-weight: bold;
            background: #e9ecef;
        }
        
        .total-row td {
            border-top: 2px solid #000;
        }
        
        /* Attendance & Conduct Section - Like template */
        .info-section {
            margin-bottom: 8px;
            border: 1px solid #000;
        }
        
        .info-row {
            display: flex;
            border-bottom: 1px solid #000;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-cell {
            padding: 4px 8px;
            border-right: 1px solid #000;
            flex: 1;
        }
        
        .info-cell:last-child {
            border-right: none;
        }
        
        .info-cell strong {
            font-weight: bold;
            margin-right: 5px;
        }
        
        /* Teacher Remark Section */
        .remark-section {
            margin-bottom: 8px;
            border: 1px solid #000;
        }
        
        .remark-header {
            background: #f0f0f0;
            padding: 3px 8px;
            font-weight: bold;
            border-bottom: 1px solid #000;
        }
        
        .remark-content {
            padding: 6px 8px;
            min-height: 30px;
        }
        
        /* Signature Section - Like template */
        .signature-section {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }
        
        .signature-box {
            width: 24%;
            border: 1px solid #000;
            padding: 4px;
            text-align: center;
            background: #f9f9f9;
        }
        
        .signature-canvas-container {
            border: 1px solid #000;
            background: #fff;
            margin-bottom: 3px;
            position: relative;
            height: 50px;
            overflow: hidden;
        }
        
        .signature-canvas {
            width: 100%;
            height: 100%;
            cursor: crosshair;
        }
        
        .signature-image {
            max-width: 100%;
            max-height: 50px;
            object-fit: contain;
        }
        
        .signature-label {
            font-size: 7px;
            font-weight: bold;
            text-transform: uppercase;
            margin-top: 2px;
        }
        
        .signature-actions {
            display: flex;
            gap: 2px;
            justify-content: center;
            margin-top: 2px;
        }
        
        .signature-btn {
            padding: 1px 3px;
            font-size: 7px;
            border-radius: 2px;
            cursor: pointer;
        }
        
        /* Bottom Row - Stamp and Grading */
        .bottom-section {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-top: 5px;
        }
        
        .stamp-section {
            width: 30%;
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
            background: #f9f9f9;
        }
        
        .stamp-label {
            font-weight: bold;
            font-size: 9px;
            margin-bottom: 10px;
        }
        
        .stamp-space {
            height: 40px;
            border-bottom: 1px dashed #000;
            margin: 10px 0;
        }
        
        .stamp-text {
            font-style: italic;
            font-size: 8px;
        }
        
        .grading-reference {
            width: 35%;
            border: 1px solid #000;
            font-size: 7px;
        }
        
        .grading-reference th,
        .grading-reference td {
            padding: 2px 3px;
            border: 1px solid #000;
            text-align: center;
        }
        
        .grading-reference th {
            background: #f0f0f0;
            font-weight: bold;
        }
        
        /* School name footer */
        .school-footer {
            text-align: center;
            margin-top: 8px;
            font-weight: bold;
            font-size: 10px;
            border-top: 1px solid #000;
            padding-top: 5px;
        }
        
        /* Buttons */
        .action-buttons {
            position: fixed;
            top: 10px;
            right: 10px;
            display: flex;
            gap: 5px;
            z-index: 1000;
            background: white;
            padding: 5px 8px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        
        .btn {
            padding: 4px 8px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-weight: bold;
            font-size: 11px;
            display: inline-flex;
            align-items: center;
            gap: 3px;
            transition: all 0.2s;
        }
        
        .btn-primary { background: #0d6efd; color: #fff; }
        .btn-success { background: #198754; color: #fff; }
        .btn-warning { background: #ffc107; color: #000; }
        .btn-danger { background: #dc3545; color: #fff; }
        .btn-info { background: #0dcaf0; color: #000; }
        
        .btn:hover { opacity: 0.9; transform: translateY(-1px); box-shadow: 0 2px 3px rgba(0,0,0,0.2); }
        
        /* Editable Fields */
        .editable-field {
            cursor: pointer;
            padding: 1px 2px;
            border-radius: 2px;
            transition: background-color 0.2s;
            min-width: 20px;
            display: inline-block;
        }
        
        .editable-field:hover {
            background-color: #e9ecef;
            outline: 1px dashed #0d6efd;
        }
        
        .editable-field.editing {
            background-color: #fff;
            outline: 2px solid #0d6efd;
            padding: 0px 1px;
        }
        
        .editable-input {
            width: 100%;
            border: none;
            background: transparent;
            padding: 1px 2px;
            font-family: inherit;
            font-size: inherit;
            font-weight: inherit;
            color: inherit;
        }
        
        .editable-input:focus {
            outline: none;
        }
        
        /* Modal */
        .modal-backdrop {
            z-index: 1040;
        }
        
        .modal {
            z-index: 1050;
        }
        
        .signature-modal .modal-body {
            min-height: 250px;
        }
        
        .signature-pad {
            border: 2px dashed #0d6efd;
            border-radius: 5px;
            background: white;
            width: 100%;
            height: 200px;
        }
        
        /* Print Styles */
        @media print {
            body { 
                padding: 0; 
                background: #fff;
                margin: 0;
            }
            .report-card {
                box-shadow: none;
                padding: 5mm;
                margin: 0;
                width: 100%;
                min-height: auto;
            }
            .action-buttons { display: none; }
            .watermark img { opacity: 0.05; }
            .editable-field { cursor: default; }
            .editable-field:hover { background-color: transparent; outline: none; }
            .signature-actions { display: none; }
            .signature-canvas-container { border: 1px solid #000; }
            @page { 
                margin: 0.3cm;
                size: A4;
            }
        }
    </style>
</head>
<body>
    <!-- Action Buttons -->
    <div class="action-buttons">
        <button class="btn btn-primary" onclick="window.print()">
            <i class="fas fa-print"></i> Print
        </button>
        <button class="btn btn-success" onclick="downloadPDF()" style="display:none">
            <i class="fas fa-file-pdf"></i> PDF
        </button>
        <button class="btn btn-warning" onclick="toggleEditMode()" id="editModeBtn">
            <i class="fas fa-edit"></i> <span id="editModeText">Edit</span>
        </button>
        <button class="btn btn-info" onclick="saveAllChanges()" id="saveChangesBtn" style="display: none;">
            <i class="fas fa-save"></i> Save
        </button>
        <button class="btn btn-<?php echo $isPublished ? 'secondary' : 'success'; ?>"
                onclick="publishReport(<?php echo $isPublished ? 'false' : 'true'; ?>)"
                id="publishBtn"
                title="<?php echo $isPublished ? 'Published ' . ($publishedAt ? 'on ' . date('d M Y H:i', strtotime($publishedAt)) : '') : 'Not yet published to parent portal'; ?>">
            <i class="fas fa-<?php echo $isPublished ? 'eye-slash' : 'paper-plane'; ?>"></i>
            <?php echo $isPublished ? ' Unpublish' : ' Publish to Parents'; ?>
        </button>
    </div>
    
    <!-- Watermark -->
    <div class="watermark">
        <img src="<?php echo $logoPath; ?>" alt="School Logo">
    </div>
    
    <!-- Report Card -->
    <div class="report-card" id="reportCard">
        <!-- Header -->
        <div class="report-header">
            <?php if (file_exists($logoPath)): ?>
            <img src="<?php echo $logoPath; ?>" alt="School Logo" class="school-logo">
            <?php endif; ?>
            <div class="school-name"><?php echo strtoupper($settings['school_name'] ?? 'REGINAMUNDI INTERNATIONAL SCHOOL'); ?></div>
            <div class="school-address"><?php echo strtoupper($settings['school_address'] ?? 'P.O. BOX AF 1691, ADENTA – ACCRA'); ?></div>
            <div class="school-contact"><?php echo $settings['school_phone'] ?? '024 466 50 55 , 055 526 02 65'; ?></div>
            <div class="school-email"><?php echo $settings['school_email'] ?? 'REGINAMUN323@GMAIL.COM'; ?></div>
        </div>
        
        <!-- Title -->
        <div class="report-title">
            TERMINAL REPORT (<?php echo strtoupper($student['class']); ?>)
        </div>
        
        <!-- Student Info Row - Like template -->
      <!-- Student Info Row - Like template -->
<div class="student-info-row">
    <div class="info-item">
        <span class="info-label">NAME:</span> <?php echo strtoupper($student['first_name'] . ' ' . $student['last_name']); ?>
    </div>
    <div class="info-item">
        <span class="info-label">NO ON ROLL:</span> <?php echo $classSize; ?>
    </div>
    <div class="info-item">
        <span class="info-label">TERM:</span> <?php echo $termFormatted; ?>
    </div>
    <div class="info-item">
        <span class="info-label">CLASS:</span> <?php echo $student['class']; ?>
    </div>
</div>
        
        <!-- Dates Row -->
        <div class="dates-row">
            <div class="date-item">
                <span class="info-label">CLOSING DATE:</span> 
                <span class="editable-field" data-field="closing_date" data-type="date"><?php echo $closingDateFormatted; ?></span>
            </div>
            <div class="date-item">
                <span class="info-label">ACADEMIC YEAR:</span> <?php echo $academic_year; ?>
            </div>
            <div class="date-item">
                <span class="info-label">RE-OPENING:</span> 
                <span class="editable-field" data-field="reopening_date" data-type="date"><?php echo $reopeningDateFormatted; ?></span>
            </div>
            <div class="date-item">
                <span class="info-label">TOTAL MARKS:</span> <strong><?php echo round($totalMarks, 0); ?></strong>
            </div>
           <div class="date-item">
    <span class="info-label">POSITION:</span> 
    <strong>
        <?php 
        // Format position with proper suffix and show out of class size
        echo getPositionSuffix($position) . ' OUT OF ' . $classSize; 
        ?>
    </strong>
</div>
        </div>
        
        <!-- Subject Results Table -->
        <table class="results-table">
            <thead>
                <tr>
                    <th width="25%">SUBJECT</th>
                    <th width="12%">CLASS SCORE (50%)</th>
                    <th width="12%">EXAMS SCORE (50%)</th>
                    <th width="12%">TOTAL (100%)</th>
                    <th width="8%">GRADE</th>
                    <th width="31%">REMARKS</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($subjects as $subject): ?>
                <?php 
                    $score = $scores[$subject['subject_id']] ?? null;
                    $classScore = $score ? $score['weighted_class_score'] : 0;
                    $examScore = $score ? $score['weighted_exam_score'] : 0;
                    $totalScore = $score ? $score['total_score'] : 0;
                    $grade = $score ? $score['grade'] : 'W';
                    $remark = $score ? $score['remark'] : 'N/A';
                ?>
                <tr>
                    <td class="subject-col"><?php echo strtoupper($subject['subject_name']); ?></td>
                    <td>
                        <span class="editable-field" data-field="class_score" data-subject="<?php echo $subject['subject_id']; ?>" data-type="number">
                            <?php echo round($classScore, 0); ?>
                        </span>
                    </td>
                    <td>
                        <span class="editable-field" data-field="exam_score" data-subject="<?php echo $subject['subject_id']; ?>" data-type="number">
                            <?php echo round($examScore, 0); ?>
                        </span>
                    </td>
                    <td><strong><?php echo round($totalScore, 0); ?></strong></td>
                    <td class="grade-<?php echo strtolower($grade); ?>"><?php echo $grade; ?></td>
                    <td><?php echo $remark; ?></td>
                </tr>
                <?php endforeach; ?>
                <tr class="total-row">
                    <td colspan="3" style="text-align: right;"><strong>TOTAL</strong></td>
                    <td><strong><?php echo round($totalMarks, 0); ?></strong></td>
                    <td colspan="2"></td>
                </tr>
            </tbody>
        </table>
        
        <!-- Attendance & Conduct Section - Like template -->
        <div class="info-section">
            <div class="info-row">
                <div class="info-cell">
                    <strong>ATTENDANCE:</strong> 
                    <span class="editable-field" data-field="attendance" data-type="number"><?php echo $attendance; ?></span>
                    <span> OUT OF </span>
                    <span class="editable-field" data-field="attendance_total_days" data-type="number"><?php echo $totalSchoolDays; ?></span>
                </div>
                <div class="info-cell">
                    <strong>PROMOTED TO:</strong> 
                    <span class="editable-field" data-field="promoted_to" data-type="text"><?php echo $promotedTo; ?></span>
                </div>
            </div>
            <div class="info-row">
                <div class="info-cell">
                    <strong>CONDUCT:</strong> 
                    <span class="editable-field" data-field="conduct" data-type="text"><?php echo $conduct; ?></span>
                </div>
                <div class="info-cell">
                    <strong>INTEREST:</strong> 
                    <span class="editable-field" data-field="interest" data-type="text"><?php echo $interest; ?></span>
                </div>
            </div>
        </div>
        
        <!-- Teacher Remark Section -->
        <div class="remark-section">
            <div class="remark-header">CLASS TEACHER'S REMARKS:</div>
            <div class="remark-content">
                <span class="editable-field" data-field="teacher_remark" data-type="textarea"><?php echo $teacherRemark; ?></span>
            </div>
        </div>

        <!-- Head Teacher Remark Section (shown on the GES standard report) -->
        <div class="remark-section">
            <div class="remark-header">HEAD TEACHER'S REMARKS:</div>
            <div class="remark-content">
                <span class="editable-field" data-field="headteacher_remark" data-type="textarea"><?php echo $headteacherRemark; ?></span>
            </div>
        </div>

        <!-- Signatures Section -->
        <div class="signature-section">
            <div class="signature-box">
                <div class="signature-canvas-container" id="director-signature-container">
                    <?php if (!empty($directorSignature) && file_exists(__DIR__ . '/../../' . $directorSignature)): ?>
                        <img src="../../<?php echo htmlspecialchars($directorSignature); ?>" class="signature-image" id="director-signature-img">
                    <?php else: ?>
                        <canvas class="signature-canvas" id="director-signature" width="150" height="50"></canvas>
                    <?php endif; ?>
                </div>
                <div class="signature-actions">
                    <button class="btn btn-sm btn-primary signature-btn" onclick="openSignatureModal('director')">
                        Sign
                    </button>
                    <button class="btn btn-sm btn-danger signature-btn" onclick="clearSignature('director')">
                        Clear
                    </button>
                </div>
                <div class="signature-label">DIRECTOR'S SIGNATURE</div>
            </div>
            
            <div class="signature-box">
                <div class="signature-canvas-container" id="headteacher-signature-container">
                    <?php if (!empty($headteacherSignature) && file_exists(__DIR__ . '/../../' . $headteacherSignature)): ?>
                        <img src="../../<?php echo htmlspecialchars($headteacherSignature); ?>" class="signature-image" id="headteacher-signature-img">
                    <?php else: ?>
                        <canvas class="signature-canvas" id="headteacher-signature" width="150" height="50"></canvas>
                    <?php endif; ?>
                </div>
                <div class="signature-actions">
                    <button class="btn btn-sm btn-primary signature-btn" onclick="openSignatureModal('headteacher')">
                        Sign
                    </button>
                    <button class="btn btn-sm btn-danger signature-btn" onclick="clearSignature('headteacher')">
                        Clear
                    </button>
                </div>
                <div class="signature-label">HEAD TEACHER'S SIGNATURE</div>
            </div>
            
            <div class="signature-box">
                <div class="signature-canvas-container" id="classteacher-signature-container">
                    <?php if (!empty($classTeacherSignature) && file_exists(__DIR__ . '/../../' . $classTeacherSignature)): ?>
                        <img src="../../<?php echo htmlspecialchars($classTeacherSignature); ?>" class="signature-image" id="classteacher-signature-img">
                    <?php else: ?>
                        <canvas class="signature-canvas" id="classteacher-signature" width="150" height="50"></canvas>
                    <?php endif; ?>
                </div>
                <div class="signature-actions">
                    <button class="btn btn-sm btn-primary signature-btn" onclick="openSignatureModal('classteacher')">
                        Sign
                    </button>
                    <button class="btn btn-sm btn-danger signature-btn" onclick="clearSignature('classteacher')">
                        Clear
                    </button>
                </div>
                <div class="signature-label">CLASS TEACHER'S SIGNATURE</div>
            </div>
            
            <div class="signature-box">
                <div class="signature-canvas-container" style="border: none; background: transparent;"></div>
                <div style="height: 25px;"></div>
                <div class="signature-label">NOTES</div>
            </div>
        </div>
        
        <!-- Bottom Section - Stamp and Grading -->
        <div class="bottom-section">
            <!-- School Stamp -->
            <div class="stamp-section">
                <div class="stamp-label">SCHOOL'S STAMP</div>
                <div class="stamp-space">
                    
                </div>
                <div class="stamp-text"><?php echo strtoupper($settings['school_name'] ?? 'REGINAMUNDI INTERNATIONAL SCHOOL'); ?></div>
            </div>
            
            <!-- Grading Reference -->
            <table class="grading-reference">
                <thead>
                    <tr>
                        <th>MARKS</th>
                        <th>GRADE</th>
                        <th>REMARK</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($gradeBoundaries as $gb):
                        $gbMax = (int) $gb['max_score'];
                        $gbMin = (int) $gb['min_score'];
                        $gbRange = $gbMin === 0 ? $gbMax . ' &amp; Below' : $gbMax . ' - ' . $gbMin;
                    ?>
                    <tr><td><?= $gbRange ?></td><td><?= htmlspecialchars($gb['grade']) ?></td><td><?= htmlspecialchars($gb['remark']) ?></td></tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- School Footer -->
        <div class="school-footer">
            <?php echo strtoupper($settings['school_name'] ?? 'REGINAMUNDI INTERNATIONAL SCHOOL'); ?>
        </div>
    </div>

    <!-- Signature Modal -->
    <div class="modal fade" id="signatureModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="signatureModalLabel">Add Signature</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <canvas id="signature-pad" class="signature-pad" width="400" height="200"></canvas>
                    <div class="d-flex gap-2 mt-3 justify-content-center">
                        <button class="btn btn-sm btn-primary" onclick="saveSignature()">
                            <i class="fas fa-check"></i> Save
                        </button>
                        <button class="btn btn-sm btn-warning" onclick="clearSignaturePad()">
                            <i class="fas fa-eraser"></i> Clear
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="undoSignature()">
                            <i class="fas fa-undo"></i> Undo
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
    
    <script>
        // Global variables
        let editMode = false;
        let signaturePad = null;
        let currentSignatureType = '';
        let signatureModal = null;
        
        // Initialize on load
        $(document).ready(function() {
            initializeEditableFields();
            initializeSignaturePads();
            
            // Initialize signature modal
            signatureModal = new bootstrap.Modal(document.getElementById('signatureModal'));
            
            // Initialize signature pads when modal is shown
            $('#signatureModal').on('shown.bs.modal', function() {
                initializeSignaturePad();
            });
            
            // Clean up when modal is hidden
            $('#signatureModal').on('hidden.bs.modal', function() {
                if (signaturePad) {
                    signaturePad.off();
                    signaturePad = null;
                }
            });
        });

        // Window resize handler for signature pad
        window.addEventListener('resize', function() {
            if (signaturePad) {
                const canvas = document.getElementById('signature-pad');
                const container = canvas.parentElement;
                const containerWidth = container.offsetWidth;
                
                // Save current signature data
                const data = signaturePad.toData();
                
                // Resize canvas
                canvas.width = containerWidth;
                canvas.height = 200;
                
                // Restore signature
                if (data && data.length > 0) {
                    signaturePad.fromData(data);
                }
            }
        });

        // ============= EDIT MODE FUNCTIONS =============
        
        // Toggle edit mode
        function toggleEditMode() {
            editMode = !editMode;
            const fields = document.querySelectorAll('.editable-field');
            const saveBtn = document.getElementById('saveChangesBtn');
            const editModeText = document.getElementById('editModeText');
            
            fields.forEach(field => {
                if (editMode) {
                    field.classList.add('editing');
                    makeFieldEditable(field);
                } else {
                    field.classList.remove('editing');
                    makeFieldReadonly(field);
                }
            });
            
            if (editMode) {
                saveBtn.style.display = 'inline-flex';
                editModeText.textContent = 'View';
            } else {
                saveBtn.style.display = 'none';
                editModeText.textContent = 'Edit';
            }
        }
        
        // Initialize editable fields with double-click
        function initializeEditableFields() {
            document.querySelectorAll('.editable-field').forEach(field => {
                field.addEventListener('dblclick', function(e) {
                    if (editMode) {
                        makeFieldEditable(this);
                    }
                });
            });
        }
        
        // Make field editable
        function makeFieldEditable(field) {
            if (field.querySelector('input') || field.querySelector('textarea')) return;
            
            const fieldType = field.dataset.type || 'text';
            const currentValue = field.textContent.trim();
            
            if (fieldType === 'textarea') {
                const textarea = document.createElement('textarea');
                textarea.className = 'editable-input';
                textarea.value = currentValue;
                textarea.style.minHeight = '40px';
                textarea.style.width = '100%';
                field.innerHTML = '';
                field.appendChild(textarea);
                textarea.focus();
                
                textarea.addEventListener('blur', function() {
                    field.textContent = this.value;
                });
            } else if (fieldType === 'date') {
                const input = document.createElement('input');
                input.type = 'date';
                input.className = 'editable-input';
                
                // Try to parse current date
                try {
                    const date = new Date(currentValue);
                    if (!isNaN(date.getTime())) {
                        input.value = date.toISOString().split('T')[0];
                    }
                } catch (e) {}
                
                field.innerHTML = '';
                field.appendChild(input);
                input.focus();
                
                input.addEventListener('blur', function() {
                    if (this.value) {
                        const date = new Date(this.value);
                        field.textContent = date.toLocaleDateString('en-GB', {
                            day: 'numeric',
                            month: 'long',
                            year: 'numeric'
                        }).toUpperCase();
                    }
                });
            } else {
                const input = document.createElement('input');
                input.type = fieldType === 'number' ? 'number' : 'text';
                input.className = 'editable-input';
                input.value = currentValue;
                input.style.width = fieldType === 'number' ? '40px' : '100%';
                
                if (fieldType === 'number') {
                    input.step = '1';
                    input.min = '0';
                    input.max = '100';
                }
                
                field.innerHTML = '';
                field.appendChild(input);
                input.focus();
                
                input.addEventListener('blur', function() {
                    field.textContent = this.value;
                    if (field.dataset.field === 'class_score' || field.dataset.field === 'exam_score') {
                        updateSubjectTotal(field);
                    }
                });
                
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        field.textContent = this.value;
                        if (field.dataset.field === 'class_score' || field.dataset.field === 'exam_score') {
                            updateSubjectTotal(field);
                        }
                    }
                });
            }
        }
        
        // Make field readonly
        function makeFieldReadonly(field) {
            const input = field.querySelector('input, textarea');
            if (input) {
                field.textContent = input.value;
            }
        }
        
        // Update subject total when scores change
        function updateSubjectTotal(field) {
            const row = field.closest('tr');
            if (!row) return;
            
            const classScoreField = row.querySelector('[data-field="class_score"]');
            const examScoreField = row.querySelector('[data-field="exam_score"]');
            
            if (classScoreField && examScoreField) {
                const classScore = parseFloat(classScoreField.textContent) || 0;
                const examScore = parseFloat(examScoreField.textContent) || 0;
                const total = classScore + examScore;
                
                const totalCell = row.querySelector('td:nth-child(4) strong');
                if (totalCell) {
                    totalCell.textContent = total.toFixed(0);
                }
                
                // Update grade based on total
                updateGradeAndRemark(row, total);
                
                // Update total marks at bottom
                updateTotalMarks();
            }
        }
        
        // Update grade and remark based on total
        function updateGradeAndRemark(row, total) {
            let grade = 'W';
            let remark = 'Weak';
            
            if (total >= 90) { grade = 'A'; remark = 'EXCELLENT'; }
            else if (total >= 80) { grade = 'B'; remark = 'VERY GOOD'; }
            else if (total >= 70) { grade = 'C'; remark = 'GOOD'; }
            else if (total >= 60) { grade = 'D'; remark = 'SATISFACTORY'; }
            else if (total >= 50) { grade = 'E'; remark = 'PASS'; }
            
            const gradeCell = row.querySelector('td:nth-child(5)');
            const remarkCell = row.querySelector('td:nth-child(6)');
            
            if (gradeCell) {
                gradeCell.textContent = grade;
                gradeCell.className = 'grade-' + grade.toLowerCase();
            }
            
            if (remarkCell) {
                remarkCell.textContent = remark;
            }
        }
        
        // Update total marks at bottom
        function updateTotalMarks() {
            let total = 0;
            document.querySelectorAll('.results-table tbody tr:not(.total-row)').forEach(row => {
                const totalCell = row.querySelector('td:nth-child(4) strong');
                if (totalCell) {
                    total += parseFloat(totalCell.textContent) || 0;
                }
            });
            
            const totalRow = document.querySelector('.total-row td:nth-child(2) strong');
            if (totalRow) {
                totalRow.textContent = total.toFixed(0);
            }
        }
        
        // ============= SIGNATURE FUNCTIONS =============
        
        // Initialize signature pads on page load
        function initializeSignaturePads() {
            const canvasIds = ['director-signature', 'headteacher-signature', 'classteacher-signature'];
            
            canvasIds.forEach(canvasId => {
                const canvas = document.getElementById(canvasId);
                const img = document.getElementById(canvasId.replace('signature', 'signature-img'));
                
                if (canvas && (!img || img.style.display === 'none')) {
                    initCanvas(canvasId);
                }
            });
        }
        
        // Initialize a single canvas
        function initCanvas(canvasId) {
            const canvas = document.getElementById(canvasId);
            if (canvas) {
                canvas.width = canvas.offsetWidth || 150;
                canvas.height = canvas.offsetHeight || 50;
                
                const ctx = canvas.getContext('2d');
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.strokeStyle = '#ccc';
                ctx.lineWidth = 1;
                ctx.strokeRect(0, 0, canvas.width, canvas.height);
            }
        }
        
        // Initialize signature pad in modal
        function initializeSignaturePad() {
            const canvas = document.getElementById('signature-pad');
            const container = canvas.parentElement;
            const containerWidth = container.offsetWidth;
            
            canvas.width = containerWidth;
            canvas.height = 200;
            
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            signaturePad = new SignaturePad(canvas, {
                backgroundColor: 'rgb(255, 255, 255)',
                penColor: 'rgb(0, 0, 0)',
                velocityFilterWeight: 0.7,
                minWidth: 0.5,
                maxWidth: 2.5,
                throttle: 16
            });
            
            loadExistingSignature();
        }
        
        // Load existing signature into pad
        function loadExistingSignature() {
            let existingSignature = null;
            
            if (currentSignatureType === 'director') {
                const img = document.getElementById('director-signature-img');
                const canvas = document.getElementById('director-signature');
                if (img && img.style.display !== 'none') {
                    existingSignature = img.src;
                } else if (canvas) {
                    const ctx = canvas.getContext('2d');
                    const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
                    const hasDrawing = pixelData.some(value => value !== 0);
                    if (hasDrawing) {
                        existingSignature = canvas.toDataURL();
                    }
                }
            } else if (currentSignatureType === 'headteacher') {
                const img = document.getElementById('headteacher-signature-img');
                const canvas = document.getElementById('headteacher-signature');
                if (img && img.style.display !== 'none') {
                    existingSignature = img.src;
                } else if (canvas) {
                    const ctx = canvas.getContext('2d');
                    const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
                    const hasDrawing = pixelData.some(value => value !== 0);
                    if (hasDrawing) {
                        existingSignature = canvas.toDataURL();
                    }
                }
            } else if (currentSignatureType === 'classteacher') {
                const img = document.getElementById('classteacher-signature-img');
                const canvas = document.getElementById('classteacher-signature');
                if (img && img.style.display !== 'none') {
                    existingSignature = img.src;
                } else if (canvas) {
                    const ctx = canvas.getContext('2d');
                    const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
                    const hasDrawing = pixelData.some(value => value !== 0);
                    if (hasDrawing) {
                        existingSignature = canvas.toDataURL();
                    }
                }
            }
            
            if (existingSignature && signaturePad) {
                try {
                    signaturePad.fromDataURL(existingSignature);
                } catch (e) {
                    console.log('Could not load existing signature');
                }
            }
        }
        
        // Open signature modal
        function openSignatureModal(type) {
            currentSignatureType = type;
            
            let title = '';
            if (type === 'director') title = "Director's Signature";
            else if (type === 'headteacher') title = "Head Teacher's Signature";
            else if (type === 'classteacher') title = "Class Teacher's Signature";
            
            document.getElementById('signatureModalLabel').textContent = 'Add ' + title;
            signatureModal.show();
        }
        
        // Save signature from modal
        function saveSignature() {
            if (!signaturePad) {
                alert('Signature pad not initialized');
                return;
            }
            
            if (signaturePad.isEmpty()) {
                alert('Please draw a signature first');
                return;
            }
            
            const signatureData = signaturePad.toDataURL();
            
            let targetCanvasId = '';
            let targetImgId = '';
            
            if (currentSignatureType === 'director') {
                targetCanvasId = 'director-signature';
                targetImgId = 'director-signature-img';
            } else if (currentSignatureType === 'headteacher') {
                targetCanvasId = 'headteacher-signature';
                targetImgId = 'headteacher-signature-img';
            } else if (currentSignatureType === 'classteacher') {
                targetCanvasId = 'classteacher-signature';
                targetImgId = 'classteacher-signature-img';
            }
            
            const targetCanvas = document.getElementById(targetCanvasId);
            if (targetCanvas) {
                const ctx = targetCanvas.getContext('2d');
                const img = new Image();
                img.onload = function() {
                    ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
                    ctx.fillStyle = 'white';
                    ctx.fillRect(0, 0, targetCanvas.width, targetCanvas.height);
                    ctx.drawImage(img, 0, 0, targetCanvas.width, targetCanvas.height);
                    
                    ctx.strokeStyle = '#ccc';
                    ctx.lineWidth = 1;
                    ctx.strokeRect(0, 0, targetCanvas.width, targetCanvas.height);
                };
                img.src = signatureData;
            }
            
            const targetImg = document.getElementById(targetImgId);
            if (targetImg) {
                targetImg.style.display = 'none';
            }
            
            signatureModal.hide();
            showNotification('Signature saved successfully!', 'success');
        }
        
        // Clear signature pad in modal
        function clearSignaturePad() {
            if (signaturePad) {
                signaturePad.clear();
            }
        }
        
        // Undo last stroke in modal
        function undoSignature() {
            if (signaturePad) {
                const data = signaturePad.toData();
                if (data && data.length > 0) {
                    data.pop();
                    signaturePad.fromData(data);
                }
            }
        }
        
        // Clear signature from report
        function clearSignature(type) {
            if (!confirm('Are you sure you want to clear this signature?')) {
                return;
            }
            
            let canvasId = '';
            let imgId = '';
            
            if (type === 'director') {
                canvasId = 'director-signature';
                imgId = 'director-signature-img';
            } else if (type === 'headteacher') {
                canvasId = 'headteacher-signature';
                imgId = 'headteacher-signature-img';
            } else if (type === 'classteacher') {
                canvasId = 'classteacher-signature';
                imgId = 'classteacher-signature-img';
            }
            
            const canvas = document.getElementById(canvasId);
            if (canvas) {
                const ctx = canvas.getContext('2d');
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                ctx.strokeStyle = '#ccc';
                ctx.lineWidth = 1;
                ctx.strokeRect(0, 0, canvas.width, canvas.height);
            }
            
            const img = document.getElementById(imgId);
            if (img) {
                img.style.display = 'none';
            }
            
            showNotification('Signature cleared', 'info');
        }
        
        // ============= PUBLISH FUNCTION =============

        function publishReport(publish) {
            const btn = document.getElementById('publishBtn');
            const orig = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>' + (publish ? 'Publishing…' : 'Unpublishing…');
            $.ajax({
                url: 'ajax/publish_report.php',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    student_id: <?php echo (int)$student_id; ?>,
                    term: <?php echo json_encode($term); ?>,
                    academic_year: <?php echo json_encode($academic_year); ?>,
                    publish: publish
                }),
                dataType: 'json',
                success: function(r) {
                    if (r.success) {
                        showNotification(r.message, 'success');
                        if (publish) {
                            btn.className = btn.className.replace('btn-success', 'btn-secondary');
                            btn.innerHTML = '<i class="fas fa-eye-slash"></i> Unpublish';
                            btn.title = 'Published just now';
                            btn.onclick = function() { publishReport(false); };
                        } else {
                            btn.className = btn.className.replace('btn-secondary', 'btn-success');
                            btn.innerHTML = '<i class="fas fa-paper-plane"></i> Publish to Parents';
                            btn.title = 'Not yet published to parent portal';
                            btn.onclick = function() { publishReport(true); };
                        }
                    } else {
                        showNotification('Error: ' + r.message, 'danger');
                        btn.innerHTML = orig;
                    }
                },
                error: function() { showNotification('Server error. Please try again.', 'danger'); btn.innerHTML = orig; },
                complete: function() { btn.disabled = false; }
            });
        }

        // ============= NOTIFICATION FUNCTION =============

        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
            notification.style.zIndex = '9999';
            notification.style.fontSize = '12px';
            notification.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" style="font-size: 10px;"></button>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.remove();
            }, 3000);
        }
        
        // ============= SAVE CHANGES FUNCTION =============
        
        function saveAllChanges() {
            const saveBtn = document.getElementById('saveChangesBtn');
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
            saveBtn.disabled = true;
            
            const reportData = {
                student_id: <?php echo $student_id; ?>,
                term: '<?php echo $term; ?>',
                academic_year: '<?php echo $academic_year; ?>',
                fields: {},
                signatures: {},
                scores: []
            };
            
            document.querySelectorAll('.editable-field').forEach(field => {
                let value = field.textContent.trim();
                const input = field.querySelector('input, textarea');
                if (input) {
                    value = input.value.trim();
                }
                
                const fieldName = field.dataset.field;
                const subjectId = field.dataset.subject;
                
                if (subjectId) {
                    reportData.scores.push({
                        subject_id: subjectId,
                        field: fieldName,
                        value: value
                    });
                } else {
                    reportData.fields[fieldName] = value;
                }
            });
            
            const signatureTypes = ['director', 'headteacher', 'classteacher'];
            
            signatureTypes.forEach(type => {
                const canvas = document.getElementById(type + '-signature');
                const img = document.getElementById(type + '-signature-img');
                
                if (canvas) {
                    const ctx = canvas.getContext('2d');
                    const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
                    const hasDrawing = pixelData.some(value => value !== 0);
                    
                    if (hasDrawing) {
                        reportData.signatures[type] = canvas.toDataURL();
                    }
                } else if (img && img.style.display !== 'none') {
                    reportData.signatures[type] = img.src;
                }
            });
            
            $.ajax({
                url: 'ajax/save_report_details.php',
                type: 'POST',
                data: JSON.stringify(reportData),
                contentType: 'application/json',
                dataType: 'json',
                timeout: 30000,
                success: function(response) {
                    if (response.success) {
                        showNotification('All changes saved successfully!', 'success');
                        
                        if (editMode) {
                            toggleEditMode();
                        }
                        
                        setTimeout(() => {
                            location.reload();
                        }, 1500);
                    } else {
                        showNotification('Error: ' + response.message, 'danger');
                    }
                },
                error: function(xhr, status, error) {
                    showNotification('Error saving changes. Please try again.', 'danger');
                },
                complete: function() {
                    saveBtn.innerHTML = originalText;
                    saveBtn.disabled = false;
                }
            });
        }
        
        // ============= PDF DOWNLOAD FUNCTION =============
        
        function downloadPDF() {
            const studentName = '<?php echo $student["first_name"] . "_" . $student["last_name"]; ?>';
            const term = '<?php echo $term; ?>';
            window.location.href = 'report_pdf.php?student_id=<?php echo $student_id; ?>&term=<?php echo urlencode($term); ?>&academic_year=<?php echo $academic_year; ?>';
        }
    </script>
</body>
</html>