<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../index.php');
    exit;
}

// Role-based access control
$allowed_roles = ['admin', 'director', 'supervisor', 'headteacher', 'tutor']; // Adjust per page

if (!in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: ../../dashboard.php?error=access_denied');
    exit;
}

require_once '../../config.php';
requireModule('terminal_reports');
$conn = getDBConnection();

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

// Classes — primary: Class Management; fallback: students
$classes = [];
$result = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
if ($result) { while ($row = $result->fetch_assoc()) $classes[] = $row['class_name']; }
$result2 = $conn->query("SELECT DISTINCT class FROM students WHERE status = 'active' AND class IS NOT NULL ORDER BY class");
if ($result2) { while ($row = $result2->fetch_assoc()) { if (!in_array($row['class'], $classes)) $classes[] = $row['class']; } }
sort($classes);

// For tutor role: restrict to assigned classes only
$is_tutor = ($_SESSION['role'] ?? '') === 'tutor';
$teacher_classes  = $_SESSION['teacher_classes']  ?? [];
$teacher_subjects = $_SESSION['teacher_subjects'] ?? [];

if ($is_tutor && !empty($teacher_classes)) {
    $classes = array_values(array_filter($classes, fn($c) => in_array($c, $teacher_classes, true)));
}

// Get all subjects
$subjects = [];
$result = $conn->query("SELECT * FROM subjects WHERE active = 1 OR active = 'yes' ORDER BY subject_name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $subjects[] = $row;
    }
}

// For tutor role: restrict to taught subjects only
if ($is_tutor && !empty($teacher_subjects)) {
    $subjects = array_values(array_filter($subjects, fn($s) => in_array($s['subject_name'], $teacher_subjects, true)));
}

// Get academic years from existing data
$academic_years = [];
$result = $conn->query("SELECT DISTINCT academic_year FROM scores ORDER BY academic_year DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $academic_years[] = $row['academic_year'];
    }
}
// Use settings-based current year as default
$currentAcademicYear = getAcademicYear();
if (!in_array($currentAcademicYear, $academic_years)) {
    array_unshift($academic_years, $currentAcademicYear);
}

// Terms — current term pre-selected from settings
$terms = ['First Term', 'Second Term', 'Third Term'];
$currentTerm = getCurrentTerm();

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Terminal Reports - EduTrack PRO</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 rel="stylesheet" href="../../css/style.css">
    <style>
        .report-nav-card {
            transition: transform 0.2s, box-shadow 0.2s;
            cursor: pointer;
            border: 2px solid transparent;
        }
        .report-nav-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
            border-color: #0d6efd;
        }
        .report-nav-card.active {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .subject-badge {
            font-size: 0.75rem;
            padding: 3px 8px;
        }
        
        /* Score Entry Table Styles */
        .student-list-table {
            font-size: 0.9rem;
        }
        .student-list-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .score-status-badge {
            font-size: 0.75rem;
            padding: 3px 8px;
        }
        .status-complete {
            background-color: #d4edda;
            color: #155724;
        }
        .status-incomplete {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-none {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        /* Modal Styles */
        .score-entry-modal .modal-dialog {
            max-width: 800px;
        }
        
        .subject-score-card {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 12px;
            transition: all 0.2s;
        }
        
        .subject-score-card:hover {
            background-color: #e9ecef;
            border-color: #0d6efd;
        }
        
        .subject-score-card .subject-name {
            font-weight: 600;
            font-size: 1rem;
            margin-bottom: 8px;
            color: #333;
        }
        
        .subject-score-card .score-inputs {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .subject-score-card .score-input {
            flex: 1;
            min-width: 120px;
        }
        
        .subject-score-card .score-input label {
            font-size: 0.8rem;
            color: #666;
            margin-bottom: 2px;
        }
        
        .subject-score-card .score-input input {
            width: 100%;
            padding: 6px 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 0.9rem;
        }
        
        .subject-score-card .score-input input:focus {
            outline: none;
            border-color: #0d6efd;
            box-shadow: 0 0 0 3px rgba(13,110,253,0.1);
        }
        
        .subject-score-card .score-total {
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 80px;
            background-color: #fff;
            border-radius: 4px;
            padding: 0 10px;
            font-weight: 600;
        }
        
        .subject-score-card .grade-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 600;
            margin-left: 10px;
        }
        
        .grade-a { background-color: #d4edda; color: #155724; }
        .grade-b { background-color: #cce5ff; color: #004085; }
        .grade-c { background-color: #fff3cd; color: #856404; }
        .grade-d { background-color: #ffeeba; color: #856404; }
        .grade-e { background-color: #f8d7da; color: #721c24; }
        .grade-w { background-color: #f5c6cb; color: #721c24; }
        
        .summary-card {
            background-color: #fff;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #dee2e6;
        }
        
        .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-label {
            color: #666;
            font-size: 0.9rem;
        }
        
        .summary-value {
            font-weight: 600;
            color: #333;
        }
        
        @media (max-width: 768px) {
            .subject-score-card .score-inputs {
                flex-direction: column;
                gap: 10px;
            }
            
            .subject-score-card .score-total {
                width: 100%;
                padding: 8px;
                margin-top: 5px;
            }
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar('modules/reports/' . basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="../../settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <!-- Page Content -->
            <main class="content">
                <div class="content-header">
                    <h2><i class="fas fa-file-alt me-2"></i>Terminal Reports</h2>
                    <p>Generate student report cards with scores, grades, and positions</p>

                    <div style="position:absolute; right:20px; display:flex; gap:8px;">
                        <a href="signatures.php">
                            <button type="button" class="btn btn-info">
                                <i class="fas fa-signature me-2"></i>Signatures
                            </button>
                        </a>
                        <a href="class_subjects.php">
                            <button type="button" class="btn btn-primary">
                                <i class="fas fa-print me-2"></i>Configure Subjects
                            </button>
                        </a>
                    </div>
                </div>

                <!-- Report Navigation Cards -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card report-nav-card" onclick="showSection('score-entry')">
                            <div class="card-body text-center py-4">
                                <i class="fas fa-pen fa-3x text-primary mb-3"></i>
                                <h5>Score Entry</h5>
                                <p class="text-muted mb-0">Enter class and exam scores for students</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card report-nav-card" onclick="showSection('generate-report')">
                            <div class="card-body text-center py-4">
                                <i class="fas fa-file-pdf fa-3x text-success mb-3"></i>
                                <h5>Generate Report</h5>
                                <p class="text-muted mb-0">View and print individual student reports</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card report-nav-card" onclick="showSection('subjects')">
                            <div class="card-body text-center py-4">
                                <i class="fas fa-book fa-3x text-warning mb-3"></i>
                                <h5>Manage Subjects</h5>
                                <p class="text-muted mb-0">Add, edit, or remove subjects</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Score Entry Section -->
                <div id="score-entry-section" class="report-section">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0"><i class="fas fa-pen me-2"></i>Score Entry</h5>
                        </div>
                        <div class="card-body">
                            <form id="scoreEntryForm" class="mb-4">
                                <div class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">Class</label>
                                        <select class="form-select" name="class" id="scoreClass" required>
                                            <option value="">Select Class</option>
                                            <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class; ?>"><?php echo $class; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Term</label>
                                        <select class="form-select" name="term" id="scoreTerm" required>
                                            <option value="">Select Term</option>
                                            <?php foreach ($terms as $term): ?>
                                            <option value="<?php echo $term; ?>" <?php echo $term === $currentTerm ? 'selected' : ''; ?>><?php echo $term; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Academic Year</label>
                                        <select class="form-select" name="academic_year" id="scoreYear" required>
                                            <?php foreach ($academic_years as $year): ?>
                                            <option value="<?php echo $year; ?>" <?php echo ($year === $currentAcademicYear) ? 'selected' : ''; ?>><?php echo $year; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="button" class="btn btn-primary w-100" onclick="loadStudentsForScores()">
                                            <i class="fas fa-search me-2"></i>Load Students
                                        </button>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <button type="button" class="btn btn-outline-secondary w-100" onclick="viewExamResults()">
                                            <i class="fas fa-file-alt me-2"></i>View Exam Results
                                        </button>
                                    </div>
                                </div>
                            </form>

                            <!-- Student List with Score Status -->
                            <div id="studentListContainer" style="display: none;">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h6 class="mb-0"><i class="fas fa-users me-2"></i>Students in Class</h6>
                                    <span class="badge bg-info" id="studentCount">0 students</span>
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-hover student-list-table">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Student ID</th>
                                                <th>Student Name</th>
                                                <th>Gender</th>
                                                <th>Scores Status</th>
                                                <th>Subjects Entered</th>
                                                <th>Total Marks</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="studentListBody">
                                            <!-- Populated via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Generate Report Section -->
                <div id="generate-report-section" class="report-section" style="display: none;">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-file-pdf me-2"></i>Generate Student Report</h5>
                        </div>
                        <div class="card-body">
                            <form id="reportForm">
                                <div class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">Class</label>
                                        <select class="form-select" name="class" id="reportClass" required onchange="loadStudentsForReport()">
                                            <option value="">Select Class</option>
                                            <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class; ?>"><?php echo $class; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Term</label>
                                        <select class="form-select" name="term" id="reportTerm" required>
                                            <option value="">Select Term</option>
                                            <?php foreach ($terms as $term): ?>
                                            <option value="<?php echo $term; ?>" <?php echo $term === $currentTerm ? 'selected' : ''; ?>><?php echo $term; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Academic Year</label>
                                        <select class="form-select" name="academic_year" id="reportYear" required>
                                            <?php foreach ($academic_years as $year): ?>
                                            <option value="<?php echo $year; ?>" <?php echo ($year === $currentAcademicYear) ? 'selected' : ''; ?>><?php echo $year; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Student</label>
                                        <select class="form-select" name="student_id" id="reportStudent" required disabled>
                                            <option value="">Select Student</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="row mt-3">
                                    <div class="col-12">
                                        <button type="button" class="btn btn-success" onclick="generateReport()">
                                            <i class="fas fa-file-alt me-2"></i>Generate Report
                                        </button>
                                        <button type="button" class="btn btn-primary ms-2" onclick="printReport()">
                                            <i class="fas fa-print me-2"></i>Print Report
                                        </button>
                                        <button style="display:none" type="button" class="btn btn-danger ms-2" onclick="downloadPDF()">
                                            <i class="fas fa-file-pdf me-2"></i>Download PDF
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Report Preview -->
                    <div id="reportPreview" class="mt-4" style="display: none;">
                        <iframe id="reportFrame" style="width: 100%; height: 600px; border: 1px solid #ddd; border-radius: 8px;"></iframe>
                    </div>
                </div>

                <!-- Subjects Management Section -->
                <div id="subjects-section" class="report-section" style="display: none;">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0"><i class="fas fa-book me-2"></i>Manage Subjects</h5>
                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addSubjectModal">
                                <i class="fas fa-plus me-2"></i>Add Subject
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Subject Name</th>
                                            <th>Subject Code</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($subjects as $index => $subject):
                                            $isActive = ($subject['active'] == 1 || $subject['active'] === 'yes');
                                        ?>
                                        <tr>
                                            <td><?php echo $index + 1; ?></td>
                                            <td><?php echo htmlspecialchars($subject['subject_name']); ?></td>
                                            <td><?php echo htmlspecialchars($subject['subject_code']); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $isActive ? 'success' : 'secondary'; ?>">
                                                    <?php echo $isActive ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-outline-primary" onclick="editSubject(<?php echo $subject['id']; ?>, '<?php echo htmlspecialchars($subject['subject_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($subject['subject_code'], ENT_QUOTES); ?>')">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-outline-<?php echo $isActive ? 'warning' : 'success'; ?>" onclick="toggleSubject(<?php echo $subject['id']; ?>, '<?php echo $isActive ? 'yes' : 'no'; ?>')">
                                                    <i class="fas fa-toggle-<?php echo $isActive ? 'off' : 'on'; ?>"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

            </main>

            <!-- Footer -->
            <footer class="footer">
                <p>&copy; 2024 EduTrack PRO. All rights reserved.</p>
            </footer>
        </div>
    </div>

    <!-- Score Entry Modal -->
    <div class="modal fade score-entry-modal" id="scoreEntryModal" tabindex="-1" aria-labelledby="scoreEntryModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="scoreEntryModalLabel">
                        <i class="fas fa-pen me-2"></i>Enter Scores
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="student-info-summary mb-4 p-3 bg-light rounded">
                        <div class="row">
                            <div class="col-md-6">
                                <p class="mb-1"><strong>Student:</strong> <span id="modalStudentName"></span></p>
                                <p class="mb-1"><strong>Student ID:</strong> <span id="modalStudentId"></span></p>
                            </div>
                            <div class="col-md-6">
                                <p class="mb-1"><strong>Class:</strong> <span id="modalStudentClass"></span></p>
                                <p class="mb-1"><strong>Term:</strong> <span id="modalTerm"></span> - <span id="modalAcademicYear"></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="summary-card">
                                <h6 class="mb-3">Summary</h6>
                                <div class="summary-item">
                                    <span class="summary-label">Total Subjects:</span>
                                    <span class="summary-value" id="totalSubjects">0</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">Subjects Entered:</span>
                                    <span class="summary-value" id="subjectsEntered">0</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">Total Marks:</span>
                                    <span class="summary-value" id="totalMarks">0</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">Average:</span>
                                    <span class="summary-value" id="averageMarks">0</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="subjectsScoreContainer">
                        <!-- Subject score cards will be loaded here -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Close
                    </button>
                    <button type="button" class="btn btn-primary" onclick="saveAllScores()">
                        <i class="fas fa-save me-2"></i>Save All Scores
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Subject Modal -->
    <div class="modal fade" id="addSubjectModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Subject</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="addSubjectForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Subject Name</label>
                            <input type="text" class="form-control" name="subject_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Subject Code</label>
                            <input type="text" class="form-control" name="subject_code" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Add Subject</button>
                    </div>
                </form>
            </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="../../js/main.js"></script>
    <script>
        const IS_TUTOR = <?= json_encode($is_tutor) ?>;
        const TEACHER_CLASSES  = <?= json_encode($teacher_classes) ?>;
        const TEACHER_SUBJECTS = <?= json_encode($teacher_subjects) ?>;

        let currentStudentId = null;
        let currentClass = null;
        let currentTerm = null;
        let currentAcademicYear = null;
        let subjects = <?php echo json_encode($subjects); ?>;
        
        // Navigation
        function showSection(section) {
            document.querySelectorAll('.report-section').forEach(s => s.style.display = 'none');
            document.getElementById(section + '-section').style.display = 'block';
            
            document.querySelectorAll('.report-nav-card').forEach(c => c.classList.remove('active'));
            event.currentTarget.classList.add('active');
        }

        // Load students for score entry
        function loadStudentsForScores() {
            const classVal = document.getElementById('scoreClass').value;
            const term = document.getElementById('scoreTerm').value;
            const year = document.getElementById('scoreYear').value;

            if (!classVal || !term || !year) {
                alert('Please select class, term, and academic year');
                return;
            }

            currentClass = classVal;
            currentTerm = term;
            currentAcademicYear = year;

            $.ajax({
                url: 'ajax/get_students_for_scores.php',
                type: 'POST',
                data: { 
                    class: classVal, 
                    term: term, 
                    academic_year: year 
                },
                success: function(response) {
                    document.getElementById('studentListBody').innerHTML = response;
                    document.getElementById('studentListContainer').style.display = 'block';
                    
                    // Update student count
                    const rowCount = document.getElementById('studentListBody').getElementsByTagName('tr').length;
                    document.getElementById('studentCount').textContent = rowCount + ' students';
                },
                error: function(xhr, status, error) {
                    alert('Error loading students: ' + error);
                }
            });
        }

        // Open score entry modal for a student
        function openScoreModal(studentId, studentName, studentIdNumber) {
            currentStudentId = studentId;
            
            // Set modal header info
            document.getElementById('modalStudentName').textContent = studentName;
            document.getElementById('modalStudentId').textContent = studentIdNumber;
            document.getElementById('modalStudentClass').textContent = currentClass;
            document.getElementById('modalTerm').textContent = currentTerm;
            document.getElementById('modalAcademicYear').textContent = currentAcademicYear;
            
            // Load subjects with existing scores
            loadStudentScores(studentId);
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('scoreEntryModal'));
            modal.show();
        }

        // Load student scores
        function loadStudentScores(studentId) {
            $.ajax({
                url: 'ajax/get_student_scores.php',
                type: 'POST',
                data: {
                    student_id: studentId,
                    term: currentTerm,
                    academic_year: currentAcademicYear
                },
                success: function(response) {
                    document.getElementById('subjectsScoreContainer').innerHTML = response;
                    updateSummary();
                }
            });
        }

        // Get (or create) the inline error element for a score card
        function getScoreErrorEl(card) {
            let errorEl = card.querySelector('.score-error');
            if (!errorEl) {
                errorEl = document.createElement('div');
                errorEl.className = 'score-error text-danger small mt-1';
                errorEl.style.display = 'none';
                const scoreInputs = card.querySelector('.score-inputs');
                scoreInputs.insertAdjacentElement('afterend', errorEl);
            }
            return errorEl;
        }

        // Validate a card's inputs against the subject's configured max scores.
        // Returns an error message string, or '' if valid.
        function validateScoreCard(card) {
            const classInput = card.querySelector('.class-score');
            const examInput = card.querySelector('.exam-score');

            // These MUST be rendered onto each .subject-score-card by
            // ajax/get_student_scores.php (data-max-class-score, data-max-exam-score,
            // data-class-score-percent, data-exam-score-percent). Fall back to the
            // same 50/50 defaults save_score.php uses if a card is missing them.
            const maxClass = parseFloat(card.dataset.maxClassScore) || 50;
            const maxExam = parseFloat(card.dataset.maxExamScore) || 50;

            const classRaw = classInput.value.trim();
            const examRaw = examInput.value.trim();
            const classScore = classRaw === '' ? 0 : parseFloat(classRaw);
            const examScore = examRaw === '' ? 0 : parseFloat(examRaw);

            let msg = '';
            let classBad = false, examBad = false;

            if (classRaw !== '' && (isNaN(classScore) || classScore < 0 || classScore > maxClass)) {
                msg = `Class score must be between 0 and ${maxClass}`;
                classBad = true;
            } else if (examRaw !== '' && (isNaN(examScore) || examScore < 0 || examScore > maxExam)) {
                msg = `Exam score must be between 0 and ${maxExam}`;
                examBad = true;
            }

            classInput.classList.toggle('is-invalid', classBad);
            examInput.classList.toggle('is-invalid', examBad);

            return msg;
        }

        // Calculate weighted total and grade for a subject, blocking invalid entries
        function calculateSubjectTotal(input) {
            const card = input.closest('.subject-score-card');
            const errorEl = getScoreErrorEl(card);

            const errorMsg = validateScoreCard(card);

            if (errorMsg) {
                errorEl.textContent = errorMsg;
                errorEl.style.display = 'block';
                card.dataset.invalid = '1';
                card.querySelector('.subject-total').textContent = '--';

                // Do not auto-save while invalid, and don't let it count in the summary
                clearTimeout(card.timeout);
                updateSummary();
                return;
            }

            errorEl.style.display = 'none';
            card.dataset.invalid = '';

            const maxClass = parseFloat(card.dataset.maxClassScore) || 50;
            const maxExam = parseFloat(card.dataset.maxExamScore) || 50;
            const classPercent = parseFloat(card.dataset.classScorePercent) || 50;
            const examPercent = parseFloat(card.dataset.examScorePercent) || 50;

            const classScore = parseFloat(card.querySelector('.class-score').value) || 0;
            const examScore = parseFloat(card.querySelector('.exam-score').value) || 0;

            // Weighted calculation - must mirror save_score.php exactly
            const weightedClass = (classScore / maxClass) * classPercent;
            const weightedExam = (examScore / maxExam) * examPercent;
            const total = weightedClass + weightedExam;

            // Update total display
            const totalElement = card.querySelector('.subject-total');
            totalElement.textContent = total.toFixed(0);
            
            // Calculate grade
            let grade = 'W';
            let gradeClass = 'grade-w';
            if (total >= 90) { grade = 'A'; gradeClass = 'grade-a'; }
            else if (total >= 80) { grade = 'B'; gradeClass = 'grade-b'; }
            else if (total >= 70) { grade = 'C'; gradeClass = 'grade-c'; }
            else if (total >= 60) { grade = 'D'; gradeClass = 'grade-d'; }
            else if (total >= 50) { grade = 'E'; gradeClass = 'grade-e'; }
            
            // Update grade badge
            const gradeElement = card.querySelector('.grade-badge');
            gradeElement.textContent = grade;
            gradeElement.className = 'grade-badge ' + gradeClass;
            
            // Update remark
            const remarkElement = card.querySelector('.subject-remark');
            const remarks = {
                'A': 'Excellent',
                'B': 'Very Good',
                'C': 'Good',
                'D': 'Satisfactory',
                'E': 'Pass',
                'W': 'Weak'
            };
            remarkElement.textContent = remarks[grade];
            
            // Update summary
            updateSummary();
            
            // Auto-save after a short delay
            clearTimeout(card.timeout);
            card.timeout = setTimeout(() => {
                saveSubjectScore(card);
            }, 500);
        }

        // Save individual subject score
        function saveSubjectScore(card) {
            // Never call the server with values already flagged invalid client-side
            if (card.dataset.invalid === '1') {
                return;
            }
            const errorMsg = validateScoreCard(card);
            if (errorMsg) {
                const errorEl = getScoreErrorEl(card);
                errorEl.textContent = errorMsg;
                errorEl.style.display = 'block';
                card.dataset.invalid = '1';
                return;
            }

            const subjectId = card.dataset.subjectId;
            const classScore = card.querySelector('.class-score').value;
            const examScore = card.querySelector('.exam-score').value;

            $.ajax({
                url: 'ajax/save_score.php',
                type: 'POST',
                data: {
                    student_id: currentStudentId,
                    subject_id: subjectId,
                    class_score: classScore || 0,
                    exam_score: examScore || 0,
                    term: currentTerm,
                    academic_year: currentAcademicYear
                },
                success: function(response) {
                    const data = JSON.parse(response);
                    if (data.success) {
                        // Show saved indicator
                        const saveIndicator = card.querySelector('.save-indicator') || document.createElement('small');
                        if (!card.querySelector('.save-indicator')) {
                            saveIndicator.className = 'save-indicator text-success ms-2';
                            saveIndicator.innerHTML = '<i class="fas fa-check"></i> Saved';
                            card.querySelector('.subject-name').appendChild(saveIndicator);
                            
                            setTimeout(() => {
                                saveIndicator.remove();
                            }, 2000);
                        }
                    } else {
                        const errorEl = getScoreErrorEl(card);
                        errorEl.textContent = data.message || 'Error saving score';
                        errorEl.style.display = 'block';
                    }
                },
                error: function() {
                    const errorEl = getScoreErrorEl(card);
                    errorEl.textContent = 'Server error while saving score. Please try again.';
                    errorEl.style.display = 'block';
                }
            });
        }

        // Save all scores
        function saveAllScores() {
            const cards = document.querySelectorAll('.subject-score-card');
            const problems = [];

            // Validate every card BEFORE any network call is made
            cards.forEach(card => {
                const errorMsg = validateScoreCard(card);
                const errorEl = getScoreErrorEl(card);

                if (errorMsg) {
                    card.dataset.invalid = '1';
                    errorEl.textContent = errorMsg;
                    errorEl.style.display = 'block';
                    const subjectName = (card.querySelector('.subject-name')?.textContent || 'Subject').trim();
                    problems.push(`${subjectName}: ${errorMsg}`);
                } else {
                    card.dataset.invalid = '';
                    errorEl.style.display = 'none';
                }
            });

            if (problems.length > 0) {
                alert('Cannot save. Please fix the following before saving:\n\n' + problems.join('\n'));
                return; // stop here - ajax/save_score.php is never called
            }

            let savedCount = 0;
            let hadError = false;

            cards.forEach(card => {
                const subjectId = card.dataset.subjectId;
                const classScore = card.querySelector('.class-score').value;
                const examScore = card.querySelector('.exam-score').value;

                $.ajax({
                    url: 'ajax/save_score.php',
                    type: 'POST',
                    data: {
                        student_id: currentStudentId,
                        subject_id: subjectId,
                        class_score: classScore || 0,
                        exam_score: examScore || 0,
                        term: currentTerm,
                        academic_year: currentAcademicYear
                    },
                    success: function(response) {
                        const data = JSON.parse(response);
                        if (!data.success) {
                            hadError = true;
                            const errorEl = getScoreErrorEl(card);
                            errorEl.textContent = data.message || 'Error saving score';
                            errorEl.style.display = 'block';
                        }
                        savedCount++;
                        if (savedCount === cards.length) {
                            alert(hadError
                                ? 'Some scores could not be saved. Please check the highlighted subjects.'
                                : 'All scores saved successfully!');
                            // Refresh student list to update status
                            loadStudentsForScores();
                        }
                    },
                    error: function() {
                        hadError = true;
                        savedCount++;
                        const errorEl = getScoreErrorEl(card);
                        errorEl.textContent = 'Server error while saving score.';
                        errorEl.style.display = 'block';
                        if (savedCount === cards.length) {
                            alert('Some scores could not be saved. Please check the highlighted subjects.');
                            loadStudentsForScores();
                        }
                    }
                });
            });
        }

        // Update summary statistics (weighted, matches save_score.php)
        function updateSummary() {
            const cards = document.querySelectorAll('.subject-score-card');
            const totalSubjects = cards.length;
            let subjectsEntered = 0;
            let totalMarks = 0;
            
            cards.forEach(card => {
                if (card.dataset.invalid === '1') return; // don't count unresolved invalid entries

                const maxClass = parseFloat(card.dataset.maxClassScore) || 50;
                const maxExam = parseFloat(card.dataset.maxExamScore) || 50;
                const classPercent = parseFloat(card.dataset.classScorePercent) || 50;
                const examPercent = parseFloat(card.dataset.examScorePercent) || 50;

                const classScore = parseFloat(card.querySelector('.class-score').value) || 0;
                const examScore = parseFloat(card.querySelector('.exam-score').value) || 0;

                const weightedClass = (classScore / maxClass) * classPercent;
                const weightedExam = (examScore / maxExam) * examPercent;
                const total = weightedClass + weightedExam;
                
                if (classScore > 0 || examScore > 0) {
                    subjectsEntered++;
                    totalMarks += total;
                }
            });
            
            const average = subjectsEntered > 0 ? (totalMarks / subjectsEntered).toFixed(1) : 0;
            
            document.getElementById('totalSubjects').textContent = totalSubjects;
            document.getElementById('subjectsEntered').textContent = subjectsEntered;
            document.getElementById('totalMarks').textContent = totalMarks.toFixed(0);
            document.getElementById('averageMarks').textContent = average;
        }

        // Load students for report
        function loadStudentsForReport() {
            const classVal = document.getElementById('reportClass').value;
            const studentSelect = document.getElementById('reportStudent');
            
            if (!classVal) {
                studentSelect.innerHTML = '<option value="">Select Student</option>';
                studentSelect.disabled = true;
                return;
            }

            $.ajax({
                url: 'ajax/get_students_for_report.php',
                type: 'POST',
                data: { class: classVal },
                success: function(response) {
                    studentSelect.innerHTML = '<option value="">Select Student</option>' + response;
                    studentSelect.disabled = false;
                }
            });
        }

        // Generate report
        function generateReport() {
            const studentId = document.getElementById('reportStudent').value;
            const term = document.getElementById('reportTerm').value;
            const year = document.getElementById('reportYear').value;

            if (!studentId || !term || !year) {
                alert('Please select all fields');
                return;
            }

            const url = `generate_report.php?student_id=${studentId}&term=${term}&academic_year=${year}`;
            document.getElementById('reportFrame').src = url;
            document.getElementById('reportPreview').style.display = 'block';
        }

        // Print report
        function printReport() {
            const studentId = document.getElementById('reportStudent').value;
            const term = document.getElementById('reportTerm').value;
            const year = document.getElementById('reportYear').value;

            if (!studentId || !term || !year) {
                alert('Please select all fields');
                return;
            }

            window.open(`print_report.php?student_id=${studentId}&term=${term}&academic_year=${year}`, '_blank');
        }

        function viewExamResults() {
            const className = document.getElementById('scoreClass').value;
            const term = document.getElementById('scoreTerm').value;
            const year = document.getElementById('scoreYear').value;

            if (!className || !term) {
                alert('Please select class and term first');
                return;
            }

            window.open(`../../exams_generator/results.php?class_name=${encodeURIComponent(className)}&term=${encodeURIComponent(term)}&academic_year=${encodeURIComponent(year)}`, '_blank');
        }

        // Download PDF
        function downloadPDF() {
            const studentId = document.getElementById('reportStudent').value;
            const term = document.getElementById('reportTerm').value;
            const year = document.getElementById('reportYear').value;

            if (!studentId || !term || !year) {
                alert('Please select all fields');
                return;
            }

            window.open(`report_pdf.php?student_id=${studentId}&term=${term}&academic_year=${year}`, '_blank');
        }

        // Add subject
        $('#addSubjectForm').submit(function(e) {
            e.preventDefault();
            $.ajax({
                url: 'ajax/manage_subjects.php',
                type: 'POST',
                data: $(this).serialize() + '&action=add',
                success: function(response) {
                    location.reload();
                }
            });
        });

        // Edit subject
        function editSubject(id, name, code) {
            const newName = prompt('Subject Name:', name);
            const newCode = prompt('Subject Code:', code);
            if (newName && newCode) {
                $.ajax({
                    url: 'ajax/manage_subjects.php',
                    type: 'POST',
                    data: { id: id, subject_name: newName, subject_code: newCode, action: 'edit' },
                    success: function(response) {
                        location.reload();
                    }
                });
            }
        }

        // Toggle subject
        function toggleSubject(id, currentStatus) {
            const newStatus = currentStatus === 'yes' ? 'no' : 'yes';
            $.ajax({
                url: 'ajax/manage_subjects.php',
                type: 'POST',
                data: { id: id, active: newStatus, action: 'toggle' },
                success: function(response) {
                    location.reload();
                }
            });
        }
    </script>
</body>
</html>