<?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 all classes — primary: Class Management table; fallback: students table

$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'];

    }

}

// Include any student class not yet in Class Management

$result2 = $conn->query("SELECT DISTINCT class FROM students WHERE class IS NOT NULL AND class != '' ORDER BY class");

if ($result2) {

    while ($row = $result2->fetch_assoc()) {

        if (!in_array($row['class'], $classes)) {

            $classes[] = $row['class'];

        }

    }

}

sort($classes);



// Get all subjects from Subject Management table

$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;

    }

}



$conn->close();

?>



<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Subject Configuration - 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>

        .config-card {

            border-radius: 10px;

            box-shadow: 0 2px 10px rgba(0,0,0,0.1);

            margin-bottom: 20px;

        }

        

        .class-tab {

            padding: 12px 24px;

            cursor: pointer;

            border: 1px solid #dee2e6;

            background: #f8f9fa;

            font-weight: 500;

            transition: all 0.2s;

            border-radius: 5px;

            margin-right: 5px;

            margin-bottom: 5px;

        }

        

        .class-tab:hover {

            background: #e9ecef;

            transform: translateY(-2px);

        }

        

        .class-tab.active {

            background: #0d6efd;

            color: white;

            border-color: #0d6efd;

        }

        

        .subject-row {

            transition: background-color 0.2s;

        }

        

        .subject-row:hover {

            background-color: #f8f9fa;

        }

        

        .percentage-input {

            width: 80px;

            display: inline-block;

        }

        

        .grade-badge {

            width: 40px;

            height: 40px;

            border-radius: 50%;

            display: flex;

            align-items: center;

            justify-content: center;

            font-weight: bold;

            margin: 0 auto;

        }

        

        .grade-A { background: #d4edda; color: #155724; }

        .grade-B { background: #cce5ff; color: #004085; }

        .grade-C { background: #fff3cd; color: #856404; }

        .grade-D { background: #ffeeba; color: #856404; }

        .grade-E { background: #f8d7da; color: #721c24; }

        .grade-W { background: #f5c6cb; color: #721c24; }

        

        .info-box {

            background-color: #e7f3ff;

            border-left: 4px solid #0d6efd;

            padding: 15px;

            border-radius: 5px;

            margin-bottom: 20px;

        }

        

        .quick-actions {

            position: sticky;

            top: 20px;

        }

        

        .subject-count-badge {

            font-size: 0.9rem;

            padding: 5px 10px;

        }

    </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 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>



            <main class="content">

                <div class="content-header">

                    <h2><i class="fas fa-cog me-2"></i>Subject Configuration</h2>

                    <p>Configure subjects, scoring percentages, and grade boundaries for each class</p>

                </div>



                <!-- Info Box -->

                <div class="info-box">

                    <i class="fas fa-info-circle me-2"></i>

                    <strong>How it works:</strong> Select a class below to configure its subjects. 

                    You can set different scoring weights, maximum scores, and grade boundaries for each class.

                </div>



                <!-- Class Tabs -->

                <div class="card config-card">

                    <div class="card-header">

                        <h5 class="mb-0"><i class="fas fa-users me-2"></i>Select Class</h5>

                    </div>

                    <div class="card-body">

                        <?php if (empty($classes)): ?>

                            <div class="alert alert-warning">

                                <i class="fas fa-exclamation-triangle me-2"></i>

                                No classes found. Please add students first.

                            </div>

                        <?php else: ?>

                            <div class="d-flex flex-wrap gap-2">

                                <?php foreach ($classes as $index => $class): ?>

                                <button class="class-tab <?php echo $index === 0 ? 'active' : ''; ?>" 

                                        onclick="loadClassSubjects('<?php echo $class; ?>')">

                                    <?php echo $class; ?>

                                    <span class="badge bg-light text-dark ms-2 subject-count" id="count-<?php echo $class; ?>">0</span>

                                </button>

                                <?php endforeach; ?>

                            </div>

                        <?php endif; ?>

                    </div>

                </div>



                <div class="row">

                    <!-- Subject Configuration -->

                    <div class="col-md-7">

                        <div class="card config-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>

                                    Subjects for  <span id="currentClassName"><?php echo $classes[0] ?? ' '; ?></span>

                                </h5>

                                <div>

                                    <button class="btn btn-success btn-sm me-2" onclick="copyFromAnotherClass()">

                                        <i class="fas fa-copy me-2"></i>Copy from Class

                                    </button>

                                    <button class="btn btn-primary btn-sm" onclick="addSubjectToClass()" 

                                            <?php echo empty($classes) ? 'disabled' : ''; ?>>

                                        <i class="fas fa-plus me-2"></i>Add Subject

                                    </button>

                                </div>

                            </div>

                            <div class="card-body">

                                <div class="table-responsive">

                                    <table class="table table-hover">

                                        <thead>

                                            <tr>

                                                <th>Subject</th>

                                                <th>Class Score</th>

                                                <th>Exam Score</th>

                                                <th>Compulsory</th>

                                                <th>Order</th>

                                                <th>Actions</th>

                                            </tr>

                                            <tr class="bg-light">

                                                <th></th>

                                                <th><small>% (Max)</small></th>

                                                <th><small>% (Max)</small></th>

                                                <th></th>

                                                <th></th>

                                                <th></th>

                                            </tr>

                                        </thead>

                                        <tbody id="classSubjectsTable">

                                            <tr>

                                                <td colspan="6" class="text-center py-4">

                                                    <div class="spinner-border text-primary" role="status">

                                                        <span class="visually-hidden">Loading...</span>

                                                    </div>

                                                </td>

                                            </tr>

                                        </tbody>

                                    </table>

                                </div>

                            </div>

                        </div>

                    </div>



                    <!-- Grade Boundaries -->

                    <div class="col-md-5" >

                        <div class="card config-card quick-actions" style=" margin-bottom:20px;">

                            <div class="card-header">

                                <h5 class="mb-0"><i class="fas fa-chart-line me-2"></i>Grade Boundaries</h5>

                            </div>

                            <div class="card-body">

                                <p class="text-muted small">Set the score ranges for each grade</p>

                                <div id="gradeBoundaries">

                                    <!-- Loaded via AJAX -->

                                </div>

                                <button class="btn btn-primary btn-sm w-100 mt-3" onclick="saveGradeBoundaries()">

                                    <i class="fas fa-save me-2"></i>Save Boundaries

                                </button>

                                <button class="btn btn-secondary btn-sm w-100 mt-2" onclick="resetGradeBoundaries()">

                                    <i class="fas fa-undo me-2"></i>Reset to Default

                                </button>

                            </div>

                        </div>



                        <!-- Quick Tips -->

                       

                    </div>



                     <div class="card config-card mt-3 col-md-12" style="background-color: #fff3cd;">

                            <div class="card-header">

                                <h5 class="mb-0"><i class="fas fa-lightbulb me-2"></i>Quick Tips</h5>

                            </div>

                            <div class="card-body">

                                <ul class="small mb-0">

                                    <li class="mb-2">Class Score % + Exam Score % should equal 100%</li>

                                    <li class="mb-2">Maximum scores can be any value (e.g., 50, 60, 100)</li>

                                    <li class="mb-2">Use Display Order to arrange subjects on the report</li>

                                    <li class="mb-2">Compulsory subjects are required for promotion</li>

                                    <li>Grade boundaries can be customized per class</li>

                                </ul>

                            </div>

                        </div>

                </div>

            </main>



            <footer class="footer">

                <p>&copy; 2024 EduTrack PRO. All rights reserved.</p>

            </footer>

        </div>

    </div>



    <!-- Add Subject Modal -->

   <!-- 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 Subject to Class</h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

            </div>

            <div class="modal-body">

                <form id="addSubjectForm">

                    <input type="hidden" name="class_name" id="modalClassName">

                    

                    <!-- Subject Selection -->

                    <div class="mb-3">

                        <label class="form-label">Subject <span class="text-danger">*</span></label>

                        <div class="mb-2">

                            <div class="form-check form-check-inline">

                                <input class="form-check-input" type="radio" name="subject_type" id="subjectTypeExisting" value="existing" checked>

                                <label class="form-check-label" for="subjectTypeExisting">Select Existing</label>

                            </div>

                            <div class="form-check form-check-inline">

                                <input class="form-check-input" type="radio" name="subject_type" id="subjectTypeNew" value="new">

                                <label class="form-check-label" for="subjectTypeNew">Add New Subject</label>

                            </div>

                        </div>

                        

                        <!-- Existing Subject Dropdown -->

                        <div id="existingSubjectDiv">

                            <select class="form-select" name="subject_id" id="subjectSelect">

                                <option value="">Select Subject</option>

                                <?php foreach ($subjects as $subject): ?>

                                <option value="<?php echo $subject['id']; ?>">

                                    <?php echo $subject['subject_name']; ?> (<?php echo $subject['subject_code']; ?>)

                                </option>

                                <?php endforeach; ?>

                            </select>

                        </div>

                        

                        <!-- New Subject Input -->

                        <div id="newSubjectDiv" style="display: none;">

                            <div class="row">

                                <div class="col-md-6">

                                    <input type="text" class="form-control" name="new_subject_name" id="newSubjectName" placeholder="Subject Name (e.g., Physics)">

                                </div>

                                <div class="col-md-6">

                                    <input type="text" class="form-control" name="new_subject_code" id="newSubjectCode" placeholder="Subject Code (e.g., PHY)">

                                </div>

                            </div>

                            <small class="text-muted">This will be added to the subjects list for future use</small>

                        </div>

                    </div>

                    

                    <div class="card bg-light mb-3">

                        <div class="card-body">

                            <h6 class="card-title">Scoring Configuration</h6>

                            <div class="row">

                                <div class="col-md-6">

                                    <div class="mb-3">

                                        <label class="form-label">Class Score %</label>

                                        <input type="number" class="form-control" name="class_score_percent" value="50" min="0" max="100" step="1" required>

                                    </div>

                                </div>

                                <div class="col-md-6">

                                    <div class="mb-3">

                                        <label class="form-label">Exam Score %</label>

                                        <input type="number" class="form-control" name="exam_score_percent" value="50" min="0" max="100" step="1" required>

                                    </div>

                                </div>

                            </div>

                            <div class="row">

                                <div class="col-md-6">

                                    <div class="mb-3">

                                        <label class="form-label">Max Class Score</label>

                                        <input type="number" class="form-control" name="max_class_score" value="50" min="0" step="0.5" required>

                                    </div>

                                </div>

                                <div class="col-md-6">

                                    <div class="mb-3">

                                        <label class="form-label">Max Exam Score</label>

                                        <input type="number" class="form-control" name="max_exam_score" value="50" min="0" step="0.5" required>

                                    </div>

                                </div>

                            </div>

                        </div>

                    </div>

                    

                    <div class="row">

                        <div class="col-md-6">

                            <div class="mb-3">

                                <div class="form-check">

                                    <input class="form-check-input" type="checkbox" name="is_compulsory" id="isCompulsory" checked>

                                    <label class="form-check-label" for="isCompulsory">

                                        Compulsory Subject

                                    </label>

                                </div>

                            </div>

                        </div>

                        <div class="col-md-6">

                            <div class="mb-3">

                                <label class="form-label">Display Order</label>

                                <input type="number" class="form-control" name="display_order" value="0" min="0">

                            </div>

                        </div>

                    </div>

                </form>

            </div>

            <div class="modal-footer">

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                <button type="button" class="btn btn-primary" onclick="saveSubjectToClass()">Add Subject</button>

            </div>

        </div>

    </div>

</div>



    <!-- Copy from Class Modal -->

    <div class="modal fade" id="copyClassModal" tabindex="-1">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <h5 class="modal-title">Copy Subjects from Another Class</h5>

                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

                </div>

                <div class="modal-body">

                    <p>Copy all subject configurations from:</p>

                    <div class="mb-3">

                        <label class="form-label">Source Class</label>

                        <select class="form-select" id="sourceClass">

                            <?php foreach ($classes as $class): ?>

                            <option value="<?php echo $class; ?>"><?php echo $class; ?></option>

                            <?php endforeach; ?>

                        </select>

                    </div>

                    <div class="row">

                        <div class="col-md-6 mb-3">

                            <label class="form-label">Source Term</label>

                            <select class="form-select" id="sourceTerm">

                                <option value="First Term">First Term</option>

                                <option value="Second Term">Second Term</option>

                                <option value="Third Term">Third Term</option>

                            </select>

                        </div>

                        <div class="col-md-6 mb-3">

                            <label class="form-label">Source Academic Year</label>

                            <input type="text" class="form-control" id="sourceYear" value="<?php echo htmlspecialchars(getAcademicYear()); ?>">

                        </div>

                    </div>

                    <hr>

                    <div class="mb-3">

                        <label class="form-label">Destination Class</label>

                        <input type="text" class="form-control" id="targetClass" value="<?php echo htmlspecialchars($classes[0] ?? ''); ?>" readonly>

                    </div>

                    <div class="row">

                        <div class="col-md-6 mb-3">

                            <label class="form-label">Destination Term</label>

                            <select class="form-select" id="targetTerm">

                                <option value="First Term">First Term</option>

                                <option value="Second Term">Second Term</option>

                                <option value="Third Term">Third Term</option>

                            </select>

                        </div>

                        <div class="col-md-6 mb-3">

                            <label class="form-label">Destination Academic Year</label>

                            <input type="text" class="form-control" id="targetYear" value="<?php echo htmlspecialchars(getAcademicYear()); ?>">

                        </div>

                    </div>

                    <p class="text-muted small mt-3">

                        <i class="fas fa-info-circle"></i>

                        This will replace all current subjects for <?php echo $classes[0] ?? ''; ?> with the ones from the selected class.

                    </p>

                </div>

                <div class="modal-footer">

                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                    <button type="button" class="btn btn-primary" onclick="copySubjects()">Copy Subjects</button>

                </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>

        let currentClass = '<?php echo $classes[0] ?? ''; ?>';

        

        $(document).ready(function() {

            if (currentClass) {

                loadClassSubjects(currentClass);

                loadGradeBoundaries(currentClass);

            }

        });



        function loadClassSubjects(className) {

            currentClass = className;

            document.getElementById('currentClassName').textContent = className;

            

            // Update active tab

            document.querySelectorAll('.class-tab').forEach(tab => {

                tab.classList.remove('active');

                if (tab.textContent.trim().startsWith(className)) {

                    tab.classList.add('active');

                }

            });

            

            $.ajax({

                url: 'ajax/get_class_subjects.php',

                type: 'POST',

                data: { class_name: className },

                success: function(response) {

                    document.getElementById('classSubjectsTable').innerHTML = response;

                    updateSubjectCounts();

                }

            });

            

            loadGradeBoundaries(className);

        }



        function loadGradeBoundaries(className) {

            $.ajax({

                url: 'ajax/get_grade_boundaries.php',

                type: 'POST',

                data: { class_name: className },

                success: function(response) {

                    document.getElementById('gradeBoundaries').innerHTML = response;

                }

            });

        }



        // Update subject counts

function updateSubjectCounts() {

    $.ajax({

        url: 'ajax/get_subject_counts.php',

        type: 'GET',

        dataType: 'json',

        success: function(response) {

            console.log('Subject counts:', response);

            

            if (response.success) {

                // Update the badges with subject counts

                const counts = response.counts;

                

                Object.keys(counts).forEach(className => {

                    if (className !== 'total_active') {

                        // Create an ID friendly version of the class name

                        const classId = 'count-' + className.replace(/\s+/g, '').replace(/[^a-zA-Z0-9]/g, '');

                        const badge = document.getElementById(classId);

                        

                        if (badge) {

                            badge.textContent = counts[className];

                            

                            // Optional: Add color coding based on count

                            if (counts[className] === 0) {

                                badge.className = 'badge bg-danger';

                            } else if (counts[className] < 5) {

                                badge.className = 'badge bg-warning text-dark';

                            } else {

                                badge.className = 'badge bg-success';

                            }

                        }

                    }

                });

                

                // You can also display total active subjects somewhere

                if (response.total_active_subjects) {

                    console.log('Total active subjects:', response.total_active_subjects);

                }

            }

        },

        error: function(xhr, status, error) {

            console.error('Error loading subject counts:', error);

        }

    });

}



// For the enhanced version with more details

function loadClassSubjectDetails(className) {

    $.ajax({

        url: 'ajax/get_subject_counts.php',

        type: 'GET',

        dataType: 'json',

        success: function(response) {

            if (response.success && response.data[className]) {

                const classData = response.data[className];

                

                // Update UI with detailed information

                console.log('Class:', className);

                console.log('Total subjects:', classData.total_subjects);

                console.log('Compulsory subjects:', classData.compulsory_count);

                console.log('Subjects list:', classData.subjects);

                

                // You can use this data to display a tooltip or detailed view

                // For example, show subject list on hover

            }

        },

        error: function(xhr, status, error) {

            console.error('Error loading class details:', error);

        }

    });

}



        function addSubjectToClass() {

            document.getElementById('modalClassName').value = currentClass;

            document.getElementById('addSubjectForm').reset();

            document.getElementById('modalClassName').value = currentClass;

            

            // Reset to defaults

            document.querySelector('[name="class_score_percent"]').value = 50;

            document.querySelector('[name="exam_score_percent"]').value = 50;

            document.querySelector('[name="max_class_score"]').value = 50;

            document.querySelector('[name="max_exam_score"]').value = 50;

            

            const modal = new bootstrap.Modal(document.getElementById('addSubjectModal'));

            modal.show();

        }



function saveSubjectToClass() {

    // Get subject type

    const subjectType = document.querySelector('input[name="subject_type"]:checked')?.value;

    

    if (!subjectType) {

        alert('Please select subject type');

        return;

    }

    

    // Validate based on subject type

    if (subjectType === 'existing') {

        const subjectSelect = document.getElementById('subjectSelect');

        if (!subjectSelect.value) {

            alert('Please select a subject');

            return;

        }

    } else {

        const subjectName = document.getElementById('newSubjectName').value.trim();

        const subjectCode = document.getElementById('newSubjectCode').value.trim();

        

        if (!subjectName) {

            alert('Please enter a subject name');

            document.getElementById('newSubjectName').focus();

            return;

        }

        

        if (!subjectCode) {

            alert('Please enter a subject code');

            document.getElementById('newSubjectCode').focus();

            return;

        }

        

        // Validate subject code format (optional)

        if (subjectCode.length < 2 || subjectCode.length > 10) {

            alert('Subject code should be between 2 and 10 characters');

            return;

        }

    }

    

    // Validate percentages sum to 100

    const classPercent = parseInt(document.querySelector('[name="class_score_percent"]').value) || 0;

    const examPercent = parseInt(document.querySelector('[name="exam_score_percent"]').value) || 0;

    

    if (classPercent + examPercent !== 100) {

        alert('Class Score % and Exam Score % must add up to 100%');

        return;

    }

    

    // Validate max scores

    const maxClassScore = parseFloat(document.querySelector('[name="max_class_score"]').value) || 0;

    const maxExamScore = parseFloat(document.querySelector('[name="max_exam_score"]').value) || 0;

    

    if (maxClassScore <= 0) {

        alert('Maximum class score must be greater than 0');

        document.querySelector('[name="max_class_score"]').focus();

        return;

    }

    

    if (maxExamScore <= 0) {

        alert('Maximum exam score must be greater than 0');

        document.querySelector('[name="max_exam_score"]').focus();

        return;

    }

    

    // Show loading state

    const saveBtn = document.querySelector('#addSubjectModal .btn-primary');

    const originalText = saveBtn.innerHTML;

    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';

    saveBtn.disabled = true;

    

    // Get form data

    const formData = new FormData(document.getElementById('addSubjectForm'));

    

    // Add subject type to form data

    formData.append('subject_type', subjectType);

    

    // If it's a new subject, ensure the existing subject_id is not sent

    if (subjectType === 'new') {

        formData.delete('subject_id');

    }

    

    // Log what we're sending (for debugging)

    console.log('Sending data:');

    for (let pair of formData.entries()) {

        console.log(pair[0] + ': ' + pair[1]);

    }

    

    $.ajax({

        url: 'ajax/save_class_subject.php',

        type: 'POST',

        data: formData,

        processData: false,

        contentType: false,

        dataType: 'json',

        timeout: 30000, // 30 second timeout

        success: function(response) {

            console.log('Server response:', response);

            

            if (response.success) {

                // Close modal

                const modal = bootstrap.Modal.getInstance(document.getElementById('addSubjectModal'));

                modal.hide();

                

                // Reload subjects for the current class

                loadClassSubjects(currentClass);

                

                // If a new subject was created, we might want to update the global subjects list

                if (response.is_new) {

                    // Show a more detailed success message

                    alert(`Subject "${response.subject_name}" has been created and added to ${currentClass} successfully!`);

                    

                    // Optionally update the existing subjects dropdown for future use

                    // This would require an AJAX call to refresh the subjects list

                    refreshSubjectsDropdown();

                } else {

                    // Show success message

                    alert(`Subject "${response.subject_name}" added to ${currentClass} successfully!`);

                }

            } else {

                alert('Error: ' + (response.message || 'Unknown error occurred'));

            }

        },

        error: function(xhr, status, error) {

            console.error('AJAX Error:', {

                status: status,

                error: error,

                response: xhr.responseText,

                statusCode: xhr.status

            });

            

            let errorMessage = 'Error saving subject. ';

            

            if (xhr.status === 404) {

                errorMessage += 'The save_class_subject.php file was not found. Please check the file path.';

            } else if (xhr.status === 500) {

                errorMessage += 'Server error. Please check PHP error logs.';

            } else if (status === 'timeout') {

                errorMessage += 'Request timed out. Please try again.';

            } else if (xhr.responseText) {

                // Try to parse error message from response

                try {

                    const errorResponse = JSON.parse(xhr.responseText);

                    errorMessage += errorResponse.message || xhr.responseText;

                } catch {

                    errorMessage += xhr.responseText;

                }

            } else {

                errorMessage += error || 'Unknown error occurred';

            }

            

            alert(errorMessage);

        },

        complete: function() {

            // Restore button state

            saveBtn.innerHTML = originalText;

            saveBtn.disabled = false;

        }

    });

}



// Helper function to refresh the subjects dropdown

function refreshSubjectsDropdown() {

    $.ajax({

        url: 'ajax/get_all_subjects.php',

        type: 'GET',

        dataType: 'json',

        success: function(response) {

            if (response.success) {

                const subjectSelect = document.getElementById('subjectSelect');

                const currentValue = subjectSelect.value;

                

                // Clear existing options except the first one

                subjectSelect.innerHTML = '<option value="">Select Subject</option>';

                

                // Add new options

                response.subjects.forEach(subject => {

                    const option = document.createElement('option');

                    option.value = subject.id;

                    option.textContent = `${subject.subject_name} (${subject.subject_code})`;

                    subjectSelect.appendChild(option);

                });

                

                // Restore previous selection if it still exists

                if (currentValue) {

                    subjectSelect.value = currentValue;

                }

            }

        },

        error: function(xhr, status, error) {

            console.error('Error refreshing subjects:', error);

        }

    });

}

// Add this to your existing JavaScript

document.getElementById('addSubjectModal').addEventListener('show.bs.modal', function() {

    // Reset form

    document.getElementById('addSubjectForm').reset();

    document.getElementById('modalClassName').value = currentClass;

    

    // Reset to existing subject by default

    document.getElementById('subjectTypeExisting').checked = true;

    document.getElementById('existingSubjectDiv').style.display = 'block';

    document.getElementById('newSubjectDiv').style.display = 'none';

    

    // Enable/disable appropriate fields

    document.getElementById('subjectSelect').disabled = false;

    document.getElementById('newSubjectName').disabled = true;

    document.getElementById('newSubjectCode').disabled = true;

    

    // Reset to default values

    document.querySelector('[name="class_score_percent"]').value = 50;

    document.querySelector('[name="exam_score_percent"]').value = 50;

    document.querySelector('[name="max_class_score"]').value = 50;

    document.querySelector('[name="max_exam_score"]').value = 50;

    document.getElementById('isCompulsory').checked = true;

    document.querySelector('[name="display_order"]').value = 0;

});



// Toggle between existing and new subject

document.querySelectorAll('input[name="subject_type"]').forEach(radio => {

    radio.addEventListener('change', function() {

        if (this.value === 'existing') {

            document.getElementById('existingSubjectDiv').style.display = 'block';

            document.getElementById('newSubjectDiv').style.display = 'none';

            // Enable existing subject field

            document.getElementById('subjectSelect').disabled = false;

            // Disable new subject fields

            document.getElementById('newSubjectName').disabled = true;

            document.getElementById('newSubjectCode').disabled = true;

        } else {

            document.getElementById('existingSubjectDiv').style.display = 'none';

            document.getElementById('newSubjectDiv').style.display = 'block';

            // Disable existing subject field

            document.getElementById('subjectSelect').disabled = true;

            // Enable new subject fields

            document.getElementById('newSubjectName').disabled = false;

            document.getElementById('newSubjectCode').disabled = false;

            // Focus on subject name for better UX

            document.getElementById('newSubjectName').focus();

        }

    });

});



        function updateClassSubject(id, field, value) {

            $.ajax({

                url: 'ajax/update_class_subject.php',

                type: 'POST',

                data: {

                    id: id,

                    field: field,

                    value: value

                },

                success: function(response) {

                    const data = JSON.parse(response);

                    if (data.success) {

                        // Show temporary success indicator

                        const input = document.querySelector(`[data-subject-id="${id}"] .${field}`);

                        if (input) {

                            input.style.borderColor = '#28a745';

                            setTimeout(() => {

                                input.style.borderColor = '#ced4da';

                            }, 1000);

                        }

                        

                        // If percentages changed, validate total

                        if (field === 'class_score_percent' || field === 'exam_score_percent') {

                            validatePercentages(id);

                        }

                    }

                }

            });

        }



        function validatePercentages(subjectId) {

            const row = document.querySelector(`[data-subject-id="${subjectId}"]`);

            const classPercent = parseInt(row.querySelector('.class_score_percent').value) || 0;

            const examPercent = parseInt(row.querySelector('.exam_score_percent').value) || 0;

            

            if (classPercent + examPercent !== 100) {

                alert('Warning: Class Score % and Exam Score % should add up to 100%');

            }

        }



        function removeClassSubject(id) {

            if (confirm('Are you sure you want to remove this subject from the class? This will also delete all scores for this subject.')) {

                $.ajax({

                    url: 'ajax/remove_class_subject.php',

                    type: 'POST',

                    data: { id: id },

                    success: function(response) {

                        const data = JSON.parse(response);

                        if (data.success) {

                            loadClassSubjects(currentClass);

                        }

                    }

                });

            }

        }



        function updateGradeBoundary(grade, field, value) {

            $.ajax({

                url: 'ajax/update_grade_boundary.php',

                type: 'POST',

                data: {

                    class_name: currentClass,

                    grade: grade,

                    field: field,

                    value: value

                },

                success: function(response) {

                    const data = JSON.parse(response);

                    if (data.success) {

                        // Show success indicator

                        const input = document.querySelector(`[data-grade="${grade}"] .${field}`);

                        if (input) {

                            input.style.borderColor = '#28a745';

                            setTimeout(() => {

                                input.style.borderColor = '#ced4da';

                            }, 1000);

                        }

                    }

                }

            });

        }



        function saveGradeBoundaries() {

            const boundaries = [];

            document.querySelectorAll('.grade-boundary-row').forEach(row => {

                boundaries.push({

                    grade: row.dataset.grade,

                    min_score: row.querySelector('.min-score').value,

                    max_score: row.querySelector('.max-score').value,

                    remark: row.querySelector('.remark').value

                });

            });

            

            $.ajax({

                url: 'ajax/save_grade_boundaries.php',

                type: 'POST',

                data: {

                    class_name: currentClass,

                    boundaries: JSON.stringify(boundaries)

                },

                success: function(response) {

                    const data = JSON.parse(response);

                    if (data.success) {

                        alert('Grade boundaries saved successfully!');

                    }

                }

            });

        }



        function resetGradeBoundaries() {

            if (confirm('Reset grade boundaries to default values?')) {

                $.ajax({

                    url: 'ajax/reset_grade_boundaries.php',

                    type: 'POST',

                    data: { class_name: currentClass },

                    success: function(response) {

                        const data = JSON.parse(response);

                        if (data.success) {

                            loadGradeBoundaries(currentClass);

                        }

                    }

                });

            }

        }



        function copyFromAnotherClass() {

            document.getElementById('targetClass').value = currentClass;

            const modal = new bootstrap.Modal(document.getElementById('copyClassModal'));

            modal.show();

        }



        function copySubjects() {

            const sourceClass = document.getElementById('sourceClass').value;

            const fromTerm = document.getElementById('sourceTerm').value;

            const toTerm = document.getElementById('targetTerm').value;

            const fromYear = document.getElementById('sourceYear').value.trim();

            const toYear = document.getElementById('targetYear').value.trim();

            

            if (!confirm(`Copy all subjects from ${sourceClass} to ${currentClass}?`)) {

                return;

            }

            

            $.ajax({

                url: 'ajax/copy_class_subjects.php',

                type: 'POST',

                data: {

                    from_class: sourceClass,

                    to_class: currentClass,

                    from_term: fromTerm,

                    to_term: toTerm,

                    from_year: fromYear,

                    to_year: toYear

                },

                success: function(response) {

                    const data = JSON.parse(response);

                    if (data.success) {

                        bootstrap.Modal.getInstance(document.getElementById('copyClassModal')).hide();

                        loadClassSubjects(currentClass);

                        alert(`Subjects copied successfully! ${data.copied} row(s) inserted.`);

                    } else {

                        alert('Error: ' + data.message);

                    }

                }

            });

        }





        // Toggle between existing and new subject

document.querySelectorAll('input[name="subject_type"]').forEach(radio => {

    radio.addEventListener('change', function() {

        if (this.value === 'existing') {

            document.getElementById('existingSubjectDiv').style.display = 'block';

            document.getElementById('newSubjectDiv').style.display = 'none';

            // Disable new subject fields

            document.getElementById('newSubjectName').disabled = true;

            document.getElementById('newSubjectCode').disabled = true;

            // Enable existing subject field

            document.getElementById('subjectSelect').disabled = false;

        } else {

            document.getElementById('existingSubjectDiv').style.display = 'none';

            document.getElementById('newSubjectDiv').style.display = 'block';

            // Enable new subject fields

            document.getElementById('newSubjectName').disabled = false;

            document.getElementById('newSubjectCode').disabled = false;

            // Disable existing subject field

            document.getElementById('subjectSelect').disabled = true;

        }

    });

});



// Initialize on modal show

document.getElementById('addSubjectModal').addEventListener('show.bs.modal', function() {

    // Reset to existing subject by default

    document.getElementById('subjectTypeExisting').checked = true;

    document.getElementById('existingSubjectDiv').style.display = 'block';

    document.getElementById('newSubjectDiv').style.display = 'none';

    document.getElementById('newSubjectName').disabled = true;

    document.getElementById('newSubjectCode').disabled = true;

    document.getElementById('subjectSelect').disabled = false;

    

    // Reset form

    document.getElementById('addSubjectForm').reset();

    document.getElementById('modalClassName').value = currentClass;

});

    </script>

</body>

</html>

