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

// 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->rowCount() > 0) {
    $current_year = $current_year_result->fetch(PDO::FETCH_ASSOC);
    $current_academic_year = $current_year['ay_ad'];
}

// Get important statistics
$total_students = $conn->query("SELECT COUNT(*) as count FROM students WHERE status = 'active'")->fetch(PDO::FETCH_ASSOC)['count'];
$total_with_sections = $conn->query("SELECT COUNT(DISTINCT student_id) as count FROM student_class_section_data WHERE academic_year = '$current_academic_year' AND status = 'active'")->fetch(PDO::FETCH_ASSOC)['count'];
$students_without_sections = $total_students - $total_with_sections;

// Get classes for grouping
$classes_list = $conn->query("SELECT class_id, class, class_numeric FROM classes WHERE status = 1 ORDER BY class_numeric")->fetchAll(PDO::FETCH_ASSOC);

// Get filter parameters
$filter_class = isset($_GET['filter_class']) ? $_GET['filter_class'] : '';
$filter_section = isset($_GET['filter_section']) ? $_GET['filter_section'] : '';
$filter_status = isset($_GET['filter_status']) ? $_GET['filter_status'] : '';
$filter_group = isset($_GET['filter_group']) ? $_GET['filter_group'] : 'class';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Students - Student Details</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>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="js/DataTables/datatables.min.css"/>
    
    <style>
        /* Custom Styles */
        .alert-info-custom {
            background-color: #e3f2fd;
            border-left: 4px solid #2196F3;
            padding: 12px 15px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .stats-box {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 10px;
        }
        .stats-number {
            font-size: 1.5rem;
            font-weight: bold;
            color: #007bff;
        }
        .stats-label {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .table th, .table td {
            padding: 8px 10px !important;
            vertical-align: middle;
            font-size: 13px;
        }
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            text-align: center;
        }
        .student-name-link {
            color: #007bff;
            cursor: pointer;
            font-weight: 500;
        }
        .student-name-link:hover {
            text-decoration: underline;
            color: #0056b3;
        }
        .section-badge {
            display: inline-block;
            background: #17a2b8;
            color: white;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        .no-section-badge {
            display: inline-block;
            background: #ffc107;
            color: #212529;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        .status-active {
            color: #28a745;
            font-weight: bold;
        }
        .status-inactive, .status-dropout {
            color: #dc3545;
            font-weight: bold;
        }
        .status-transferred {
            color: #ffc107;
            font-weight: bold;
        }
        .status-promoted {
            color: #17a2b8;
            font-weight: bold;
        }
        .action-buttons {
            white-space: nowrap;
        }
        .action-buttons .btn {
            padding: 4px 8px;
            font-size: 12px;
            margin: 2px;
            border-radius: 3px;
        }
        .filter-section {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1040;
        }
        .student-details-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 600px;
            max-width: 90%;
            background: white;
            border-radius: 8px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.2);
            z-index: 1050;
        }
        .close-btn {
            float: right;
            font-size: 1.5rem;
            font-weight: bold;
            line-height: 1;
            color: #000;
            text-shadow: 0 1px 0 #fff;
            opacity: .5;
            cursor: pointer;
        }
        .close-btn:hover {
            opacity: .75;
        }
        .btn-group-sm > .btn, .btn-sm {
            padding: .25rem .5rem;
            font-size: .875rem;
            line-height: 1.5;
            border-radius: .2rem;
        }
        #studentTable_wrapper {
            padding: 0;
        }
        .dataTables_filter {
            margin-bottom: 15px;
        }
        .dataTables_filter label {
            font-weight: 500;
        }
        .dataTables_length {
            margin-bottom: 15px;
        }
        .dataTables_length label {
            font-weight: 500;
        }
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
        }
        .page-info {
            font-size: 14px;
            color: #666;
        }
        .pagination .page-item.active .page-link {
            background-color: #007bff;
            border-color: #007bff;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            padding: 5px 10px;
            margin-left: 2px;
        }
        .class-group-header {
            background-color: #e9ecef !important;
            font-weight: bold;
            font-size: 14px;
            color: #495057;
        }
        .class-group-header td {
            padding: 10px !important;
        }
        .profile-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #007bff;
            color: white;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 14px;
        }
        .student-info-cell {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .student-info-cell .profile-icon {
            flex-shrink: 0;
        }
        .student-info-cell .student-details {
            flex-grow: 1;
        }
        .student-info-cell .student-name {
            font-weight: 600;
            color: #333;
        }
        .student-info-cell .student-regd {
            font-size: 11px;
            color: #6c757d;
        }
        .badge-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }
        .badge-active {
            background-color: #d4edda;
            color: #155724;
        }
        .badge-inactive, .badge-dropout {
            background-color: #f8d7da;
            color: #721c24;
        }
        .badge-transferred {
            background-color: #fff3cd;
            color: #856404;
        }
        .badge-promoted {
            background-color: #d1ecf1;
            color: #0c5460;
        }
    </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">
                        <!-- Breadcrumb -->
                        <div class="row breadcrumb-div" style="margin-bottom: 15px;">
                            <div class="col-md-6">
                                <ul class="breadcrumb" style="margin-bottom: 0; padding: 5px 0;">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li>Students</li>
                                    <li class="active">Manage Students</li>
                                </ul>
                            </div>
                            <div class="col-md-6 text-right">
                                <span class="badge badge-info" style="font-size: 0.9rem; padding: 5px 10px;">
                                    <i class="fa fa-calendar"></i> <?= $current_academic_year ?: 'Year Not Set' ?>
                                </span>
                            </div>
                        </div>

                        <!-- Important Alerts -->
                        <div class="row">
                            <div class="col-md-12">
                                <?php if($students_without_sections > 0): ?>
                                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                                    <i class="fa fa-exclamation-triangle"></i>
                                    <strong>Attention:</strong> <?= $students_without_sections ?> student(s) are not assigned to any section for <?= $current_academic_year ?>. 
                                    <a href="assign_sections.php" class="alert-link">Assign sections now</a>
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($current_academic_year): ?>
                                <div class="alert alert-info-custom">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="stats-box text-center">
                                                <div class="stats-number"><?= $total_students ?></div>
                                                <div class="stats-label">Total Active Students</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="stats-box text-center">
                                                <div class="stats-number"><?= $total_with_sections ?></div>
                                                <div class="stats-label">With Sections (<?= $current_academic_year ?>)</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="stats-box text-center">
                                                <div class="stats-number"><?= $students_without_sections ?></div>
                                                <div class="stats-label">Without Sections</div>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="stats-box text-center">
                                                <a href="add_student.php" class="btn btn-success btn-sm btn-block">
                                                    <i class="fa fa-plus"></i> Add New Student
                                                </a>
                                                <small class="text-muted mt-2 d-block">Add new student record</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php else: ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <i class="fa fa-exclamation-circle"></i>
                                    <strong>Important:</strong> No active academic year set. Please set an active academic year in settings.
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Filter Section -->
                        <div class="filter-section">
                            <form id="filterForm" method="GET" action="">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="form-group mb-2">
                                            <label for="filter_class" class="mb-1"><small><i class="fa fa-graduation-cap"></i> Class</small></label>
                                            <select id="filter_class" name="filter_class" class="form-control form-control-sm">
                                                <option value="">All Classes</option>
                                                <?php
                                                $classes_query = "SELECT class_id, class, class_numeric FROM classes WHERE status = 1 ORDER BY class_numeric";
                                                $classes_result = $conn->query($classes_query);
                                                while ($class = $classes_result->fetch(PDO::FETCH_ASSOC)) {
                                                    $selected = ($filter_class == $class['class_id']) ? 'selected' : '';
                                                    echo '<option value="' . $class['class_id'] . '" ' . $selected . '>Class ' . 
                                                         htmlspecialchars($class['class']) . ' (G' . $class['class_numeric'] . ')</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group mb-2">
                                            <label for="filter_section" class="mb-1"><small><i class="fa fa-columns"></i> Section</small></label>
                                            <select id="filter_section" name="filter_section" class="form-control form-control-sm">
                                                <option value="">All Sections</option>
                                                <?php
                                                $sections_query = "SELECT section_id, section_name FROM sections ORDER BY section_name";
                                                $sections_result = $conn->query($sections_query);
                                                while ($section = $sections_result->fetch(PDO::FETCH_ASSOC)) {
                                                    $selected = ($filter_section == $section['section_id']) ? 'selected' : '';
                                                    echo '<option value="' . $section['section_id'] . '" ' . $selected . '>' . 
                                                         htmlspecialchars($section['section_name']) . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group mb-2">
                                            <label for="filter_status" class="mb-1"><small><i class="fa fa-flag"></i> Status</small></label>
                                            <select id="filter_status" name="filter_status" class="form-control form-control-sm">
                                                <option value="">All Status</option>
                                                <option value="active" <?= $filter_status == 'active' ? 'selected' : '' ?>>Active</option>
                                                <option value="inactive" <?= $filter_status == 'inactive' ? 'selected' : '' ?>>Inactive</option>
                                                <option value="transferred" <?= $filter_status == 'transferred' ? 'selected' : '' ?>>Transferred</option>
                                                <option value="dropout" <?= $filter_status == 'dropout' ? 'selected' : '' ?>>Dropout</option>
                                                <option value="promoted" <?= $filter_status == 'promoted' ? 'selected' : '' ?>>Promoted</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="form-group mb-2">
                                            <label for="filter_group" class="mb-1"><small><i class="fa fa-group"></i> Group By</small></label>
                                            <select id="filter_group" name="filter_group" class="form-control form-control-sm">
                                                <option value="class" <?= $filter_group == 'class' ? 'selected' : '' ?>>Class</option>
                                                <option value="status" <?= $filter_group == 'status' ? 'selected' : '' ?>>Status</option>
                                                <option value="none" <?= $filter_group == 'none' ? 'selected' : '' ?>>No Grouping</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group mb-2">
                                            <label class="mb-1 d-block">&nbsp;</label>
                                            <button type="submit" class="btn btn-primary btn-sm">
                                                <i class="fa fa-filter"></i> Apply Filters
                                            </button>
                                            <a href="student_detail.php" class="btn btn-secondary btn-sm">
                                                <i class="fa fa-refresh"></i> Reset
                                            </a>
                                            <button type="button" id="exportBtn" class="btn btn-success btn-sm">
                                                <i class="fa fa-download"></i> Export
                                            </button>
                                            <button type="button" id="printBtn" class="btn btn-info btn-sm">
                                                <i class="fa fa-print"></i> Print
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <!-- Main Table -->
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5><i class="fa fa-users"></i> Student List (<?= $total_students ?> total)</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body p-2">
                                        <div class="table-responsive">
                                            <table id="studentTable" class="table table-striped table-bordered" style="width:100%">
                                                <thead>
                                                    <tr>
                                                        <th width="30">#</th>
                                                        <th width="70">Regd. ID</th>
                                                        <th>Student Information</th>
                                                        <th width="70">Gender</th>
                                                        <th width="90">DOB</th>
                                                        <th width="50">Class</th>
                                                        <th width="30">Section</th>
                                                        <th>Parent</th>
                                                        <!-- <th width="90">Contact</th> -->
                                                        <th width="45">Status</th>
                                                        <th width="80">Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    // Build query with filters
                                                    $query = "SELECT 
                                                        s.student_id, 
                                                        s.regd_id, 
                                                        s.name, 
                                                        s.gender, 
                                                        s.dob, 
                                                        s.phone, 
                                                        s.email,
                                                        s.address,
                                                        s.parent_name, 
                                                        s.parent_phone,
                                                        s.std_group,
                                                        s.status as student_status,
                                                        c.class_id,
                                                        c.class,
                                                        c.class_numeric,
                                                        scsd.section_id,
                                                        sec.section_name,
                                                        scsd.academic_year,
                                                        scsd.status as section_status,
                                                        scsd.remarks as section_remarks
                                                    FROM students s
                                                    LEFT JOIN student_class_section_data scsd ON s.student_id = scsd.student_id 
                                                        AND scsd.academic_year = :academic_year
                                                    LEFT JOIN classes c ON scsd.class_id = c.class_id
                                                    LEFT JOIN sections sec ON scsd.section_id = sec.section_id
                                                    WHERE 1=1";
                                                    
                                                    $params = [':academic_year' => $current_academic_year];
                                                    
                                                    // Add filters
                                                    if (!empty($filter_class)) {
                                                        $query .= " AND c.class_id = :class_id";
                                                        $params[':class_id'] = $filter_class;
                                                    }
                                                    
                                                    if (!empty($filter_section)) {
                                                        $query .= " AND sec.section_id = :section_id";
                                                        $params[':section_id'] = $filter_section;
                                                    }
                                                    
                                                    if (!empty($filter_status)) {
                                                        $query .= " AND (s.status = :status OR scsd.status = :status2)";
                                                        $params[':status'] = $filter_status;
                                                        $params[':status2'] = $filter_status;
                                                    }
                                                    
                                                    // Group by and order
                                                    if ($filter_group == 'class') {
                                                        $query .= " ORDER BY c.class_numeric, s.name ASC";
                                                    } elseif ($filter_group == 'status') {
                                                        $query .= " ORDER BY s.status, c.class_numeric, s.name ASC";
                                                    } else {
                                                        $query .= " ORDER BY s.name ASC";
                                                    }
                                                    
                                                    $stmt = $conn->prepare($query);
                                                    $stmt->execute($params);
                                                    
                                                    $sn = 1;
                                                    $current_class = '';
                                                    $current_status = '';
                                                    
                                                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                        $student_id = $row['student_id'];
                                                        
                                                        // Add group header if grouping by class
                                                        if ($filter_group == 'class' && $current_class != $row['class']) {
                                                            $current_class = $row['class'];
                                                            $class_display = $row['class'] ? $row['class'] : 'Unassigned';
                                                            echo "<tr class='class-group-header'>";
                                                            echo "<td colspan='10'><i class='fa fa-graduation-cap'></i> Class: " . htmlspecialchars($class_display) . " (Grade " . $row['class_numeric'] . ")</td>";
                                                            echo "</tr>";
                                                        }
                                                        
                                                        // Add group header if grouping by status
                                                        if ($filter_group == 'status' && $current_status != $row['section_status']) {
                                                            $current_status = $row['section_status'] ? $row['section_status'] : 'Not Assigned';
                                                            $status_icon = '';
                                                            switch($row['section_status']) {
                                                                case 'active': $status_icon = 'fa-check-circle text-success'; break;
                                                                case 'inactive': $status_icon = 'fa-ban text-danger'; break;
                                                                case 'transferred': $status_icon = 'fa-exchange text-warning'; break;
                                                                case 'dropout': $status_icon = 'fa-user-times text-danger'; break;
                                                                case 'promoted': $status_icon = 'fa-arrow-up text-info'; break;
                                                                default: $status_icon = 'fa-question-circle text-secondary';
                                                            }
                                                            echo "<tr class='class-group-header'>";
                                                            echo "<td colspan='10'><i class='fa $status_icon'></i> Status: " . ucfirst($current_status) . "</td>";
                                                            echo "</tr>";
                                                        }
                                                        
                                                        $section_name = $row['section_name'] ?: 'N/A';
                                                        $section_class = $row['section_name'] ? 'section-badge' : 'no-section-badge';
                                                        $class_display = $row['class'] ? $row['class'] : 'N/A';
                                                        
                                                        // Determine status class and badge
                                                        $status_value = $row['section_status'] ? $row['section_status'] : 'not_assigned';
                                                        $status_badge_class = 'badge-secondary';
                                                        $status_icon = 'fa-circle-o';
                                                        
                                                        switch($status_value) {
                                                            case 'active':
                                                                $status_badge_class = 'badge-active';
                                                                $status_icon = 'fa-check-circle';
                                                                break;
                                                            case 'inactive':
                                                            case 'dropout':
                                                                $status_badge_class = 'badge-inactive';
                                                                $status_icon = 'fa-ban';
                                                                break;
                                                            case 'transferred':
                                                                $status_badge_class = 'badge-transferred';
                                                                $status_icon = 'fa-exchange';
                                                                break;
                                                            case 'promoted':
                                                                $status_badge_class = 'badge-promoted';
                                                                $status_icon = 'fa-arrow-up';
                                                                break;
                                                            default:
                                                                $status_badge_class = 'badge-secondary';
                                                                $status_icon = 'fa-question-circle';
                                                        }
                                                        
                                                        $status_text = $row['section_status'] ? ucfirst($row['section_status']) : 'Not Assigned';
                                                        $dob_display = $row['dob'] ? date('Y-m-d', strtotime($row['dob'])) : 'N/A';
                                                        $parent_name = $row['parent_name'] ? $row['parent_name'] : 'N/A';
                                                        
                                                        // Get initials for profile icon
                                                        $name_parts = explode(' ', $row['name']);
                                                        $initials = '';
                                                        foreach($name_parts as $part) {
                                                            if(!empty($part)) $initials .= strtoupper(substr($part, 0, 1));
                                                        }
                                                        $initials = substr($initials, 0, 2);
                                                        
                                                        echo "<tr>";
                                                        echo "<td class='text-center'>$sn</td>";
                                                        echo "<td class='text-center'><span class='badge badge-info'>" . htmlspecialchars($row['regd_id']) . "</span></td>";
                                                        echo "<td>";
                                                        "<div class='student-info-cell'>";
                                                        "<div class='profile-icon'>$initials</div>";
                                                        echo "<div class='student-details'>";
                                                        echo "<div class='student-name'>";
                                                        echo "<span class='student-name-link' onclick='toggleDetails($student_id)'>" . htmlspecialchars($row['name']) . "</span>";
                                                        echo "</div>";
                                                        echo "<div class='student-regd'><i class='fa fa-id-card'></i> " . htmlspecialchars($row['regd_id']) . "</div>";
                                                        echo "</div>";
                                                        echo "</div>";
                                                        echo "</td>";
                                                        echo "<td class='text-center'>";
                                                        $gender_icon = ($row['gender'] == 'Male') ? 'fa-male' : (($row['gender'] == 'Female') ? 'fa-female' : 'fa-genderless');
                                                        echo "<i class='fa $gender_icon'></i> " . htmlspecialchars($row['gender']);
                                                        echo "</td>";
                                                        echo "<td class='text-center'>$dob_display</td>";
                                                        echo "<td class='text-center'><span class='badge badge-primary'>$class_display</span></td>";
                                                        echo "<td class='text-center'><span class='$section_class'>" . htmlspecialchars($section_name) . "</span></td>";
                                                        echo "<td>";
                                                        echo "<i class='fa fa-user'></i> " . htmlspecialchars($parent_name) . "<br>";
                                                        echo "<small><i class='fa fa-phone'></i> " . htmlspecialchars($row['parent_phone']) . "</small>";
                                                        echo "</td>";
                                                        echo "<td class='text-center'>";
                                                        echo "<span class='badge-status $status_badge_class'><i class='fa $status_icon'></i> </span>";
                                                        echo "</td>";
                                                        echo "<td class='text-center action-buttons'>";
                                                        echo "<a href='view_student.php?student_id=$student_id' class='btn btn-info btn-sm' title='View Details'>";
                                                        echo "<i class='fa fa-eye'></i>";
                                                        echo "</a>";
                                                        echo "<a href='edit_student.php?student_id=$student_id' class='btn btn-primary btn-sm' title='Edit Student'>";
                                                        echo "<i class='fa fa-edit'></i>";
                                                        echo "</a>";
                                                        echo "<button onclick='changeSection($student_id)' class='btn btn-warning btn-sm' title='Change Section'>";
                                                        echo "<i class='fa fa-exchange'></i>";
                                                        echo "</button>";
                                                        echo "<button onclick='updateStatus($student_id)' class='btn btn-secondary btn-sm' title='Update Status'>";
                                                        echo "<i class='fa fa-flag'></i>";
                                                        echo "</button>";
                                                        "<button onclick='deleteStudent($student_id)' class='btn btn-danger btn-sm' title='Delete Student'>";
                                                        "<i class='fa fa-trash'></i>";
                                                        "</button>";
                                                        echo "</td>";
                                                        echo "</tr>";
                                                        
                                                        // Hidden data for modal
                                                        echo "<div style='display: none;' id='data-$student_id'>";
                                                        echo "<span id='name-$student_id'>" . htmlspecialchars($row['name']) . "</span>";
                                                        echo "<span id='regd_id-$student_id'>" . htmlspecialchars($row['regd_id']) . "</span>";
                                                        echo "<span id='gender-$student_id'>" . htmlspecialchars($row['gender']) . "</span>";
                                                        echo "<span id='dob-$student_id'>" . ($row['dob'] ? date('d-m-Y', strtotime($row['dob'])) : 'N/A') . "</span>";
                                                        echo "<span id='phone-$student_id'>" . htmlspecialchars($row['phone']) . "</span>";
                                                        echo "<span id='email-$student_id'>" . htmlspecialchars($row['email']) . "</span>";
                                                        echo "<span id='address-$student_id'>" . htmlspecialchars($row['address']) . "</span>";
                                                        echo "<span id='parent_name-$student_id'>" . htmlspecialchars($row['parent_name']) . "</span>";
                                                        echo "<span id='parent_phone-$student_id'>" . htmlspecialchars($row['parent_phone']) . "</span>";
                                                        echo "<span id='class-$student_id'>$class_display</span>";
                                                        echo "<span id='section-$student_id'>" . htmlspecialchars($section_name) . "</span>";
                                                        echo "<span id='status-$student_id'>$status_text</span>";
                                                        echo "<span id='std_group-$student_id'>" . htmlspecialchars($row['std_group']) . "</span>";
                                                        echo "</div>";
                                                        
                                                        $sn++;
                                                    }
                                                    
                                                    if ($sn == 1) {
                                                        echo "<tr><td colspan='10' class='text-center'>No students found</td></tr>";
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Overlay and Details Box -->
    <div class="modal-overlay" onclick="closeDetails()"></div>
    <div id="student-details-modal" class="student-details-modal">
        <div class="modal-header" style="padding: 15px; border-bottom: 1px solid #dee2e6; background-color: #f8f9fa;">
            <h5 class="modal-title mb-0"><i class="fa fa-user-circle"></i> Student Details</h5>
            <span class="close-btn" onclick="closeDetails()">×</span>
        </div>
        <div id="student-details-content" class="modal-body" style="padding: 20px;">
            <!-- Content will be populated by JavaScript -->
        </div>
        <div class="modal-footer" style="padding: 15px; border-top: 1px solid #dee2e6;">
            <button type="button" class="btn btn-secondary btn-sm" onclick="closeDetails()"><i class="fa fa-times"></i> Close</button>
            <button type="button" class="btn btn-primary btn-sm" id="editFromDetailsBtn"><i class="fa fa-edit"></i> Edit</button>
        </div>
    </div>

    <!-- Change Section Modal -->
    <div id="changeSectionModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-md" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white py-2">
                    <h6 class="modal-title mb-0"><i class="fa fa-exchange"></i> Change Student Section</h6>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body p-3">
                    <form id="changeSectionForm">
                        <input type="hidden" id="change_student_id" name="student_id">
                        <div class="form-group mb-3">
                            <label for="new_class_id" class="mb-1"><strong>Class *</strong></label>
                            <select id="new_class_id" name="class_id" class="form-control form-control-sm" required>
                                <option value="">-- Select Class --</option>
                                <?php
                                $classes_result = $conn->query("SELECT class_id, class, class_numeric FROM classes WHERE status = 1 ORDER BY class_numeric");
                                while ($class = $classes_result->fetch(PDO::FETCH_ASSOC)) {
                                    echo '<option value="' . $class['class_id'] . '">Class ' . 
                                         htmlspecialchars($class['class']) . ' (Grade ' . $class['class_numeric'] . ')</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group mb-3">
                            <label for="new_section_id" class="mb-1"><strong>Section *</strong></label>
                            <select id="new_section_id" name="section_id" class="form-control form-control-sm" required disabled>
                                <option value="">-- Select Class First --</option>
                            </select>
                        </div>
                        <div class="form-group mb-3">
                            <label for="new_academic_year" class="mb-1"><strong>Academic Year *</strong></label>
                            <select id="new_academic_year" name="academic_year" class="form-control form-control-sm" required>
                                <option value="">-- Select --</option>
                                <?php
                                $years_query = "SELECT * FROM academic_years ORDER BY start_date DESC";
                                $years_result = $conn->query($years_query);
                                while ($year = $years_result->fetch(PDO::FETCH_ASSOC)) {
                                    $selected = ($year['ay_ad'] == $current_academic_year) ? 'selected' : '';
                                    echo '<option value="' . $year['ay_ad'] . '" ' . $selected . '>' . 
                                         $year['ay_ad'] . '</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group mb-2">
                            <label for="change_remarks" class="mb-1"><strong>Remarks</strong></label>
                            <textarea id="change_remarks" name="remarks" class="form-control form-control-sm" rows="2" placeholder="Optional remarks (e.g., reason for change)"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
                    <button type="button" class="btn btn-primary btn-sm" id="saveSectionBtn"><i class="fa fa-save"></i> Save Changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Update Status Modal -->
    <div id="updateStatusModal" class="modal fade" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header bg-warning py-2">
                    <h6 class="modal-title mb-0"><i class="fa fa-flag"></i> Update Student Status</h6>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body p-3">
                    <div id="studentInfo"></div>
                    <form id="updateStatusForm">
                        <input type="hidden" id="status_student_id" name="student_id">
                        <div class="form-group mb-3">
                            <label for="student_status" class="mb-1"><strong>Select Status</strong></label>
                            <select id="student_status" name="status" class="form-control form-control-sm" required>
                                <option value="">-- Select --</option>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="transferred">Transferred</option>
                                <option value="dropout">Dropout</option>
                                <option value="promoted">Promoted</option>
                                <option value="others">Others</option>
                            </select>
                        </div>
                        <div class="form-group mb-2">
                            <label for="status_remarks" class="mb-1"><strong>Remarks</strong></label>
                            <textarea id="status_remarks" name="remarks" class="form-control form-control-sm" rows="2" placeholder="Reason for status change (optional)"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
                    <button type="button" class="btn btn-warning btn-sm" id="saveStatusBtn"><i class="fa fa-save"></i> Update</button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Files -->
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script type="text/javascript" src="js/DataTables/datatables.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 DataTable
        var table = $('#studentTable').DataTable({
            "pageLength": 25,
            "lengthMenu": [[10, 25, 50, 100, 250, 500], [10, 25, 50, 100, 250, 500]],
            "order": [[0, 'asc']],
            "processing": true,
            "language": {
                "search": "<i class='fa fa-search'></i> Search:",
                "searchPlaceholder": "Search by name, ID, parent...",
                "lengthMenu": "Show _MENU_ entries",
                "info": "Showing _START_ to _END_ of _TOTAL_ students",
                "infoEmpty": "Showing 0 to 0 of 0 entries",
                "infoFiltered": "(filtered from _MAX_ total entries)",
                "paginate": {
                    "first": "First",
                    "last": "Last",
                    "next": "<i class='fa fa-chevron-right'></i>",
                    "previous": "<i class='fa fa-chevron-left'></i>"
                },
                "emptyTable": "No students found matching the criteria"
            },
            "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>>"
        });

        // Initialize Select2 for better dropdowns
        $('.form-control-sm').select2({
            width: '100%',
            minimumResultsForSearch: 10
        });

        // Apply filters on form submission
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            this.submit(); // Let the form submit normally with GET parameters
        });

        // Export to CSV
        $('#exportBtn').click(function() {
            var data = [];
            var headers = ['SN', 'Regd. ID', 'Name', 'Gender', 'DOB', 'Class', 'Section', 'Parent', 'Parent Phone', 'Status'];
            data.push(headers);
            
            table.rows({ search: 'applied' }).every(function() {
                var row = this.data();
                var parentCell = row[7] || '';
                var parentPhone = '';
                var parentMatch = parentCell.match(/[\d-]+/g);
                if (parentMatch && parentMatch.length > 1) {
                    parentPhone = parentMatch[1];
                }
                
                data.push([
                    this.index() + 1,
                    row[1].replace(/<[^>]*>/g, ''),
                    row[2].replace(/<[^>]*>/g, '').replace(/Student Information/g, '').trim(),
                    row[3].replace(/<[^>]*>/g, ''),
                    row[4],
                    row[5].replace(/<[^>]*>/g, ''),
                    row[6].replace(/<[^>]*>/g, ''),
                    row[7].replace(/<[^>]*>/g, '').split('\n')[0].replace(/i class=[^>]*><\/i> /g, ''),
                    parentPhone,
                    row[8].replace(/<[^>]*>/g, '')
                ]);
            });
            
            var csvContent = "data:text/csv;charset=utf-8,";
            data.forEach(function(rowArray) {
                var row = rowArray.map(function(item) {
                    return '"' + String(item).replace(/"/g, '""') + '"';
                }).join(",");
                csvContent += row + "\r\n";
            });
            
            var encodedUri = encodeURI(csvContent);
            var link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "students_" + new Date().toISOString().split('T')[0] + ".csv");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // Print functionality
        $('#printBtn').click(function() {
            window.print();
        });

        // Edit from details modal
        $('#editFromDetailsBtn').click(function() {
            var studentId = $('#student-details-modal').data('studentId');
            if (studentId) {
                window.location.href = 'edit_student.php?student_id=' + studentId;
            }
        });
    });

    function toggleDetails(studentId) {
        var detailsBox = $('#student-details-modal');
        var overlay = $('.modal-overlay');
        
        // Store student ID for edit button
        detailsBox.data('studentId', studentId);

        var studentDetails = `
            <div class="row">
                <div class="col-md-12 text-center mb-3">
                    <div class="profile-icon" style="width: 60px; height: 60px; font-size: 24px; margin: 0 auto;">
                        ${$('#name-' + studentId).text().charAt(0)}
                    </div>
                    <h5 class="mt-2">${$('#name-' + studentId).text()}</h5>
                    <span class="badge badge-info">${$('#regd_id-' + studentId).text()}</span>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-sm table-borderless">
                        <tr>
                            <td><strong><i class='fa fa-venus-mars'></i> Gender:</strong></td>
                            <td>${$('#gender-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-calendar'></i> DOB:</strong></td>
                            <td>${$('#dob-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-phone'></i> Phone:</strong></td>
                            <td>${$('#phone-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-envelope'></i> Email:</strong></td>
                            <td>${$('#email-' + studentId).text() || 'N/A'}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-map-marker'></i> Address:</strong></td>
                            <td>${$('#address-' + studentId).text() || 'N/A'}</td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-sm table-borderless">
                        <tr>
                            <td><strong><i class='fa fa-graduation-cap'></i> Class:</strong></td>
                            <td>${$('#class-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-columns'></i> Section:</strong></td>
                            <td>${$('#section-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-user'></i> Parent:</strong></td>
                            <td>${$('#parent_name-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-phone'></i> Parent Phone:</strong></td>
                            <td>${$('#parent_phone-' + studentId).text()}</td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-tag'></i> Status:</strong></td>
                            <td><span class="badge-status ${$('#status-' + studentId).text().toLowerCase().includes('active') ? 'badge-active' : 'badge-inactive'}">${$('#status-' + studentId).text()}</span></td>
                        </tr>
                        <tr>
                            <td><strong><i class='fa fa-group'></i> Group:</strong></td>
                            <td>${$('#std_group-' + studentId).text() || 'N/A'}</td>
                        </tr>
                    </table>
                </div>
            </div>
        `;

        $('#student-details-content').html(studentDetails);
        detailsBox.show();
        overlay.show();
    }

    function closeDetails() {
        $('#student-details-modal').hide();
        $('.modal-overlay').hide();
    }

    function changeSection(studentId) {
        $('#change_student_id').val(studentId);
        
        // Reset form
        $('#new_class_id').val('').trigger('change');
        $('#new_section_id').html('<option value="">-- Select Class First --</option>').prop('disabled', true);
        $('#new_academic_year').val('<?= $current_academic_year ?>').trigger('change');
        $('#change_remarks').val('');
        
        $('#changeSectionModal').modal('show');
    }

    // Load sections when class changes in modal
    $('#new_class_id').change(function() {
        var classId = $(this).val();
        if (classId) {
            $.ajax({
                url: 'ajax/get_sections.php',
                type: 'GET',
                data: { class_id: classId },
                beforeSend: function() {
                    $('#new_section_id').html('<option value="">Loading...</option>').prop('disabled', true);
                },
                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>';
                            });
                            $('#new_section_id').html(options).prop('disabled', false);
                        } else {
                            $('#new_section_id').html('<option value="">No sections available</option>').prop('disabled', true);
                        }
                    } catch(e) {
                        $('#new_section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
                        console.error('Error parsing sections:', e);
                    }
                },
                error: function(xhr, status, error) {
                    $('#new_section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
                    console.error('AJAX Error:', error);
                }
            });
        } else {
            $('#new_section_id').html('<option value="">-- Select Class First --</option>').prop('disabled', true);
        }
    });

    // Save section change
    $('#saveSectionBtn').click(function() {
        var formData = $('#changeSectionForm').serialize();
        
        if (!$('#new_class_id').val() || !$('#new_section_id').val() || !$('#new_academic_year').val()) {
            Swal.fire('Error!', 'Please fill all required fields', 'error');
            return;
        }
        
        Swal.fire({
            title: 'Change Section?',
            text: 'Are you sure you want to update this student\'s section?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, update it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'ajax/update_student_section.php',
                    type: 'POST',
                    data: formData,
                    beforeSend: function() {
                        $('#saveSectionBtn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
                    },
                    success: function(response) {
                        $('#saveSectionBtn').prop('disabled', false).html('<i class="fa fa-save"></i> Save Changes');
                        try {
                            const data = JSON.parse(response);
                            if (data.success) {
                                Swal.fire('Success!', data.message, 'success').then(() => {
                                    $('#changeSectionModal').modal('hide');
                                    location.reload();
                                });
                            } else {
                                Swal.fire('Error!', data.message, 'error');
                            }
                        } catch(e) {
                            Swal.fire('Error!', 'Failed to update: ' + response, 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#saveSectionBtn').prop('disabled', false).html('<i class="fa fa-save"></i> Save Changes');
                        Swal.fire('Error!', 'Server error: ' + error, 'error');
                    }
                });
            }
        });
    });

    function updateStatus(studentId) {
        // Show loading indicator
        Swal.fire({
            title: 'Loading...',
            text: 'Fetching student details',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Fetch student details from the data stored in hidden divs first
        setTimeout(function() {
            Swal.close();
            
            // Get data from hidden divs
            var name = $('#name-' + studentId).text();
            var regd_id = $('#regd_id-' + studentId).text();
            var class_name = $('#class-' + studentId).text();
            var section_name = $('#section-' + studentId).text();
            var current_status = $('#status-' + studentId).text().toLowerCase();
            
            // Store current status and student info in modal data
            $('#updateStatusModal').data('current-status', current_status);
            $('#updateStatusModal').data('student-name', name);
            $('#updateStatusModal').data('student-regd', regd_id);
            $('#updateStatusModal').data('student-class', class_name);
            $('#updateStatusModal').data('student-section', section_name);
            
            // Set student ID
            $('#status_student_id').val(studentId);
            
            // Clear and reset form
            $('#student_status').val('').trigger('change');
            $('#status_remarks').val('');
            
            // Update modal title with student info
            $('.modal-title').html('<i class="fa fa-flag"></i> Update Status - ' + name);
            
            // Add student info to modal body
            let studentInfoHtml = `
                <div class="alert alert-info p-2 mb-3" style="font-size: 12px;">
                    <div><strong>Regd ID:</strong> ${regd_id}</div>
                    <div><strong>Class/Section:</strong> ${class_name} - ${section_name}</div>
                    <div><strong>Current Status:</strong> 
                        <span class="badge ${getStatusBadgeClass(current_status)}">${current_status}</span>
                    </div>
                </div>
            `;
            
            // Remove existing info and add new
            $('#studentInfo').remove();
            $('.modal-body').prepend('<div id="studentInfo" class="mb-3">' + studentInfoHtml + '</div>');
            
            // Show modal
            $('#updateStatusModal').modal('show');
        }, 500);
    }

    // Helper function to get badge class based on status
    function getStatusBadgeClass(status) {
        status = status.toLowerCase();
        switch(status) {
            case 'active': return 'badge-success';
            case 'inactive': return 'badge-secondary';
            case 'transferred': return 'badge-warning';
            case 'dropout': return 'badge-danger';
            case 'promoted': return 'badge-info';
            default: return 'badge-secondary';
        }
    }

    // Helper function to get badge color
    function getStatusBadgeColor(status) {
        switch(status) {
            case 'active': return 'success';
            case 'inactive': return 'secondary';
            case 'transferred': return 'warning';
            case 'dropout': return 'danger';
            case 'promoted': return 'info';
            default: return 'secondary';
        }
    }

    // Save status update
    $('#saveStatusBtn').click(function() {
        var studentId = $('#status_student_id').val();
        var selectedStatus = $('#student_status').val();
        var remarks = $('#status_remarks').val();
        var currentStatus = $('#updateStatusModal').data('current-status');
        var studentName = $('#updateStatusModal').data('student-name');
        
        // Validate inputs
        if (!studentId) {
            Swal.fire('Error!', 'Student ID is missing', 'error');
            return;
        }
        
        if (!selectedStatus) {
            Swal.fire('Error!', 'Please select a status', 'error');
            return;
        }
        
        // Check if status is actually changed
        if (selectedStatus === currentStatus) {
            Swal.fire({
                icon: 'info',
                title: 'No Change',
                text: 'The selected status is the same as current status. No update needed.',
                timer: 2000,
                showConfirmButton: true
            }).then(() => {
                $('#updateStatusModal').modal('hide');
            });
            return;
        }
        
        // Confirm status change
        let statusText = selectedStatus.charAt(0).toUpperCase() + selectedStatus.slice(1);
        let currentStatusText = currentStatus ? currentStatus.charAt(0).toUpperCase() + currentStatus.slice(1) : 'Unknown';
        
        Swal.fire({
            title: 'Update Status?',
            html: `Change status for <strong>${studentName}</strong><br><br>
                   <div class="row text-center">
                       <div class="col-5">
                           <div class="badge badge-secondary p-2">${currentStatusText}</div>
                           <div><small>Current</small></div>
                       </div>
                       <div class="col-2"><i class="fa fa-arrow-right"></i></div>
                       <div class="col-5">
                           <div class="badge badge-${getStatusBadgeColor(selectedStatus)} p-2">${statusText}</div>
                           <div><small>New</small></div>
                       </div>
                   </div>
                   ${remarks ? '<hr><small><i class="fa fa-comment"></i> Remarks: ' + remarks + '</small>' : ''}`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, update it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Prepare form data
                var formData = new FormData();
                formData.append('student_id', studentId);
                formData.append('status', selectedStatus);
                formData.append('remarks', remarks);
                
                $.ajax({
                    url: 'ajax/update_student_status.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    beforeSend: function() {
                        $('#saveStatusBtn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Updating...');
                    },
                    success: function(response) {
                        $('#saveStatusBtn').prop('disabled', false).html('<i class="fa fa-save"></i> Update');
                        
                        try {
                            // Handle response if it's already an object
                            const data = typeof response === 'object' ? response : JSON.parse(response);
                            
                            if (data.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Updated!',
                                    html: `Status for <strong>${studentName}</strong> changed from<br>
                                           <span class="badge badge-secondary">${currentStatusText}</span> 
                                           <i class="fa fa-arrow-right"></i> 
                                           <span class="badge badge-${getStatusBadgeColor(selectedStatus)}">${statusText}</span>`,
                                    timer: 3000,
                                    showConfirmButton: true
                                }).then(() => {
                                    $('#updateStatusModal').modal('hide');
                                    location.reload();
                                });
                            } else {
                                Swal.fire('Error!', data.message || 'Failed to update status', 'error');
                            }
                        } catch(e) {
                            console.error('Parse error:', e);
                            console.log('Raw response:', response);
                            Swal.fire('Error!', 'Failed to process server response. Check console for details.', 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#saveStatusBtn').prop('disabled', false).html('<i class="fa fa-save"></i> Update');
                        
                        let errorMessage = 'Server error: ' + error;
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.message) {
                                errorMessage = response.message;
                            }
                        } catch(e) {
                            // Use default error message
                        }
                        
                        Swal.fire('Error!', errorMessage, 'error');
                    }
                });
            }
        });
    });

    function deleteStudent(studentId) {
        Swal.fire({
            title: 'Delete Student?',
            text: "This action cannot be undone! All related records will be affected.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'ajax/delete_student.php',
                    type: 'POST',
                    data: { student_id: studentId },
                    success: function(response) {
                        try {
                            const data = JSON.parse(response);
                            if (data.success) {
                                Swal.fire('Deleted!', data.message, 'success').then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire('Error!', data.message, 'error');
                            }
                        } catch(e) {
                            Swal.fire('Error!', 'Failed to delete', 'error');
                        }
                    }
                });
            }
        });
    }

    // Close modal when clicking overlay
    $('.modal-overlay').click(function() {
        closeDetails();
    });

    // Handle escape key
    $(document).keydown(function(e) {
        if (e.key === 'Escape') {
            closeDetails();
            $('#changeSectionModal').modal('hide');
            $('#updateStatusModal').modal('hide');
        }
    });

    // Reset form when modals are hidden
    $('#updateStatusModal').on('hidden.bs.modal', function () {
        $('#student_status').val('').trigger('change');
        $('#status_remarks').val('');
        $('#studentInfo').remove();
        $(this).removeData('current-status');
        $(this).removeData('student-name');
        $(this).removeData('student-regd');
        $(this).removeData('student-class');
        $(this).removeData('student-section');
    });

    $('#changeSectionModal').on('hidden.bs.modal', function () {
        $('#new_class_id').val('').trigger('change');
        $('#new_section_id').html('<option value="">-- Select Class First --</option>').prop('disabled', true);
        $('#new_academic_year').val('<?= $current_academic_year ?>');
        $('#change_remarks').val('');
    });
    </script>
</body>
</html>