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

$alert = ''; // Initialize alert variable

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['assign_section'])) {
        $class_id = $_POST['class_id'];
        $section_id = $_POST['section_id'];
        $academic_year = $_POST['academic_year'];
        $student_ids = $_POST['student_ids'] ?? [];
        
        if (empty($student_ids)) {
            $_SESSION['error'] = "Please select at least one student.";
            header("Location: assign_sections.php");
            exit();
        }
        
        $success_count = 0;
        $error_count = 0;
        $error_details = [];
        
        foreach ($student_ids as $student_id) {
            // Check if student already has section assignment for this academic year
            $check_sql = "SELECT id FROM student_class_section_data 
                          WHERE student_id = ? AND academic_year = ?";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("is", $student_id, $academic_year);
            $check_stmt->execute();
            $check_result = $check_stmt->get_result();
            
            if ($check_result->num_rows > 0) {
                // Update existing record
                $sql = "UPDATE student_class_section_data 
                        SET class_id = ?, section_id = ?, status = 'active', 
                            remarks = 'Section assigned/updated', updated_at = NOW()
                        WHERE student_id = ? AND academic_year = ?";
            } else {
                // Insert new record
                $sql = "INSERT INTO student_class_section_data 
                        (student_id, class_id, section_id, academic_year, status, remarks, created_at, updated_at) 
                        VALUES (?, ?, ?, ?, 'active', 'Section assigned', NOW(), NOW())";
            }
            
            $stmt = $conn->prepare($sql);
            
            if ($check_result->num_rows > 0) {
                $stmt->bind_param("iiis", $class_id, $section_id, $student_id, $academic_year);
            } else {
                $stmt->bind_param("iiis", $student_id, $class_id, $section_id, $academic_year);
            }
            
            if ($stmt->execute()) {
                $success_count++;
            } else {
                $error_count++;
                $error_details[] = "Student ID $student_id: " . $conn->error;
            }
            
            $stmt->close();
            $check_stmt->close();
        }
        
        if ($success_count > 0) {
            $message = "Successfully assigned section to $success_count student(s).";
            if ($error_count > 0) {
                $message .= " Failed for $error_count student(s).";
            }
            $_SESSION['success'] = $message;
        } else {
            $_SESSION['error'] = "Failed to assign section to any student. " . implode(", ", $error_details);
        }
        
        header("Location: assign_sections.php");
        exit();
    }
}

// Display success/error messages from session
if (isset($_SESSION['success'])) {
    $alert = '<div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fa fa-check-circle"></i> ' . $_SESSION['success'] . '
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>';
    unset($_SESSION['success']);
}

if (isset($_SESSION['error'])) {
    $alert = '<div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fa fa-exclamation-circle"></i> ' . $_SESSION['error'] . '
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>';
    unset($_SESSION['error']);
}

// Get all classes from classes table
$classes_sql = "SELECT class_id, class, class_numeric, status FROM classes WHERE status = 1 ORDER BY class_numeric";
$classes_result = $conn->query($classes_sql);

// Get all sections from sections table
$sections_sql = "SELECT section_id, section_name FROM sections ORDER BY section_name";
$sections_result = $conn->query($sections_sql);

// Get academic years for dropdown
$academic_years_query = "SELECT * FROM academic_years ORDER BY start_date DESC";
$academic_years_result = $conn->query($academic_years_query);

// Get students based on selected class
$students = [];
$class_name = '';
if (isset($_GET['class_id']) && !empty($_GET['class_id'])) {
    $selected_class_id = $_GET['class_id'];
    
    // First get class name for display
    $class_info_sql = "SELECT class FROM classes WHERE class_id = ?";
    $class_stmt = $conn->prepare($class_info_sql);
    $class_stmt->bind_param("i", $selected_class_id);
    $class_stmt->execute();
    $class_result = $class_stmt->get_result();
    if ($class_result->num_rows > 0) {
        $class_info = $class_result->fetch_assoc();
        $class_name = $class_info['class'];
    }
    $class_stmt->close();
    
    if (!empty($class_name)) {
        // Get students for this class using class_id
        $students_sql = "SELECT student_id, regd_id, name, gender, dob, address, phone, email, 
                         parent_name, parent_phone 
                         FROM students 
                         WHERE class_id = ? 
                         AND status = 'active' 
                         ORDER BY name";
        
        $stmt = $conn->prepare($students_sql);
        $stmt->bind_param("i", $selected_class_id);
        $stmt->execute();
        $students_result = $stmt->get_result();
        $students = $students_result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
}
?>
<!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>Assign Sections - School Management System</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">
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css"/>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.7.1/css/buttons.bootstrap4.min.css"/>
    <style>
        .select-all-container {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #dee2e6;
        }
        .selected-count {
            background-color: #007bff;
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: 500;
        }
        .highlight-row {
            background-color: #e3f2fd !important;
        }
        .class-badge {
            font-size: 0.75em;
            margin-left: 5px;
        }
        .student-table-container {
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .section-assign-form {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }
        .table th {
            background-color: #f8f9fa;
            border-top: none;
            font-weight: 600;
            white-space: nowrap;
        }
        .table td {
            vertical-align: middle;
        }
        .btn-group-sm > .btn, .btn-sm {
            padding: .25rem .5rem;
            font-size: .875rem;
            line-height: 1.5;
            border-radius: .2rem;
        }
        .custom-checkbox {
            padding-left: 0;
        }
        .custom-checkbox .custom-control-input:checked ~ .custom-control-label::before {
            background-color: #007bff;
            border-color: #007bff;
        }
        .card-header {
            background-color: #007bff;
            color: white;
            font-weight: 600;
        }
        .badge-info {
            background-color: #17a2b8;
        }
        .badge-warning {
            background-color: #ffc107;
            color: #212529;
        }
        .form-control:focus {
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        .select2-container--default .select2-selection--single {
            border: 1px solid #ced4da;
            border-radius: .25rem;
            height: calc(2.25rem + 2px);
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 2.25rem;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 2.25rem;
        }
        .dataTables_wrapper {
            padding: 0 !important;
        }
        .dataTables_filter {
            margin-bottom: 10px;
        }
        .dataTables_length {
            margin-bottom: 10px;
        }
        .dataTables_info {
            padding-top: 10px !important;
        }
        .dataTables_paginate {
            padding-top: 10px !important;
        }
        /* Fix for DataTables sorting icons */
        table.dataTable thead .sorting,
        table.dataTable thead .sorting_asc,
        table.dataTable thead .sorting_desc {
            background-position: center right 10px;
        }
        /* Fix for checkbox column width */
        .dt-checkboxes-select-all {
            text-align: center !important;
        }
        .dt-checkboxes-cell {
            text-align: center !important;
        }
    </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">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Assign Sections to Students</h2>
                            </div>
                        </div>
                        <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> Students </li>
                                    <li class="">Assign Sections</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <?= $alert; ?>

                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5><i class="fa fa-users"></i> Assign Sections</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body p-20">
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <form method="GET" action="" id="classFilterForm">
                                                    <div class="form-row">
                                                        <!-- Class Selection -->
                                                        <div class="col-md-8">
                                                            <div class="form-group mb-0">
                                                                <label for="class_id" class="control-label">Select Class *</label>
                                                                <select class="form-control select2" id="class_id" name="class_id" required>
                                                                    <option value="">-- Select Class --</option>
                                                                    <?php 
                                                                    if ($classes_result->num_rows > 0) {
                                                                        $classes_result->data_seek(0);
                                                                        while ($class = $classes_result->fetch_assoc()): ?>
                                                                            <option value="<?= $class['class_id'] ?>" 
                                                                                <?= isset($_GET['class_id']) && $_GET['class_id'] == $class['class_id'] ? 'selected' : '' ?>>
                                                                                Class <?= htmlspecialchars($class['class']) ?>
                                                                                <?php if ($class['class_numeric']): ?>
                                                                                    (Grade <?= htmlspecialchars($class['class_numeric']) ?>)
                                                                                <?php endif; ?>
                                                                            </option>
                                                                        <?php endwhile;
                                                                    } ?>
                                                                </select>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Action Buttons -->
                                                        <div class="col-md-4">
                                                            <div class="form-group mb-0">
                                                                <label class="control-label d-block">&nbsp;</label>
                                                                <div class="d-flex">
                                                                    <button type="submit" class="btn btn-primary mr-2">
                                                                        <i class="fa fa-search mr-1"></i> Load Students
                                                                    </button>
                                                                    <a href="assign_sections.php" class="btn btn-secondary">
                                                                        <i class="fa fa-refresh"></i> Reset
                                                                    </a>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                        
                                        <?php if (isset($_GET['class_id']) && !empty($_GET['class_id']) && !empty($class_name)): ?>
                                        <!-- Class Info -->
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <div class="alert alert-info">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <div>
                                                            <i class="fa fa-chalkboard-teacher fa-lg mr-2"></i>
                                                            <strong>Selected Class:</strong> Class <?= htmlspecialchars($class_name) ?>
                                                        </div>
                                                        <div>
                                                            <span class="badge badge-pill badge-light">
                                                                <i class="fa fa-users mr-1"></i>
                                                                <?= count($students) ?> Student(s) Found
                                                            </span>
                                                            <span id="selectedCount" class="badge badge-pill badge-primary ml-2">0 selected</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Assignment Form -->
                                        <form method="POST" action="" id="assignForm">
                                            <input type="hidden" name="class_id" value="<?= $_GET['class_id'] ?>">
                                            
                                            <div class="section-assign-form">
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <div class="form-group">
                                                            <label for="section_id" class="control-label">Select Section *</label>
                                                            <select class="form-control select2" id="section_id" name="section_id" required>
                                                                <option value="">-- Select Section --</option>
                                                                <?php 
                                                                if ($sections_result->num_rows > 0) {
                                                                    $sections_result->data_seek(0);
                                                                    while ($section = $sections_result->fetch_assoc()): ?>
                                                                        <option value="<?= $section['section_id'] ?>">
                                                                            <?= htmlspecialchars($section['section_name']) ?>
                                                                        </option>
                                                                    <?php endwhile;
                                                                } ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <div class="form-group">
                                                            <label for="academic_year" class="control-label">Academic Year *</label>
                                                            <select class="form-control select2" id="academic_year" name="academic_year" required>
                                                                <option value="">-- Select Academic Year --</option>
                                                                <?php
                                                                if ($academic_years_result->num_rows > 0) {
                                                                    $academic_years_result->data_seek(0);
                                                                    while ($year = $academic_years_result->fetch_assoc()) {
                                                                        $display_text = $year['ay_ad'] . ' (' . $year['ay_bs'] . ')';
                                                                        if ($year['status'] == 'active') {
                                                                            $display_text .= ' (Active)';
                                                                        }
                                                                        echo '<option value="' . $year['ay_ad'] . '">' . $display_text . '</option>';
                                                                    }
                                                                } else {
                                                                    $current_year = date('Y');
                                                                    $next_year = $current_year + 1;
                                                                    $current_academic_year = "$current_year-$next_year";
                                                                    echo '<option value="' . $current_academic_year . '">' . $current_academic_year . '</option>';
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <div class="form-group">
                                                            <label class="control-label">&nbsp;</label>
                                                            <div>
                                                                <button type="submit" name="assign_section" class="btn btn-success btn-block">
                                                                    <i class="fa fa-save mr-1"></i> 
                                                                    <span id="assignButtonText">Assign Section</span>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Students Table -->
                                            <?php if (!empty($students)): ?>
                                            <div class="row mb-3">
                                                <div class="col-md-12">
                                                    <div class="select-all-container">
                                                        <div class="custom-control custom-checkbox">
                                                            <input type="checkbox" class="custom-control-input" id="selectAll">
                                                            <label class="custom-control-label" for="selectAll">
                                                                <strong>Select/Deselect All Students</strong>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="student-table-container">
                                                <table class="table table-hover table-bordered display" id="studentsTable" style="width:100%">
                                                    <thead>
                                                        <tr>
                                                            <th width="50px" class="text-center dt-checkboxes-select-all">
                                                                <div class="custom-control custom-checkbox">
                                                                    <input type="checkbox" class="custom-control-input" id="dataTableSelectAll">
                                                                    <label class="custom-control-label" for="dataTableSelectAll"></label>
                                                                </div>
                                                            </th>
                                                            <th>Registration ID</th>
                                                            <th>Student Name</th>
                                                            <th>Gender</th>
                                                            <th>Date of Birth</th>
                                                            <th>Parent Name</th>
                                                            <th>Contact</th>
                                                            <th>Current Section</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($students as $student): 
                                                            // Get current section if assigned for current academic year
                                                            $current_section = null;
                                                            if (!empty($student['student_id'])) {
                                                                // Get current academic year
                                                                $current_year_sql = "SELECT ay_ad FROM academic_years WHERE status = 'active' LIMIT 1";
                                                                $current_year_result = $conn->query($current_year_sql);
                                                                $current_academic_year = '';
                                                                if ($current_year_result->num_rows > 0) {
                                                                    $current_year = $current_year_result->fetch_assoc();
                                                                    $current_academic_year = $current_year['ay_ad'];
                                                                }
                                                                
                                                                if ($current_academic_year) {
                                                                    $check_sql = "SELECT s.section_name 
                                                                                 FROM student_class_section_data scsd
                                                                                 JOIN sections s ON scsd.section_id = s.section_id
                                                                                 WHERE scsd.student_id = ? 
                                                                                 AND scsd.academic_year = ?
                                                                                 ORDER BY scsd.created_at DESC LIMIT 1";
                                                                    $stmt = $conn->prepare($check_sql);
                                                                    $stmt->bind_param("is", $student['student_id'], $current_academic_year);
                                                                    $stmt->execute();
                                                                    $section_result = $stmt->get_result();
                                                                    $current_section = $section_result->fetch_assoc();
                                                                    $stmt->close();
                                                                }
                                                            }
                                                        ?>
                                                        <tr>
                                                            <td class="text-center dt-checkboxes-cell">
                                                                <div class="custom-control custom-checkbox">
                                                                    <input type="checkbox" class="custom-control-input student-checkbox dt-checkboxes" 
                                                                           name="student_ids[]" value="<?= $student['student_id'] ?? '' ?>"
                                                                           id="student_<?= $student['student_id'] ?? '' ?>"
                                                                           data-student-name="<?= htmlspecialchars($student['name'] ?? '') ?>">
                                                                    <label class="custom-control-label" for="student_<?= $student['student_id'] ?? '' ?>"></label>
                                                                </div>
                                                            </td>
                                                            <td><?= htmlspecialchars($student['regd_id'] ?? 'N/A') ?></td>
                                                            <td>
                                                                <strong><?= htmlspecialchars($student['name'] ?? '') ?></strong>
                                                                <?php if (!empty($student['email'])): ?>
                                                                    <br><small class="text-muted"><?= htmlspecialchars($student['email']) ?></small>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                $gender = $student['gender'] ?? '';
                                                                $gender_icon = ($gender == 'Male') ? 'mars' : 
                                                                              (($gender == 'Female') ? 'venus' : 'genderless');
                                                                $gender_color = ($gender == 'Male') ? 'primary' : 
                                                                               (($gender == 'Female') ? 'danger' : 'secondary');
                                                                ?>
                                                                <span class="badge badge-<?= $gender_color ?>">
                                                                    <i class="fa fa-<?= $gender_icon ?> mr-1"></i>
                                                                    <?= htmlspecialchars($gender) ?>
                                                                </span>
                                                            </td>
                                                            <td data-order="<?= !empty($student['dob']) ? date('Y-m-d', strtotime($student['dob'])) : '' ?>">
                                                                <?= !empty($student['dob']) ? date('Y-m-d', strtotime($student['dob'])) : 'N/A' ?>
                                                            </td>
                                                            <td><?= htmlspecialchars($student['parent_name'] ?? 'N/A') ?></td>
                                                            <td>
                                                                <?php if (!empty($student['phone'])): ?>
                                                                    <i class="fa fa-phone mr-1"></i><?= htmlspecialchars($student['phone']) ?>
                                                                <?php endif; ?>
                                                                <?php if (!empty($student['parent_phone'])): ?>
                                                                    <br><small><i class="fa fa-mobile-alt mr-1"></i><?= htmlspecialchars($student['parent_phone']) ?></small>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php if ($current_section): ?>
                                                                    <span class="badge badge-info">
                                                                        <i class="fa fa-check-circle mr-1"></i>
                                                                        <?= htmlspecialchars($current_section['section_name']) ?>
                                                                    </span>
                                                                <?php else: ?>
                                                                    <span class="badge badge-warning">
                                                                        <i class="fa fa-exclamation-circle mr-1"></i>
                                                                        Not Assigned
                                                                    </span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                            <?php else: ?>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <div class="alert alert-warning">
                                                        <i class="fa fa-info-circle mr-2"></i>
                                                        No active students found for Class <?= htmlspecialchars($class_name) ?>.
                                                        <br><small>Check if students are assigned to this class in the students table.</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Files -->
    <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>
    
    <!-- DataTables JS -->
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>
    
    <script src="js/main.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('.select2').select2({
                width: '100%'
            });
            
            // Initialize DataTable only if table exists
            var dataTable = null;
            if ($('#studentsTable').length) {
                dataTable = $('#studentsTable').DataTable({
                    "pageLength": 1000,
                    "ordering": true,
                    "order": [[2, 'asc']], // Sort by name by default
                    "columnDefs": [
                        { 
                            "orderable": false, 
                            "targets": 0,
                            "className": "dt-checkboxes-cell"
                        },
                        { 
                            "orderable": true, 
                            "targets": [1, 2, 3, 4, 5, 6, 7]
                        }
                    ],
                    "language": {
                        "search": "Search students:",
                        "lengthMenu": "Show _MENU_ entries",
                        "info": "Showing _START_ to _END_ of _TOTAL_ students",
                        "paginate": {
                            "first": "First",
                            "last": "Last",
                            "next": "Next",
                            "previous": "Previous"
                        },
                        "emptyTable": "No students found",
                        "zeroRecords": "No matching students found"
                    },
                    "dom": '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                           '<"row"<"col-sm-12"tr>>' +
                           '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                    "initComplete": function(settings, json) {
                        // Make sure checkboxes work with DataTables
                        initCheckboxHandlers();
                    },
                    "drawCallback": function(settings) {
                        // Re-initialize checkbox handlers after each draw
                        initCheckboxHandlers();
                    }
                });
            }
            
            // Function to initialize checkbox handlers
            function initCheckboxHandlers() {
                // DataTable select all checkbox
                $('#dataTableSelectAll').off('change').on('change', function() {
                    const isChecked = $(this).prop('checked');
                    $('.student-checkbox').prop('checked', isChecked).trigger('change');
                    updateSelectedCount();
                });
                
                // Individual checkbox change
                $('.student-checkbox').off('change').on('change', function() {
                    updateSelectedCount();
                    
                    // Update DataTable select all checkbox
                    const total = $('.student-checkbox').length;
                    const checked = $('.student-checkbox:checked').length;
                    $('#dataTableSelectAll').prop('checked', checked === total && total > 0);
                    $('#selectAll').prop('checked', checked === total && total > 0);
                    
                    // Highlight row
                    if ($(this).prop('checked')) {
                        $(this).closest('tr').addClass('highlight-row');
                    } else {
                        $(this).closest('tr').removeClass('highlight-row');
                    }
                });
            }
            
            // Manual select all checkbox
            $('#selectAll').change(function() {
                const isChecked = $(this).prop('checked');
                $('.student-checkbox').prop('checked', isChecked).trigger('change');
                $('#dataTableSelectAll').prop('checked', isChecked);
                updateSelectedCount();
            });
            
            // Form submission validation
            $('#assignForm').submit(function(e) {
                const selectedStudents = $('.student-checkbox:checked').length;
                const sectionId = $('#section_id').val();
                const academicYear = $('#academic_year').val();
                
                if (selectedStudents === 0) {
                    e.preventDefault();
                    showAlert('warning', 'Please select at least one student.');
                    return false;
                }
                
                if (!sectionId) {
                    e.preventDefault();
                    showAlert('warning', 'Please select a section.');
                    return false;
                }
                
                if (!academicYear) {
                    e.preventDefault();
                    showAlert('warning', 'Please select an academic year.');
                    return false;
                }
                
                // Get selected student names for confirmation
                const selectedNames = [];
                $('.student-checkbox:checked').each(function() {
                    selectedNames.push($(this).data('student-name'));
                });
                
                // Show confirmation modal instead of alert
                showConfirmationModal(selectedStudents, selectedNames);
                return false;
            });
            
            // Auto-load students when class is selected
            $('#class_id').change(function() {
                if ($(this).val()) {
                    $('#classFilterForm').submit();
                }
            });
            
            function updateSelectedCount() {
                const selectedCount = $('.student-checkbox:checked').length;
                $('#selectedCount').text(selectedCount + ' selected');
                
                // Update button text
                const buttonText = selectedCount > 0 ? 
                    `Assign Section to ${selectedCount} Student(s)` : 
                    'Assign Section';
                $('#assignButtonText').text(buttonText);
            }
            
            function showAlert(type, message) {
                const alertClass = type === 'warning' ? 'alert-warning' : 'alert-danger';
                const icon = type === 'warning' ? 'fa-exclamation-triangle' : 'fa-exclamation-circle';
                
                const alertHtml = `<div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                    <i class="fa ${icon} mr-2"></i> ${message}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>`;
                
                // Insert at the top of the panel body
                $('.panel-body').prepend(alertHtml);
                
                // Auto remove after 5 seconds
                setTimeout(function() {
                    $('.alert').alert('close');
                }, 5000);
            }
            
            function showConfirmationModal(selectedCount, selectedNames) {
                // Create modal HTML
                const modalHtml = `
                <div class="modal fade" id="confirmationModal" tabindex="-1" role="dialog" aria-labelledby="confirmationModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header bg-primary text-white">
                                <h5 class="modal-title" id="confirmationModalLabel">
                                    <i class="fa fa-question-circle mr-2"></i>Confirm Section Assignment
                                </h5>
                                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="alert alert-info">
                                    <i class="fa fa-info-circle mr-2"></i>
                                    You are about to assign section <strong>${$('#section_id option:selected').text()}</strong> 
                                    for academic year <strong>${$('#academic_year option:selected').text()}</strong> 
                                    to <strong>${selectedCount} student(s)</strong>.
                                </div>
                                
                                <h6>Selected Students (${selectedCount}):</h6>
                                <div class="selected-students-list" style="max-height: 200px; overflow-y: auto; border: 1px solid #dee2e6; padding: 10px; border-radius: 5px;">
                                    <ul class="list-group list-group-flush">
                                        ${selectedNames.slice(0, 20).map(name => `<li class="list-group-item py-2"><i class="fa fa-user mr-2 text-primary"></i>${name}</li>`).join('')}
                                        ${selectedNames.length > 20 ? `<li class="list-group-item py-2 text-muted"><i class="fa fa-ellipsis-h mr-2"></i>and ${selectedNames.length - 20} more students...</li>` : ''}
                                    </ul>
                                </div>
                                
                                <div class="mt-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="confirmAssignment">
                                        <label class="form-check-label" for="confirmAssignment">
                                            I confirm that I want to assign the selected section to the above students.
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                                    <i class="fa fa-times mr-1"></i> Cancel
                                </button>
                                <button type="button" class="btn btn-success" id="confirmButton" disabled>
                                    <i class="fa fa-check mr-1"></i> Confirm Assignment
                                </button>
                            </div>
                        </div>
                    </div>
                </div>`;
                
                // Remove existing modal if any
                $('#confirmationModal').remove();
                
                // Append modal to body
                $('body').append(modalHtml);
                
                // Show modal
                $('#confirmationModal').modal('show');
                
                // Enable confirm button when checkbox is checked
                $('#confirmAssignment').change(function() {
                    $('#confirmButton').prop('disabled', !$(this).prop('checked'));
                });
                
                // Handle confirm button click
                $('#confirmButton').click(function() {
                    $('#confirmationModal').modal('hide');
                    // Submit the form
                    $('#assignForm').off('submit').submit();
                });
            }
            
            // Initialize count
            updateSelectedCount();
            
            // Auto-close alerts after 5 seconds
            setTimeout(function() {
                $('.alert-dismissible').alert('close');
            }, 5000);
        });
    </script>
</body>
</html>
<?php
$conn->close();
?>