<?php
if (session_status() == PHP_SESSION_NONE) { session_start(); }
include_once 'db_connect.php'; 

$school = $conn->query("SELECT school_name FROM schools LIMIT 1")->fetch_assoc();
$current_school = $school['school_name'] ?? 'المدرسة';

// 1. التحديث التلقائي لقاعدة البيانات
$check_supervisor = $conn->query("SHOW COLUMNS FROM school_buses LIKE 'supervisor_name'");
if($check_supervisor && $check_supervisor->num_rows == 0) { $conn->query("ALTER TABLE school_buses ADD COLUMN supervisor_name VARCHAR(100) NULL"); }
$check_camera = $conn->query("SHOW COLUMNS FROM school_buses LIKE 'camera_stream_url'");
if($check_camera && $check_camera->num_rows == 0) { $conn->query("ALTER TABLE school_buses ADD COLUMN camera_stream_url VARCHAR(255) NULL"); }

$conn->query("CREATE TABLE IF NOT EXISTS student_transport (
    id INT AUTO_INCREMENT PRIMARY KEY,
    school_name VARCHAR(255),
    bus_id INT NOT NULL,
    student_name VARCHAR(255),
    class_info VARCHAR(255),
    pickup_address VARCHAR(255),
    pickup_time VARCHAR(20),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// 2. معالجة الإضافة والتحديث للباص
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bus_number = $conn->real_escape_string($_POST['bus_number']);
    $plate_number = $conn->real_escape_string($_POST['plate_number']);
    $driver_name = $conn->real_escape_string($_POST['driver_name']);
    $driver_phone = $conn->real_escape_string($_POST['driver_phone']);
    $supervisor_name = $conn->real_escape_string($_POST['supervisor_name']);
    $traccar_device_id = $conn->real_escape_string($_POST['traccar_device_id']);
    $camera_stream_url = $conn->real_escape_string($_POST['camera_stream_url'] ?? ''); 
    $capacity = (int)$_POST['capacity'];

    if (isset($_POST['add_bus']) && !empty($bus_number) && !empty($driver_name)) {
        $stmt = $conn->prepare("INSERT INTO school_buses (school_name, bus_number, plate_number, driver_name, driver_phone, supervisor_name, traccar_device_id, camera_stream_url, capacity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssssi", $current_school, $bus_number, $plate_number, $driver_name, $driver_phone, $supervisor_name, $traccar_device_id, $camera_stream_url, $capacity);
        $stmt->execute();
        echo "<script>alert('✅ تم إضافة الباص بنجاح!'); window.location.href='manage_transport.php';</script>";
    } 
    elseif (isset($_POST['update_bus'])) {
        $edit_id = (int)$_POST['edit_id'];
        $stmt = $conn->prepare("UPDATE school_buses SET bus_number=?, plate_number=?, driver_name=?, driver_phone=?, supervisor_name=?, traccar_device_id=?, camera_stream_url=?, capacity=? WHERE id=? AND school_name=?");
        $stmt->bind_param("ssssssssis", $bus_number, $plate_number, $driver_name, $driver_phone, $supervisor_name, $traccar_device_id, $camera_stream_url, $capacity, $edit_id, $current_school);
        $stmt->execute();
        echo "<script>alert('✅ تم تحديث بيانات الباص بنجاح!'); window.location.href='manage_transport.php';</script>";
    }
}

// 3. معالجة توزيع الطلاب
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_student'])) {
    $bus_id = (int)$_POST['bus_id'];
    $students_data = $_POST['student_data'] ?? []; 
    $pickup_address = $conn->real_escape_string($_POST['pickup_address']);
    $pickup_time = $conn->real_escape_string($_POST['pickup_time']);

    if ($bus_id > 0 && !empty($students_data)) {
        $stmt = $conn->prepare("INSERT INTO student_transport (school_name, bus_id, student_name, class_info, pickup_address, pickup_time) VALUES (?, ?, ?, ?, ?, ?)");
        foreach($students_data as $student_str) {
            $student_info = explode('|', $student_str); 
            $student_name = $conn->real_escape_string($student_info[0]);
            $class_info = $conn->real_escape_string($student_info[1] ?? 'بدون صف');
            $stmt->bind_param("sissss", $current_school, $bus_id, $student_name, $class_info, $pickup_address, $pickup_time);
            $stmt->execute();
        }
        echo "<script>alert('✅ تم ربط الطلاب بالباص بنجاح!'); window.location.href='manage_transport.php';</script>";
    }
}

// 4. الحذف
if (isset($_GET['delete_bus'])) {
    $del_id = (int)$_GET['delete_bus'];
    $conn->query("DELETE FROM school_buses WHERE id = $del_id AND school_name = '$current_school'");
    $conn->query("DELETE FROM student_transport WHERE bus_id = $del_id"); 
    echo "<script>window.location.href='manage_transport.php';</script>";
}
if (isset($_GET['remove_student'])) {
    $del_id = (int)$_GET['remove_student'];
    $conn->query("DELETE FROM student_transport WHERE id = $del_id AND school_name = '$current_school'");
    echo "<script>alert('✅ تم إزالة الطالب من الباص!'); window.location.href='manage_transport.php';</script>";
}

// 5. جلب بيانات للتعديل (إن وجدت)
$edit_data = null;
if(isset($_GET['edit_id'])) {
    $e_id = (int)$_GET['edit_id'];
    $edit_data = $conn->query("SELECT * FROM school_buses WHERE id = $e_id AND school_name = '$current_school'")->fetch_assoc();
}

// 6. جلب جميع الباصات وطلابهم للواجهة
$buses = $conn->query("SELECT * FROM school_buses WHERE school_name = '$current_school' ORDER BY id DESC");
$buses_array = [];
$students_by_bus = []; 

if($buses) { 
    while($b = $buses->fetch_assoc()) { 
        $buses_array[] = $b; 
        $bus_id = $b['id'];
        
        $st_query = $conn->query("SELECT * FROM student_transport WHERE bus_id = $bus_id ORDER BY pickup_time ASC");
        $students_by_bus[$bus_id] = [];
        if($st_query) {
            while($st = $st_query->fetch_assoc()) {
                $students_by_bus[$bus_id][] = $st;
            }
        }
    } 
}

// جلب الوسوم والطلاب للفلترة
$tags_query = $conn->query("SELECT DISTINCT stage_name, department_name, section_name FROM school_tags WHERE school_name = '$current_school'");
$tags_list = []; if($tags_query) { while($t = $tags_query->fetch_assoc()) { $tags_list[] = $t; } }

$students_query = $conn->query("SELECT student_name, stage, department, branch FROM students WHERE school_name = '$current_school'");
$students_list = [];
if($students_query) {
    while($s = $students_query->fetch_assoc()) {
        $parts = [];
        if(!empty($s['stage'])) $parts[] = trim($s['stage']);
        if(!empty($s['department'])) $parts[] = trim($s['department']);
        if(!empty($s['branch'])) $parts[] = trim($s['branch']);
        $students_list[] = [
            'name' => !empty($s['student_name']) ? trim($s['student_name']) : 'بدون اسم',
            'stage' => !empty($s['stage']) ? trim($s['stage']) : '',
            'dept' => !empty($s['department']) ? trim($s['department']) : '',
            'section' => !empty($s['branch']) ? trim($s['branch']) : '',
            'full_class' => !empty($parts) ? implode(' - ', $parts) : 'بدون صف'
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>إدارة النقل والباصات - <?php echo htmlspecialchars($current_school); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0f172a; color: #fff; padding: 20px; margin: 0; }
        .card { background: #1e293b; border-radius: 12px; padding: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); margin-bottom: 25px; border-top: 4px solid #f59e0b; }
        h3 { color: #f8fafc; margin-top: 0; border-bottom: 1px solid #334155; padding-bottom: 10px; display: flex; align-items: center; gap: 10px; }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
        .form-group { display: flex; flex-direction: column; gap: 8px; }
        label { color: #cbd5e1; font-size: 0.95rem; font-weight: bold; }
        input[type="text"], input[type="time"], input[type="number"], select { padding: 12px; background: #0f172a; color: #fff; border: 1px solid #475569; border-radius: 8px; font-size: 14px; outline: none; }
        input:focus, select:focus { border-color: #f59e0b; }
        .btn-submit { background: #f59e0b; color: white; border: none; padding: 12px; border-radius: 8px; cursor: pointer; font-weight: bold; width: 100%; font-size: 16px; transition: 0.3s; }
        .btn-submit.update-btn { background: #10b981; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; background: #0f172a; border-radius: 8px; overflow: hidden; }
        th, td { padding: 12px; border-bottom: 1px solid #334155; text-align: center; font-size: 14px; }
        th { background: #334155; color: #cbd5e1; }
        .action-btn { color: #ef4444; text-decoration: none; font-weight: bold; margin: 0 5px; cursor: pointer; }
        .action-btn.edit { color: #3b82f6; }
        .action-btn:hover { text-decoration: underline; }
        .badge { display: inline-block; padding: 4px 8px; border-radius: 12px; font-size: 12px; margin-top: 4px; color: white; cursor: pointer; }
        .smart-filter-box { background: #334155; padding: 15px; border-radius: 8px; grid-column: 1 / -1; border: 1px solid #475569; margin-bottom: 15px; }
        .smart-filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
        .search-input { background: #fff !important; color: #000 !important; border: 2px solid #3b82f6 !important; }
        .students-checkbox-list { max-height: 250px; overflow-y: auto; background: #0f172a; border: 2px solid #3b82f6; border-radius: 8px; padding: 10px; }
        .student-item { display: flex; align-items: center; gap: 12px; padding: 10px; border-bottom: 1px solid #1e293b; color: #e2e8f0; cursor: pointer; }
        
        /* Modal Styles */
        .modal-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.85); z-index:1000; justify-content:center; align-items:center; }
        .modal-box { background:#1e293b; width:90%; max-width:700px; padding:20px; border-radius:12px; border:2px solid #3b82f6; position:relative; max-height: 85vh; overflow-y: auto; }
        .modal-close { position:absolute; top:10px; left:20px; color:#ef4444; font-size:30px; cursor:pointer; }
    </style>
</head>
<body>

    <div class="card" id="busFormSection">
        <h3><i class="fas fa-bus"></i> <?= $edit_data ? 'تعديل بيانات الباص المحددة' : 'إضافة باص مدرسي ومشرف جديد' ?></h3>
        <form method="POST" action="manage_transport.php">
            <?php if($edit_data): ?>
                <input type="hidden" name="edit_id" value="<?= $edit_data['id'] ?>">
            <?php endif; ?>
            <div class="form-grid">
                <div class="form-group">
                    <label>رقم أو اسم الباص:</label>
                    <input type="text" name="bus_number" value="<?= $edit_data['bus_number'] ?? '' ?>" required>
                </div>
                <div class="form-group">
                    <label>اسم السائق:</label>
                    <input type="text" name="driver_name" value="<?= $edit_data['driver_name'] ?? '' ?>" required>
                </div>
                <div class="form-group">
                    <label>اسم مشرف / مشرفة الباص:</label>
                    <input type="text" name="supervisor_name" value="<?= $edit_data['supervisor_name'] ?? '' ?>">
                </div>
                <div class="form-group">
                    <label>رابط التتبع أو الـ ID (Traccar):</label>
                    <input type="text" name="traccar_device_id" value="<?= $edit_data['traccar_device_id'] ?? '' ?>" placeholder="الرابط الكامل أو رقم IMEI">
                </div>
                <div class="form-group">
                    <label>رابط الكاميرا (Live Stream):</label>
                    <input type="text" name="camera_stream_url" value="<?= $edit_data['camera_stream_url'] ?? '' ?>" placeholder="اختياري - HLS / WebRTC">
                </div>
                <div class="form-group">
                    <label>رقم اللوحة المرورية:</label>
                    <input type="text" name="plate_number" value="<?= $edit_data['plate_number'] ?? '' ?>">
                </div>
                <div class="form-group">
                    <label>رقم هاتف السائق:</label>
                    <input type="text" name="driver_phone" value="<?= $edit_data['driver_phone'] ?? '' ?>">
                </div>
                <div class="form-group">
                    <label>سعة الباص:</label>
                    <input type="number" name="capacity" value="<?= $edit_data['capacity'] ?? 30 ?>">
                </div>
            </div>
            
            <?php if($edit_data): ?>
                <div style="display:flex; gap:10px;">
                    <button type="submit" name="update_bus" class="btn-submit update-btn"><i class="fas fa-save"></i> تحديث بيانات الباص</button>
                    <a href="manage_transport.php" class="btn-submit" style="background:#64748b; text-align:center; text-decoration:none;">إلغاء التعديل</a>
                </div>
            <?php else: ?>
                <button type="submit" name="add_bus" class="btn-submit"><i class="fas fa-plus"></i> حفظ الباص</button>
            <?php endif; ?>
        </form>
    </div>

    <div class="card" style="border-top-color: #3b82f6;">
        <h3><i class="fas fa-user-graduate"></i> توزيع الطلاب على الباصات</h3>
        <form method="POST">
            <div class="form-grid">
                <div class="form-group">
                    <label>اختر الباص:</label>
                    <select name="bus_id" required style="border: 2px solid #f59e0b;">
                        <option value="">-- اختر الباص --</option>
                        <?php foreach($buses_array as $b): ?>
                            <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['bus_number']) ?> (السائق: <?= htmlspecialchars($b['driver_name']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="smart-filter-box">
                    <label style="color: #60a5fa; margin-bottom: 10px; display: block;"><i class="fas fa-filter"></i> الفلترة السريعة:</label>
                    <div class="smart-filter-grid">
                        <select id="filter_stage" onchange="applySmartFilters()"><option value="">كل المراحل</option></select>
                        <select id="filter_dept" onchange="applySmartFilters()"><option value="">كل الصفوف</option></select>
                        <select id="filter_section" onchange="applySmartFilters()"><option value="">كل الشعب</option></select>
                        <input type="text" id="search_name" class="search-input" placeholder="🔍 ابحث بالاسم..." onkeyup="applySmartFilters()">
                    </div>
                </div>

                <div class="form-group" style="grid-column: 1 / -1;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <label>حدد الطلاب لربطهم بالباص:</label>
                        <label style="color: #10b981; font-weight: bold; cursor: pointer;">
                            <input type="checkbox" id="selectAll" onclick="toggleSelectAll(this)"> تحديد جميع المعروضين
                        </label>
                    </div>
                    <div id="students_container" class="students-checkbox-list"></div>
                </div>

                <div class="form-group">
                    <label>نقطة التجمع (للمجموعة):</label>
                    <input type="text" name="pickup_address" required>
                </div>
                <div class="form-group">
                    <label>وقت الصعود (صباحاً):</label>
                    <input type="time" name="pickup_time" required>
                </div>
            </div>
            <button type="submit" name="assign_student" class="btn-submit" style="background: #3b82f6;"><i class="fas fa-users"></i> ربط الطلاب بالباص</button>
        </form>
    </div>

    <div class="card">
        <h3><i class="fas fa-clipboard-list"></i> أسطول الباصات والطلاب المرتبطين</h3>
        <table>
            <thead>
                <tr>
                    <th>الباص والمشرف</th>
                    <th>التتبع والكاميرا</th>
                    <th>عدد الطلاب</th>
                    <th>إجراءات الإدارة</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($buses_array)): ?>
                    <?php foreach($buses_array as $row): 
                        $b_id = $row['id'];
                        $std_count = count($students_by_bus[$b_id]);
                        
                        // روابط التتبع الحقيقية 🚀
                        $traccar_val = trim($row['traccar_device_id']);
                        $gps_url = "";
                        if(!empty($traccar_val)) {
                            // إذا كان رابط كامل يعمل مباشرة، وإلا يحوله لصيغة سيرفر Traccar الخاص بك
                            if(strpos($traccar_val, 'http') === 0) {
                                $gps_url = htmlspecialchars($traccar_val);
                            } else {
                                // يمكنك استبدال YOUR_VPS_IP برقم الأي بي الخاص بسيرفرك لاحقاً
                                $gps_url = "http://YOUR_VPS_IP:8082/?deviceId=" . htmlspecialchars($traccar_val); 
                            }
                        }
                        
                        $gps_badge = !empty($gps_url) ? "<div class='badge' style='background:#10b981;' onclick=\"openMediaModal('gps', '{$gps_url}')\"><i class='fas fa-map-marker-alt'></i> خريطة</div>" : "";
                        $cam_badge = !empty($row['camera_stream_url']) ? "<div class='badge' style='background:#3b82f6;' onclick=\"openMediaModal('camera', '{$row['camera_stream_url']}')\"><i class='fas fa-video'></i> كاميرا</div>" : "";
                    ?>
                    <tr>
                        <td><strong style='color:#f59e0b;'><?= htmlspecialchars($row['bus_number']) ?></strong><br><small><?= htmlspecialchars($row['supervisor_name']) ?></small></td>
                        <td><?= $gps_badge ?> <?= $cam_badge ?></td>
                        <td>
                            <strong style="font-size: 18px; color: #10b981;"><?= $std_count ?></strong> طالب<br>
                            <button onclick="openStudentsModal(<?= $b_id ?>)" style="background:#475569; color:white; border:none; padding:5px 10px; border-radius:5px; cursor:pointer; margin-top:5px; font-size:11px;">عرض الطلاب</button>

<button onclick="quickAddStudent(<?= $b_id ?>)" style="background:#10b981; color:white; border:none; padding:5px 10px; border-radius:5px; cursor:pointer; margin-top:5px; font-size:11px; margin-right:5px;"><i class="fas fa-plus"></i> إضافة طلاب</button>
</td>
                        <td>
                            <a href="?edit_id=<?= $b_id ?>#busFormSection" class="action-btn edit" title="تعديل الباص"><i class="fas fa-edit"></i> تعديل</a> | 
                            <a href="?delete_bus=<?= $b_id ?>" class="action-btn" onclick="return confirm('حذف الباص سيحذف الطلاب المرتبطين به أيضاً، هل أنت متأكد؟')" title="حذف"><i class="fas fa-trash"></i> حذف</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan='4' style='color:#64748b; padding:30px;'>لم يتم إضافة باصات بعد.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div id="mediaModal" class="modal-overlay">
        <div class="modal-box" style="max-width: 900px;">
            <span class="modal-close" onclick="closeMediaModal()">×</span>
            <h3 id="mediaModalTitle" style="color:white; margin-top:0;">نافذة العرض</h3>
            <div id="mediaModalContent" style="width:100%; height:500px; background:#000; border-radius:8px; display:flex; justify-content:center; align-items:center;"></div>
        </div>
    </div>

    <div id="studentsModal" class="modal-overlay">
        <div class="modal-box">
            <span class="modal-close" onclick="closeStudentsModal()">×</span>
            <h3 style="color:white; margin-top:0; border-bottom:1px solid #475569; padding-bottom:10px;"><i class="fas fa-users"></i> قائمة طلاب الباص</h3>
            <div id="studentsModalContent"></div>
        </div>
    </div>

    <script>
        function openMediaModal(type, url) {
            const modal = document.getElementById('mediaModal');
            const content = document.getElementById('mediaModalContent');
            const title = document.getElementById('mediaModalTitle');
            
            modal.style.display = 'flex';
            if(type === 'gps') {
                title.innerHTML = '<i class="fas fa-map-marker-alt"></i> تتبع مسار الباص';
                content.innerHTML = `<iframe src="${url}" style="width:100%; height:100%; border:none;"></iframe>`;
            } else {
                title.innerHTML = '<i class="fas fa-video"></i> بث الكاميرا المباشر';
                content.innerHTML = `<iframe src="${url}" style="width:100%; height:100%; border:none;" allowfullscreen></iframe>`;
            }
        }
        function closeMediaModal() {
            document.getElementById('mediaModal').style.display = 'none';
            document.getElementById('mediaModalContent').innerHTML = '';
        }

        const allStudentsInBuses = <?php echo json_encode($students_by_bus, JSON_UNESCAPED_UNICODE); ?>;
        
        function openStudentsModal(busId) {
            const modal = document.getElementById('studentsModal');
            const content = document.getElementById('studentsModalContent');
            const studentsList = allStudentsInBuses[busId] || [];
            
            let html = '<table style="width:100%; text-align:right;">';
            html += '<tr style="border-bottom:1px solid #475569;"><th>الاسم والصف</th><th>نقطة التجمع</th><th>إجراء</th></tr>';
            
            if(studentsList.length === 0) {
                html += '<tr><td colspan="3" style="text-align:center; padding:20px; color:#94a3b8;">لا يوجد طلاب في هذا الباص</td></tr>';
            } else {
                studentsList.forEach(st => {
                    html += `<tr>
                        <td style="padding:10px 0;"><strong>${st.student_name}</strong><br><small style="color:#94a3b8;">${st.class_info}</small></td>
                        <td>${st.pickup_address}<br><small style="color:#3b82f6;">${st.pickup_time}</small></td>
                        <td><a href="?remove_student=${st.id}" class="action-btn" onclick="return confirm('إزالة الطالب؟')" style="font-size:12px; border:1px solid #ef4444; padding:3px 8px; border-radius:4px;"><i class="fas fa-trash"></i> إزالة</a></td>
                    </tr>`;
                });
            }
            html += '</table>';
            
            content.innerHTML = html;
            modal.style.display = 'flex';
        }
        function closeStudentsModal() {
            document.getElementById('studentsModal').style.display = 'none';
        }

        const tagsData = <?php echo json_encode($tags_list, JSON_UNESCAPED_UNICODE); ?>;
        const studentsData = <?php echo json_encode($students_list, JSON_UNESCAPED_UNICODE); ?>;
        
        function initSmartFilters() {
            let stages = new Set(), depts = new Set(), sections = new Set();
            tagsData.forEach(t => {
                if(t.stage_name) stages.add(t.stage_name.trim());
                if(t.department_name) depts.add(t.department_name.trim());
                if(t.section_name) sections.add(t.section_name.trim());
            });

            const stSel = document.getElementById('filter_stage'); stages.forEach(s => stSel.innerHTML += `<option value="${s}">${s}</option>`);
            stSel.innerHTML += `<option value="unassigned" style="color:red;">⚠️ طلاب بدون مرحلة</option>`;
            
            const dpSel = document.getElementById('filter_dept'); depts.forEach(d => dpSel.innerHTML += `<option value="${d}">${d}</option>`);
            dpSel.innerHTML += `<option value="unassigned" style="color:red;">⚠️ طلاب بدون صف</option>`;
            
            const scSel = document.getElementById('filter_section'); sections.forEach(s => scSel.innerHTML += `<option value="${s}">${s}</option>`);
            scSel.innerHTML += `<option value="unassigned" style="color:red;">⚠️ طلاب بدون شعبة</option>`;

            applySmartFilters(); 
        }

        function applySmartFilters() {
            const stVal = document.getElementById('filter_stage').value;
            const dpVal = document.getElementById('filter_dept').value;
            const scVal = document.getElementById('filter_section').value;
            const srchVal = document.getElementById('search_name').value.trim().toLowerCase();
            const container = document.getElementById('students_container');
            container.innerHTML = '';
            document.getElementById('selectAll').checked = false; 

            let count = 0;
            studentsData.forEach(s => {
                let mSt = (stVal === "" || s.stage === stVal || (stVal === "unassigned" && s.stage === ""));
                let mDp = (dpVal === "" || s.dept === dpVal || (dpVal === "unassigned" && s.dept === ""));
                let mSc = (scVal === "" || s.section === scVal || (scVal === "unassigned" && s.section === ""));
                let mNm = (srchVal === "" || s.name.toLowerCase().includes(srchVal));

                if (mSt && mDp && mSc && mNm) {
                    let alert = (s.stage === "") ? '<i class="fas fa-exclamation-triangle" style="color:#ef4444;" title="غير مسجل بصف"></i>' : '';
                    container.innerHTML += `
                        <label class="student-item">
                            <input type="checkbox" name="student_data[]" value="${s.name}|${s.full_class}">
                            <span><strong>${s.name}</strong> ${alert} <small style="color:#94a3b8;">(${s.full_class})</small></span>
                        </label>`;
                    count++;
                }
            });
            if(count === 0) container.innerHTML = '<div style="padding: 20px; color: #ef4444; text-align: center;">❌ لا يوجد طلاب يطابقون خيارات البحث</div>';
        }
        function toggleSelectAll(source) { document.querySelectorAll('#students_container input[type="checkbox"]').forEach(cb => cb.checked = source.checked); }
        window.onload = initSmartFilters;
        
        // 🚀 دالة الإضافة السريعة
function quickAddStudent(busId) {
    // تحديد الباص تلقائياً في القائمة المنسدلة
    const busSelect = document.querySelector('select[name="bus_id"]');
    busSelect.value = busId;
    
    // الصعود بالصفحة إلى قسم التوزيع بسلاسة
    busSelect.scrollIntoView({ behavior: 'smooth', block: 'center' });
    
    // وميض أزرق لتنبيه المستخدم
    busSelect.style.transition = "box-shadow 0.3s";
    busSelect.style.boxShadow = "0 0 15px #3b82f6";
    setTimeout(() => { busSelect.style.boxShadow = "none"; }, 2000);
}

    </script>
</body>
</html>