<?php
include('session_validator.php');
include('includes/db.php');

$alert = "";

// Handle subject assignment to students
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['assign_subjects'])) {
    $class_id = (int)$_POST['class_id'];
    $section_id = (int)$_POST['section_id'];
    $academic_year = $conn->real_escape_string($_POST['academic_year']);
    
    if (isset($_POST['subjects']) && is_array($_POST['subjects'])) {
        $success_count = 0;
        $error_count = 0;
        
        foreach ($_POST['subjects'] as $student_id => $subjects) {
            $student_id = (int)$student_id;
            
            // Prepare subject array (max 7 subjects)
            $subject_array = array_fill(0, 7, '');
            $index = 0;
            
            foreach ($subjects as $subject_code => $value) {
                if ($index < 7) {
                    $subject_array[$index] = $conn->real_escape_string($subject_code);
                    $index++;
                }
            }
            
            // Check if record exists for this student, class, section and academic year
            $check_sql = "SELECT * FROM studentsub 
                          WHERE student_id = $student_id 
                          AND class_id = $class_id 
                          AND section_id = $section_id 
                          AND academic_year = '$academic_year'";
            $check_result = $conn->query($check_sql);
            
            if ($check_result->num_rows > 0) {
                // Update existing record
                $update_sql = "UPDATE studentsub SET 
                               sub1 = '{$subject_array[0]}',
                               sub2 = '{$subject_array[1]}',
                               sub3 = '{$subject_array[2]}',
                               sub4 = '{$subject_array[3]}',
                               sub5 = '{$subject_array[4]}',
                               sub6 = '{$subject_array[5]}',
                               sub7 = '{$subject_array[6]}'
                               WHERE student_id = $student_id 
                               AND class_id = $class_id 
                               AND section_id = $section_id 
                               AND academic_year = '$academic_year'";
                
                if ($conn->query($update_sql)) {
                    $success_count++;
                } else {
                    $error_count++;
                }
            } else {
                // Insert new record with section_id
                $insert_sql = "INSERT INTO studentsub 
                               (student_id, class_id, section_id, sub1, sub2, sub3, sub4, sub5, sub6, sub7, academic_year) 
                               VALUES ($student_id, $class_id, $section_id, 
                               '{$subject_array[0]}', '{$subject_array[1]}', '{$subject_array[2]}', 
                               '{$subject_array[3]}', '{$subject_array[4]}', '{$subject_array[5]}', 
                               '{$subject_array[6]}', '$academic_year')";
                
                if ($conn->query($insert_sql)) {
                    $success_count++;
                } else {
                    $error_count++;
                }
            }
        }
        
        // Get class and section names for success message
        $class_name = $conn->query("SELECT class FROM classes WHERE class_id = $class_id")->fetch_assoc()['class'];
        $section_name = $conn->query("SELECT section_name FROM sections WHERE section_id = $section_id")->fetch_assoc()['section_name'];
        
        if ($error_count == 0) {
            $alert = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                        Successfully assigned subjects to $success_count student(s) in $class_name - $section_name for $academic_year!
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                      </div>";
        } else {
            $alert = "<div class='alert alert-warning alert-dismissible fade show' role='alert'>
                        Assigned subjects to $success_count student(s) in $class_name - $section_name, $error_count failed.
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                      </div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SRMS Admin - Assign Subjects to Students</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="js/modernizr/modernizr.min.js"></script>
    <style>
        .subject-badge {
            display: inline-block;
            background: #e9ecef;
            padding: 5px 12px;
            margin: 3px;
            border-radius: 4px;
            font-size: 0.9em;
            color: #495057;
        }
        .table-container {
            max-height: 800px;
            overflow-y: auto;
            margin-top: 10px;
            border: 1px solid #dee2e6;
            border-radius: 4px;
        }
        .table th {
            position: sticky;
            top: 0;
            background-color: #f8f9fa;
            z-index: 100;
        }
        .student-id-col {
            position: sticky;
            left: 0;
            background-color: #f8f9fa;
            z-index: 5;
            min-width: 100px;
        }
        .student-name-col {
            position: sticky;
            left: 100px;
            background-color: #f8f9fa;
            z-index: 5;
            min-width: 200px;
        }
        .student-section-col {
            position: sticky;
            /*left: 300px;*/
            background-color: #f8f9fa;
            z-index: 5;
            min-width: 90px;
        }
        .table td, .table th {
            vertical-align: middle;
            text-align: center;
            min-width: 120px;
        }
        .table td.student-id-col,
        .table td.student-name-col,
        .table td.student-section-col {
            text-align: left;
        }
        .subject-header {
            min-width: 150px;
        }
        .select-all-col {
            background-color: #f8f9fa;
            min-width: 120px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .panel {
            margin-bottom: 20px;
        }
        .year-active {
            background-color: #e8f5e8;
        }
        .checkbox-cell {
            text-align: center;
        }
        .header-checkbox-label {
            font-size: 0.9em;
            display: block;
            margin-bottom: 5px;
        }
        .select-all-label {
            font-weight: bold;
            color: #007bff;
        }
        .section-badge {
            display: inline-block;
            background: #17a2b8;
            color: white;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 0.8em;
        }
        .no-section-badge {
            display: inline-block;
            background: #ffc107;
            color: #212529;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 0.8em;
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
                
                <div class="main-page">
                    <div class="container-fluid">
                        <!-- Page Title -->
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Assign Subjects to Students</h2>
                            </div>
                        </div>
                        
                        <!-- Breadcrumb -->
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li>Subjects</li>
                                    <li class="active">Assign to Students</li>
                                </ul>
                            </div>
                        </div>
                        
                        <!-- Alert Messages -->
                        <?php if($alert): ?>
                            <div class="row">
                                <div class="col-md-12">
                                    <?php echo $alert; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Class and Section Selection Form -->
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5>Select Class, Section and Academic Year</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body">
                                        <form method="post" action="" id="filterForm">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label for="class_id">Select Class *</label>
                                                        <select class="form-control" id="class_id" name="class_id" required onchange="loadSections(this.value)">
                                                            <option value="">-- Select Class --</option>
                                                            <?php
                                                            $classes_query = "SELECT * FROM classes WHERE status = 1 ORDER BY class_numeric";
                                                            $classes_result = $conn->query($classes_query);
                                                            while ($class = $classes_result->fetch_assoc()) {
                                                                echo '<option value="' . $class['class_id'] . '">' . 
                                                                     htmlspecialchars($class['class']) . ' (' . $class['class_numeric'] . ')</option>';
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label for="section_id">Select Section *</label>
                                                        <select class="form-control" id="section_id" name="section_id" required disabled>
                                                            <option value="">-- Select Class First --</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label for="academic_year">Academic Year *</label>
                                                        <select class="form-control" id="academic_year" name="academic_year" required>
                                                            <option value="">-- Select Academic Year --</option>
                                                            <?php
                                                            // Fetch academic years from database
                                                            $academic_years_query = "SELECT * FROM academic_years ORDER BY start_date DESC";
                                                            $academic_years_result = $conn->query($academic_years_query);
                                                            
                                                            if ($academic_years_result->num_rows > 0) {
                                                                while ($year = $academic_years_result->fetch_assoc()) {
                                                                    $active_class = ($year['status'] == 'active') ? 'year-active' : '';
                                                                    $display_text = $year['ay_ad'] . ' (' . $year['ay_bs'] . ')';
                                                                    if ($year['status'] == 'active') {
                                                                        $display_text .= ' [Active]';
                                                                    }
                                                                    echo '<option value="' . $year['ay_ad'] . '" class="' . $active_class . '">' . $display_text . '</option>';
                                                                }
                                                            } else {
                                                                $current_year = date('Y');
                                                                echo '<option value="' . $current_year . '-' . ($current_year + 1) . '">' . $current_year . '-' . ($current_year + 1) . ' [Default]</option>';
                                                            }
                                                            ?>
                                                        </select>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label>&nbsp;</label><br>
                                                        <button type="submit" class="btn btn-primary btn-block">
                                                            <i class="fa fa-search"></i> Load Students & Subjects
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <?php
                        // Display students and subjects if class, section and year are selected
                        if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['class_id']) && isset($_POST['section_id']) && isset($_POST['academic_year'])) {
                            $class_id = (int)$_POST['class_id'];
                            $section_id = (int)$_POST['section_id'];
                            $academic_year = $conn->real_escape_string($_POST['academic_year']);
                            
                            // Get class and section names
                            $class_name = $conn->query("SELECT class FROM classes WHERE class_id = $class_id")->fetch_assoc()['class'];
                            $section_name = $conn->query("SELECT section_name FROM sections WHERE section_id = $section_id")->fetch_assoc()['section_name'];
                            
                            // Get students assigned to this class-section-year combination from student_class_section_data
                            $studentQuery = "SELECT scsd.*, s.student_id, s.regd_id, s.name, s.gender, s.dob, s.phone, s.email, 
                                            s.parent_name, s.parent_phone, s.status as student_status,
                                            sec.section_name
                                            FROM student_class_section_data scsd
                                            JOIN students s ON scsd.student_id = s.student_id
                                            JOIN sections sec ON scsd.section_id = sec.section_id
                                            WHERE scsd.class_id = $class_id 
                                            AND scsd.section_id = $section_id 
                                            AND scsd.academic_year = '$academic_year'
                                            AND scsd.status = 'active'
                                            AND s.status = 'Active'
                                            ORDER BY s.regd_id";
                            
                            $studentResult = $conn->query($studentQuery);
                            
                            if ($studentResult->num_rows > 0) {
                                // Check if class-section mapping exists
                                $class_section_check = $conn->query("SELECT * FROM class_section WHERE class_id = $class_id AND section_id = $section_id AND status = 1");
                                
                                if ($class_section_check->num_rows > 0) {
                                    // Fetch subjects for the selected class-section from class_subject_mapping table
                                    $subjectMappingQuery = "SELECT DISTINCT cs.subject_id, s.subject_code, s.subject_name
                                                            FROM class_subject_mapping cs
                                                            JOIN subjects s ON cs.subject_id = s.id
                                                            WHERE cs.class_id = $class_id 
                                                            AND cs.section_id = $section_id
                                                            ORDER BY s.subject_code ASC";
                                    $subjectMappingResult = $conn->query($subjectMappingQuery);
                                    
                                    if ($subjectMappingResult->num_rows > 0) {
                                        ?>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="panel">
                                                    <div class="panel-heading">
                                                        <div class="panel-title">
                                                            <h5>Assign Subjects to Students - <?php echo htmlspecialchars($class_name); ?> - <?php echo htmlspecialchars($section_name); ?> (<?php echo htmlspecialchars($academic_year); ?>)</h5>
                                                            <p class="text-muted">
                                                                Section: <span class="section-badge"><?php echo htmlspecialchars($section_name); ?></span> | 
                                                                Students in this section: <?php echo $studentResult->num_rows; ?>
                                                            </p>
                                                        </div>
                                                    </div>
                                                    <div class="panel-body">
                                                        <form method="post" action="" id="assignForm">
                                                            <input type="hidden" name="class_id" value="<?php echo $class_id; ?>">
                                                            <input type="hidden" name="section_id" value="<?php echo $section_id; ?>">
                                                            <input type="hidden" name="academic_year" value="<?php echo htmlspecialchars($academic_year); ?>">
                                                            
                                                            <div class="table-responsive table-container">
                                                                <table class="table table-bordered table-striped" id="assignTable">
                                                                    <thead>
                                                                        <tr>
                                                                            <th class="student-id-col">Student ID</th>
                                                                            <th class="student-name-col">Student Name</th>
                                                                            <th class="student-section-col">Section Status</th>
                                                                            <?php
                                                                            $subjectMappingResult->data_seek(0);
                                                                            $subject_counter = 1;
                                                                            while ($subject = $subjectMappingResult->fetch_assoc()) {
                                                                                $subject_code = $subject['subject_code'];
                                                                                $subject_name = $subject['subject_name'];
                                                                                echo '<th class="subject-header">';
                                                                                echo '<div class="header-checkbox-label">' . htmlspecialchars($subject_name) . '</div>';
                                                                                echo '<small>(' . htmlspecialchars($subject_code) . ')</small>';
                                                                                echo '<br>';
                                                                                echo '<input type="checkbox" class="headerCheckbox" data-subject-code="' . $subject_code . '" 
                                                                                       title="Select all for ' . $subject_name . '">';
                                                                                echo '</th>';
                                                                                $subject_counter++;
                                                                            }
                                                                            ?>
                                                                            <th class="select-all-col">
                                                                                <div class="select-all-label">Select All</div>
                                                                                <input type="checkbox" id="selectAllStudents" title="Select all students for all subjects">
                                                                            </th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody>
                                                                        <?php
                                                                        $studentResult->data_seek(0);
                                                                        $student_counter = 1;
                                                                        while ($student = $studentResult->fetch_assoc()) {
                                                                            $student_id = $student['student_id'];
                                                                            $student_name = $student['name'];
                                                                            $regd_id = $student['regd_id'];
                                                                            $current_section = $student['section_name'];
                                                                            $section_status = $student['status'];
                                                                            $section_remarks = $student['remarks'];
                                                                            
                                                                            // Get already assigned subjects for this student in this class-section and academic year
                                                                            $assigned_subjects = [];
                                                                            $assigned_query = $conn->query("SELECT sub1, sub2, sub3, sub4, sub5, sub6, sub7 
                                                                                                            FROM studentsub 
                                                                                                            WHERE student_id = $student_id 
                                                                                                            AND class_id = $class_id 
                                                                                                            AND section_id = $section_id 
                                                                                                            AND academic_year = '$academic_year'");
                                                                            if ($assigned_query->num_rows > 0) {
                                                                                $assigned_row = $assigned_query->fetch_assoc();
                                                                                $assigned_subjects = array_filter([
                                                                                    $assigned_row['sub1'], $assigned_row['sub2'], $assigned_row['sub3'],
                                                                                    $assigned_row['sub4'], $assigned_row['sub5'], $assigned_row['sub6'],
                                                                                    $assigned_row['sub7']
                                                                                ]);
                                                                            }
                                                                            
                                                                            echo '<tr>';
                                                                            echo '<td class="student-id-col">' . $regd_id . '</td>';
                                                                            echo '<td class="student-name-col">' . htmlspecialchars($student_name) . '</td>';
                                                                            echo '<td class="student-section-col">';
                                                                            echo '<span class="section-badge">' . htmlspecialchars($current_section) . '</span><br>';
                                                                            echo '<small class="text-muted">Status: ' . htmlspecialchars($section_status) . '</small>';
                                                                            if (!empty($section_remarks)) {
                                                                                echo '<br><small class="text-muted">' . htmlspecialchars($section_remarks) . '</small>';
                                                                            }
                                                                            echo '</td>';
                                                                            
                                                                            // Display checkboxes for each subject
                                                                            $subjectMappingResult->data_seek(0);
                                                                            while ($subject = $subjectMappingResult->fetch_assoc()) {
                                                                                $subject_code = $subject['subject_code'];
                                                                                $checked = in_array($subject_code, $assigned_subjects) ? 'checked' : '';
                                                                                echo '<td class="checkbox-cell">';
                                                                                echo '<input type="checkbox" name="subjects[' . $student_id . '][' . $subject_code . ']" 
                                                                                       value="1" ' . $checked . ' class="subject-checkbox" 
                                                                                       data-student-id="' . $student_id . '" 
                                                                                       data-subject-code="' . $subject_code . '">';
                                                                                echo '</td>';
                                                                            }
                                                                            
                                                                            // Select all checkbox for this student
                                                                            echo '<td class="select-all-col checkbox-cell">';
                                                                            echo '<input type="checkbox" class="selectRowCheckbox" data-student-id="' . $student_id . '" 
                                                                                   title="Select all subjects for ' . htmlspecialchars($student_name) . '">';
                                                                            echo '</td>';
                                                                            echo '</tr>';
                                                                            
                                                                            $student_counter++;
                                                                        }
                                                                        ?>
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                            
                                                            <div class="text-center mt-3">
                                                                <button type="submit" name="assign_subjects" class="btn btn-success btn-lg">
                                                                    <i class="fa fa-save"></i> Save Subject Assignments
                                                                </button>
                                                                <button type="button" id="clearSelection" class="btn btn-secondary btn-lg ml-2">
                                                                    <i class="fa fa-times"></i> Clear All Selection
                                                                </button>
                                                                <button type="button" id="selectAllForSection" class="btn btn-info btn-lg ml-2">
                                                                    <i class="fa fa-check-square"></i> Select All for Section
                                                                </button>
                                                            </div>
                                                            
                                                            <div class="mt-3">
                                                                <p class="text-muted">
                                                                    <strong>Note:</strong> 
                                                                    <ul>
                                                                        <li>Subjects shown are those assigned to this class-section in the "Manage Subjects" section</li>
                                                                        <li>Checkboxes show previously assigned subjects for the selected class-section and academic year</li>
                                                                        <li>Each student can have up to 7 subjects assigned per section</li>
                                                                        <li>Section information is stored with each subject assignment</li>
                                                                        <li>Only students assigned to this section for the selected academic year are shown</li>
                                                                    </ul>
                                                                </p>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php
                                    } else {
                                        echo '<div class="alert alert-warning">No subjects have been assigned to this class-section. Please assign subjects first in the Manage Subjects section.</div>';
                                    }
                                } else {
                                    echo '<div class="alert alert-danger">This class-section combination does not exist or is inactive. Please check the Class-Section mapping.</div>';
                                }
                            } else {
                                // Show students in the class but not assigned to this section
                                echo '<div class="alert alert-warning">';
                                echo 'No students found in ' . htmlspecialchars($class_name) . ' - ' . htmlspecialchars($section_name) . ' for academic year ' . htmlspecialchars($academic_year) . '.';
                                
                                // Show students in the class but not assigned to any section
                                $class_students_query = "SELECT s.* FROM students s 
                                                         WHERE s.Class_id = $class_id 
                                                         AND s.status = 'Active'
                                                         AND s.student_id NOT IN (
                                                             SELECT student_id FROM student_class_section_data 
                                                             WHERE class_id = $class_id 
                                                             AND academic_year = '$academic_year'
                                                             AND status = 'active'
                                                         )
                                                         ORDER BY s.regd_id";
                                $class_students_result = $conn->query($class_students_query);
                                
                                if ($class_students_result->num_rows > 0) {
                                    echo '<br><strong>Students in ' . htmlspecialchars($class_name) . ' but not assigned to any section for ' . htmlspecialchars($academic_year) . ':</strong>';
                                    echo '<ul>';
                                    while ($student = $class_students_result->fetch_assoc()) {
                                        echo '<li>' . htmlspecialchars($student['regd_id']) . ' - ' . htmlspecialchars($student['name']) . '</li>';
                                    }
                                    echo '</ul>';
                                    echo '<p>Please assign these students to sections first using the "Assign Sections" page.</p>';
                                }
                                
                                echo '</div>';
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/iscroll/iscroll.js"></script>
    <script src="js/prism/prism.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="js/main.js"></script>

    <script>
    $(document).ready(function() {
        // Initialize select2 if available
        if ($.fn.select2) {
            $('select').select2();
        }
        
        // Load sections based on selected class
        $('#class_id').change(function() {
            var classId = $(this).val();
            loadSections(classId);
        });
        
        // Header checkbox - select all for a specific subject
        $(document).on('click', '.headerCheckbox', function() {
            var subjectCode = $(this).data('subject-code');
            var isChecked = $(this).prop('checked');
            
            $('.subject-checkbox[data-subject-code="' + subjectCode + '"]').prop('checked', isChecked);
            updateRowCheckboxes();
            updateSelectAllCheckbox();
        });
        
        // Select all students for all subjects
        $('#selectAllStudents').click(function() {
            var isChecked = $(this).prop('checked');
            $('.subject-checkbox').prop('checked', isChecked);
            $('.selectRowCheckbox').prop('checked', isChecked);
            $('.headerCheckbox').prop('checked', isChecked);
        });
        
        // Select all for section button
        $('#selectAllForSection').click(function() {
            $('.subject-checkbox').prop('checked', true);
            $('.selectRowCheckbox').prop('checked', true);
            $('.headerCheckbox').prop('checked', true);
            $('#selectAllStudents').prop('checked', true);
        });
        
        // Select all subjects for a specific student (row checkbox)
        $(document).on('click', '.selectRowCheckbox', function() {
            var studentId = $(this).data('student-id');
            var isChecked = $(this).prop('checked');
            
            $('.subject-checkbox[data-student-id="' + studentId + '"]').prop('checked', isChecked);
            updateHeaderCheckboxes();
            updateSelectAllCheckbox();
        });
        
        // Individual subject checkbox click
        $(document).on('click', '.subject-checkbox', function() {
            updateRowCheckboxes();
            updateHeaderCheckboxes();
            updateSelectAllCheckbox();
        });
        
        // Clear all selection
        $('#clearSelection').click(function() {
            $('.subject-checkbox').prop('checked', false);
            $('.selectRowCheckbox').prop('checked', false);
            $('.headerCheckbox').prop('checked', false);
            $('#selectAllStudents').prop('checked', false);
        });
        
        // Form validation
        $('#assignForm').submit(function() {
            var checkedCount = $('.subject-checkbox:checked').length;
            if (checkedCount === 0) {
                alert('Please select at least one subject for at least one student!');
                return false;
            }
            
            var studentCount = $('.subject-checkbox[data-student-id]').length / $('.headerCheckbox').length;
            var totalPossible = studentCount * $('.headerCheckbox').length;
            var percentage = Math.round((checkedCount / totalPossible) * 100);
            
            return confirm('Save subject assignments for ' + checkedCount + ' subject selections (' + percentage + '% of total possible)?\n\nSection: <?php echo isset($section_name) ? htmlspecialchars($section_name) : ""; ?>\nAcademic Year: <?php echo isset($academic_year) ? htmlspecialchars($academic_year) : ""; ?>');
        });
        
        // Function to update row checkboxes based on subject selections
        function updateRowCheckboxes() {
            $('.selectRowCheckbox').each(function() {
                var studentId = $(this).data('student-id');
                var studentCheckboxes = $('.subject-checkbox[data-student-id="' + studentId + '"]');
                var checkedCount = studentCheckboxes.filter(':checked').length;
                var totalCount = studentCheckboxes.length;
                
                if (checkedCount === 0) {
                    $(this).prop('checked', false);
                    $(this).prop('indeterminate', false);
                } else if (checkedCount === totalCount) {
                    $(this).prop('checked', true);
                    $(this).prop('indeterminate', false);
                } else {
                    $(this).prop('checked', false);
                    $(this).prop('indeterminate', true);
                }
            });
        }
        
        // Function to update header checkboxes based on subject selections
        function updateHeaderCheckboxes() {
            $('.headerCheckbox').each(function() {
                var subjectCode = $(this).data('subject-code');
                var subjectCheckboxes = $('.subject-checkbox[data-subject-code="' + subjectCode + '"]');
                var checkedCount = subjectCheckboxes.filter(':checked').length;
                var totalCount = subjectCheckboxes.length;
                
                if (checkedCount === 0) {
                    $(this).prop('checked', false);
                    $(this).prop('indeterminate', false);
                } else if (checkedCount === totalCount) {
                    $(this).prop('checked', true);
                    $(this).prop('indeterminate', false);
                } else {
                    $(this).prop('checked', false);
                    $(this).prop('indeterminate', true);
                }
            });
        }
        
        // Function to update select all checkbox
        function updateSelectAllCheckbox() {
            var allCheckboxes = $('.subject-checkbox');
            var allCheckedCount = allCheckboxes.filter(':checked').length;
            var allTotalCount = allCheckboxes.length;
            
            if (allCheckedCount === 0) {
                $('#selectAllStudents').prop('checked', false);
                $('#selectAllStudents').prop('indeterminate', false);
            } else if (allCheckedCount === allTotalCount) {
                $('#selectAllStudents').prop('checked', true);
                $('#selectAllStudents').prop('indeterminate', false);
            } else {
                $('#selectAllStudents').prop('checked', false);
                $('#selectAllStudents').prop('indeterminate', true);
            }
        }
        
        // Initialize checkbox states
        updateRowCheckboxes();
        updateHeaderCheckboxes();
        updateSelectAllCheckbox();
        
        // Auto-dismiss alerts
        setTimeout(function() {
            $('.alert').alert('close');
        }, 5000);
    });
    
    // Function to load sections based on selected class
    function loadSections(classId) {
        if (!classId) {
            $('#section_id').html('<option value="">-- Select Class First --</option>').prop('disabled', true);
            return;
        }
        
        $.ajax({
            url: 'ajax/get_sections.php',
            type: 'GET',
            data: { class_id: classId },
            success: function(response) {
                try {
                    const sections = JSON.parse(response);
                    let options = '<option value="">-- Select Section --</option>';
                    
                    if (sections.length > 0) {
                        sections.forEach(function(section) {
                            options += '<option value="' + section.section_id + '">' + section.section_name + '</option>';
                        });
                        $('#section_id').html(options).prop('disabled', false);
                    } else {
                        $('#section_id').html('<option value="">No sections available for this class</option>').prop('disabled', true);
                    }
                } catch(e) {
                    console.error('Error parsing sections:', e);
                    $('#section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
                }
            },
            error: function() {
                $('#section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
            }
        });
    }
    </script>
</body>
</html>