<?php
// subject_enrollment.php - Enroll subjects for students
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// CSRF Protection
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$committeeId = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

// Sanitization function
function sanitizeInput($input, $type = 'string') {
    if ($type === 'student_id') {
        return preg_replace('/[^a-zA-Z0-9\-_]/', '', $input);
    } elseif ($type === 'subjectcode') {
        return preg_replace('/[^a-zA-Z0-9]/', '', $input);
    } elseif ($type === 'int') {
        return (int)$input;
    }
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Initialize variables
$errors = [];
$success_message = '';
$action = isset($_GET['action']) ? sanitizeInput($_GET['action']) : '';
$student_id_to_cancel = isset($_GET['student_id']) ? sanitizeInput($_GET['student_id'], 'student_id') : '';
$subjectcode_to_cancel = isset($_GET['subjectcode']) ? sanitizeInput($_GET['subjectcode'], 'subjectcode') : '';

// Handle cancellation (hard delete)
if ($action === 'cancel' && $student_id_to_cancel && $subjectcode_to_cancel) {
    $semester_id = isset($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
    $batch_id = isset($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
    $subjecttype_id = isset($_GET['subjecttype_id']) ? (int)$_GET['subjecttype_id'] : 1;
    
    if ($semester_id && $batch_id && !empty($student_id_to_cancel) && !empty($subjectcode_to_cancel)) {
        if (!is_numeric($semester_id) || !is_numeric($batch_id) || $semester_id <= 0 || $batch_id <= 0) {
            $errors[] = "معرف الفصل أو الدفعة غير صالح";
        } else {
            $deleteStmt = $mysqli1->prepare("
                DELETE FROM studentsubjects 
                WHERE student_id = ? 
                AND subjectcode = ? 
                AND semester_id = ? 
                AND batch_id = ?
                AND subjecttype_id = ?
            ");
            $deleteStmt->bind_param('ssiii', $student_id_to_cancel, $subjectcode_to_cancel, $semester_id, $batch_id, $subjecttype_id);
            
            if ($deleteStmt->execute()) {
                $success_message = "تم إلغاء تسجيل المادة بنجاح";
            } else {
                $errors[] = "حدث خطأ أثناء إلغاء التسجيل";
            }
            $deleteStmt->close();
        }
        
        $cleanGet = $_GET;
        unset($cleanGet['action']);
        unset($cleanGet['student_id']);
        unset($cleanGet['subjectcode']);
        
        header("Location: subject_enrollment.php?" . http_build_query($cleanGet));
        exit();
    } else {
        $errors[] = "بيانات غير صالحة لعملية الإلغاء";
    }
}

// Get filter data for dropdowns
$colleges = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$programs = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$all_sections = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$batches = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value")->fetch_all(MYSQLI_ASSOC);
$semesters = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id")->fetch_all(MYSQLI_ASSOC);

// Get subject types from database (table name: subjecttypes)
$subjectTypes = $mysqli1->query("SELECT id, name FROM subjecttypes WHERE deleted_at IS NULL ORDER BY id")->fetch_all(MYSQLI_ASSOC);

// If no subject types found, use defaults
if (empty($subjectTypes)) {
    $subjectTypes = [
        ['id' => 1, 'name' => 'عادي'],
        ['id' => 2, 'name' => 'إزالة رسوب'],
        ['id' => 3, 'name' => 'لم يؤخذ'],
        ['id' => 4, 'name' => 'ترفيع'],
        ['id' => 5, 'name' => 'فروقات منهج'],
        ['id' => 6, 'name' => 'تعليق دراسة']
    ];
}

// If committee has restricted access, filter colleges
if (!$canAll && $scopeCollege !== null) {
    $colleges = array_filter($colleges, function($college) use ($scopeCollege) {
        return $college['id'] == $scopeCollege;
    });
}

// Handle form submission for filtering - with validation
$college_id = isset($_GET['college_id']) && ctype_digit($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$section_id = isset($_GET['section_id']) && ctype_digit($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
$program_id = isset($_GET['program_id']) && ctype_digit($_GET['program_id']) ? (int)$_GET['program_id'] : 0;
$specialization_id = isset($_GET['specialization_id']) && ctype_digit($_GET['specialization_id']) ? (int)$_GET['specialization_id'] : 0;
$batch_id = isset($_GET['batch_id']) && ctype_digit($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
$semester_id = isset($_GET['semester_id']) && ctype_digit($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
$subject_source = isset($_GET['subject_source']) && in_array($_GET['subject_source'], ['plan', 'all']) ? $_GET['subject_source'] : 'plan';

// Handle enrollment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enroll_students'])) {
    // CSRF Protection
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $errors[] = "طلب غير مصرح به. يرجى تحديث الصفحة والمحاولة مرة أخرى.";
    } else {
        $semester_id = (int)$_POST['semester_id'];
        $batch_id = (int)$_POST['batch_id'];
        $subject_ids = isset($_POST['subject_ids']) ? array_map('intval', $_POST['subject_ids']) : [];
        $subjecttype_id = isset($_POST['subjecttype_id']) ? (int)$_POST['subjecttype_id'] : 1;
        
        if (empty($semester_id)) {
            $errors[] = 'الرجاء اختيار الفصل الدراسي';
        }
        
        if (empty($batch_id)) {
            $errors[] = 'الرجاء اختيار الدفعة';
        }
        
        if (empty($subject_ids)) {
            $errors[] = 'الرجاء اختيار مادة واحدة على الأقل';
        }
        
        if ($subjecttype_id <= 0) {
            $errors[] = 'نوع التسجيل غير صالح';
        }
        
        $student_ids = isset($_POST['student_ids']) ? array_map('sanitizeInput', $_POST['student_ids']) : [];
        if (empty($student_ids)) {
            $errors[] = 'الرجاء اختيار طالب واحد على الأقل';
        }
        
        if (empty($errors)) {
            $success_count = 0;
            $update_count = 0;
            $error_count = 0;
            $duplicate_count = 0;
            
            $mysqli1->begin_transaction();
            
            try {
                foreach ($student_ids as $student_id) {
                    foreach ($subject_ids as $subject_id) {
                        $subjectStmt = $mysqli1->prepare("SELECT subjectcode FROM subjects WHERE id = ?");
                        $subjectStmt->bind_param('i', $subject_id);
                        $subjectStmt->execute();
                        $subjectResult = $subjectStmt->get_result()->fetch_assoc();
                        $subjectcode = $subjectResult['subjectcode'] ?? '';
                        $subjectStmt->close();
                        
                        if (!$subjectcode) {
                            $error_count++;
                            continue;
                        }
                        
                        // Check if already enrolled with the same subject type
                        $checkStmt = $mysqli1->prepare("
                            SELECT id, subjecttype_id FROM studentsubjects 
                            WHERE student_id = ? 
                            AND subjectcode = ? 
                            AND semester_id = ? 
                            AND batch_id = ?
                            AND subjecttype_id = ?
                        ");
                        $checkStmt->bind_param('ssiii', $student_id, $subjectcode, $semester_id, $batch_id, $subjecttype_id);
                        $checkStmt->execute();
                        $exists = $checkStmt->get_result()->fetch_assoc();
                        $checkStmt->close();
                        
                        if (!$exists) {
                            // Check if exists with different subject type
                            $checkDiffStmt = $mysqli1->prepare("
                                SELECT id, subjecttype_id FROM studentsubjects 
                                WHERE student_id = ? 
                                AND subjectcode = ? 
                                AND semester_id = ? 
                                AND batch_id = ?
                            ");
                            $checkDiffStmt->bind_param('ssii', $student_id, $subjectcode, $semester_id, $batch_id);
                            $checkDiffStmt->execute();
                            $existingDiff = $checkDiffStmt->get_result()->fetch_assoc();
                            $checkDiffStmt->close();
                            
                            if ($existingDiff) {
                                $duplicate_count++;
                                continue;
                            }
                            
                            // Insert new enrollment
                            $insertStmt = $mysqli1->prepare("
                                INSERT INTO studentsubjects 
                                (subjectcode, student_id, semester_id, batch_id, subjecttype_id, weight, created_at, updated_at) 
                                VALUES (?, ?, ?, ?, ?, 100.00, NOW(), NOW())
                            ");
                            $insertStmt->bind_param('ssiii', $subjectcode, $student_id, $semester_id, $batch_id, $subjecttype_id);
                            
                            if ($insertStmt->execute()) {
                                $success_count++;
                            } else {
                                $error_count++;
                            }
                            $insertStmt->close();
                        } else {
                            // Update existing enrollment
                            $updateStmt = $mysqli1->prepare("
                                UPDATE studentsubjects 
                                SET weight = 100.00, updated_at = NOW()
                                WHERE student_id = ? 
                                AND subjectcode = ? 
                                AND semester_id = ? 
                                AND batch_id = ?
                                AND subjecttype_id = ?
                            ");
                            $updateStmt->bind_param('ssiii', $student_id, $subjectcode, $semester_id, $batch_id, $subjecttype_id);
                            
                            if ($updateStmt->execute()) {
                                $update_count++;
                            } else {
                                $error_count++;
                            }
                            $updateStmt->close();
                        }
                    }
                }
                
                $mysqli1->commit();
                
                if ($success_count > 0 || $update_count > 0) {
                    $success_message = "تم تسجيل المقررات بنجاح";
                    if ($success_count > 0) {
                        $success_message .= " ($success_count تسجيل جديد)";
                    }
                    if ($update_count > 0) {
                        $success_message .= " ($update_count تحديث)";
                    }
                    if ($duplicate_count > 0) {
                        $success_message .= " (تم تخطي $duplicate_count مادة مكررة)";
                    }
                    if ($error_count > 0) {
                        $success_message .= " (فشل في $error_count حالة)";
                    }
                } else {
                    $errors[] = "لم يتم تنفيذ أي عملية";
                }
                
            } catch (Exception $e) {
                $mysqli1->rollback();
                $errors[] = "حدث خطأ أثناء الحفظ: " . $e->getMessage();
            }
        }
    }
}

// Get filtered students based on selection
$students = [];
$subjects = [];
$selected_subjects = [];
$enrolled_details = [];
$plan_info = null;
$program_name = '';
$section_name = '';
$college_name = '';

if ($college_id && $section_id && $program_id && $batch_id) {
    // Get names safely
    $nameStmt = $mysqli1->prepare("SELECT name FROM colleges WHERE id = ? AND deleted_at IS NULL");
    $nameStmt->bind_param('i', $college_id);
    $nameStmt->execute();
    $college_name = $nameStmt->get_result()->fetch_assoc()['name'] ?? '';
    $nameStmt->close();
    
    $nameStmt = $mysqli1->prepare("SELECT name FROM sections WHERE id = ? AND deleted_at IS NULL");
    $nameStmt->bind_param('i', $section_id);
    $nameStmt->execute();
    $section_name = $nameStmt->get_result()->fetch_assoc()['name'] ?? '';
    $nameStmt->close();
    
    $nameStmt = $mysqli1->prepare("SELECT name FROM programs WHERE id = ? AND deleted_at IS NULL");
    $nameStmt->bind_param('i', $program_id);
    $nameStmt->execute();
    $program_name = $nameStmt->get_result()->fetch_assoc()['name'] ?? '';
    $nameStmt->close();
    
    // Get students
    $studentQuery = "
        SELECT s.student_id, s.student_name
        FROM students s
        WHERE s.college_id = ? 
        AND s.section_id = ? 
        AND s.program_id = ? 
        AND s.batch_id = ?
        AND s.deleted_at IS NULL
    ";
    
    $types = "iiii";
    $params = [$college_id, $section_id, $program_id, $batch_id];
    
    if ($specialization_id > 0) {
        $studentQuery .= " AND s.specialization_id = ?";
        $types .= "i";
        $params[] = $specialization_id;
    }
    
    $studentQuery .= " ORDER BY s.student_name";
    
    $studentStmt = $mysqli1->prepare($studentQuery);
    $studentStmt->bind_param($types, ...$params);
    $studentStmt->execute();
    $students = $studentStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $studentStmt->close();
    
    // Find academic plan
    $planStmt = $mysqli1->prepare("
        SELECT ap.*, apb.start_date, apb.end_date, apb.is_current
        FROM academic_plans ap
        JOIN academic_plan_batches apb ON ap.id = apb.plan_id
        WHERE ap.program_id = ? 
        AND ap.college_id = ? 
        AND ap.section_id = ?
        AND apb.batch_id = ?
        AND ap.deleted_at IS NULL
        AND ap.is_active = 1
        LIMIT 1
    ");
    $planStmt->bind_param('iiii', $program_id, $college_id, $section_id, $batch_id);
    $planStmt->execute();
    $plan_info = $planStmt->get_result()->fetch_assoc();
    $planStmt->close();
    
    if ($subject_source === 'plan' && !$plan_info) {
        $errors[] = "لا توجد خطة دراسية نشطة مرتبطة بهذه الدفعة";
        $subjects = [];
    }
    
    // Get subjects based on source
    if ($subject_source === 'plan' && $plan_info && $semester_id) {
        $subjectQuery = "
            SELECT s.id, s.subjectcode, s.subjectnamea, s.subjectnamee, s.credit_hours,
                   aps.is_core, aps.semester_id, aps_sem.semester_number
            FROM academic_plan_subjects aps
            JOIN subjects s ON aps.subject_id = s.id
            JOIN academic_plan_semesters aps_sem ON aps.semester_id = aps_sem.id
            WHERE aps.plan_id = ? 
            AND aps_sem.semester_number = ?
            AND s.is_active = 1
            AND s.deleted_at IS NULL
            ORDER BY aps.is_core DESC, s.subjectcode
        ";
        $subjectStmt = $mysqli1->prepare($subjectQuery);
        $subjectStmt->bind_param('ii', $plan_info['id'], $semester_id);
    } else if ($subject_source === 'all') {
        $subjectQuery = "
            SELECT s.id, s.subjectcode, s.subjectnamea, s.subjectnamee, s.credit_hours
            FROM subjects s
            WHERE s.program_id = ? 
            AND s.college_id = ? 
            AND s.section_id = ?
            AND s.is_active = 1
            AND s.deleted_at IS NULL
        ";
        
        $types = "iii";
        $params = [$program_id, $college_id, $section_id];
        
        if ($specialization_id > 0) {
            $subjectQuery .= " AND (s.specialization_id = ? OR s.specialization_id = 0 OR s.specialization_id IS NULL)";
            $types .= "i";
            $params[] = $specialization_id;
        }
        
        $subjectQuery .= " ORDER BY s.subjectcode";
        
        $subjectStmt = $mysqli1->prepare($subjectQuery);
        $subjectStmt->bind_param($types, ...$params);
    }
    
    if (isset($subjectStmt)) {
        $subjectStmt->execute();
        $subjects = $subjectStmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $subjectStmt->close();
    }
    
    // Get enrolled subjects with subject type info
// Get enrolled subjects with subject type info - FIXED for duplicates
if ($semester_id) {
    $enrolledQuery = "
        SELECT DISTINCT 
            ss.student_id, 
            ss.subjectcode, 
            ss.id as enrollment_id, 
            ss.subjecttype_id,
            s.student_name, 
            sub.subjectnamea, 
            st.name as subjecttype_name
        FROM studentsubjects ss
        INNER JOIN students s ON ss.student_id = s.student_id
        INNER JOIN subjects sub ON ss.subjectcode = sub.subjectcode
        LEFT JOIN subjecttypes st ON ss.subjecttype_id = st.id
        WHERE ss.batch_id = ? 
        AND ss.semester_id = ?
        AND ss.deleted_at IS NULL
        GROUP BY ss.student_id, ss.subjectcode, ss.subjecttype_id
        ORDER BY s.student_name, ss.subjectcode
    ";
    $enrolledStmt = $mysqli1->prepare($enrolledQuery);
    $enrolledStmt->bind_param('ii', $batch_id, $semester_id);
    $enrolledStmt->execute();
    $enrolled_details = $enrolledStmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $enrolledStmt->close();
    
    $selected_subjects = [];
    foreach ($enrolled_details as $enrolled) {
        $key = $enrolled['subjectcode'] . '_' . $enrolled['subjecttype_id'];
        $selected_subjects[$key] = true;
    }
}
}

// Get selected specialization name
$selected_specialization_name = '';
if ($specialization_id > 0) {
    $specStmt = $mysqli1->prepare("SELECT specialization_name_ar FROM specializations WHERE specialization_id = ?");
    $specStmt->bind_param('i', $specialization_id);
    $specStmt->execute();
    $specResult = $specStmt->get_result();
    if ($specRow = $specResult->fetch_assoc()) {
        $selected_specialization_name = $specRow['specialization_name_ar'];
    }
    $specStmt->close();
}

include 'header.php';
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل المقررات للطلاب</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            text-align: right;
            direction: rtl;
        }
        
        body {
            font-family: 'Cairo', sans-serif;
            background-color: #f8fafc;
            min-height: 100vh;
        }

        .main-wrapper {
            padding: 30px 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border-radius: 30px;
            padding: 30px 40px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            position: relative;
            overflow: hidden;
            color: white;
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: rotate 20s linear infinite;
        }

        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .page-header h1 {
            font-size: 2.2rem;
            font-weight: 800;
            margin: 0;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
            position: relative;
            z-index: 2;
            text-align: right;
        }

        .page-header p {
            font-size: 1rem;
            margin-top: 5px;
            opacity: 0.9;
            position: relative;
            z-index: 2;
            text-align: right;
        }

        .btn-gradient {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 176, 155, 0.4);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-gradient:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6);
            color: white;
        }

        .btn-outline-gradient {
            background: transparent;
            border: 2px solid rgba(255, 255, 255, 0.5);
            color: white;
            padding: 10px 25px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-outline-gradient:hover {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            transform: translateY(-2px);
        }

        .btn-reset {
            background: linear-gradient(135deg, #6b7280, #4b5563);
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .filter-card {
            background: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
        }

        .form-label {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
            font-size: 0.95rem;
            text-align: right;
        }

        .required-field::after {
            content: " *";
            color: #e53e3e;
        }

        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 10px 15px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            text-align: right;
        }

        .content-card {
            background: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            border-right: 5px solid #667eea;
        }

        .content-card-header {
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 15px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }

        .content-card-header h5 {
            font-weight: 700;
            color: #2d3748;
            margin: 0;
            text-align: right;
        }

        .content-card-header h5 i {
            color: #667eea;
            margin-left: 10px;
        }

        .scrollable-area {
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
            background: #f8fafc;
            border-radius: 20px;
        }

        .student-item, .subject-item {
            background: white;
            border-radius: 15px;
            padding: 12px 15px;
            margin-bottom: 8px;
            border: 2px solid transparent;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            text-align: right;
        }

        .student-item.selected, .subject-item.selected {
            background: #e3f2fd;
            border-color: #2196f3;
        }

        .student-item.enrolled, .subject-item.enrolled {
            background: #d4edda;
            border-color: #28a745;
        }

        .badge-credit {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .badge-core {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e4620;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .badge-enrolled {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 600;
        }

        .plan-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
            text-align: right;
        }

        .source-toggle {
            background: #f8fafc;
            border-radius: 15px;
            padding: 15px;
            margin-top: 15px;
            border: 1px solid #e2e8f0;
        }

        .btn-toggle {
            background: white;
            border: 2px solid #e2e8f0;
            color: #4a5568;
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-toggle.active {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border-color: transparent;
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.3);
        }

        .btn-cancel {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 4px 12px;
            font-size: 0.8rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .stat-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 25px;
            padding: 25px 20px;
            text-align: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            height: 100%;
        }

        .alert {
            border-radius: 20px;
            border: none;
            padding: 20px 30px;
            font-weight: 600;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.5s ease;
            margin-bottom: 25px;
            text-align: right;
        }

        @keyframes slideIn {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .alert-success {
            background: linear-gradient(135deg, #84fab0, #8fd3f4);
            color: #1e4620;
        }

        .alert-danger {
            background: linear-gradient(135deg, #fc6767, #ec008c);
            color: white;
        }

        .active-filters {
            background: #f8fafc;
            border-radius: 15px;
            padding: 15px;
            margin-top: 15px;
            border: 1px solid #e2e8f0;
        }

        .filter-badge {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 5px 12px;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .enrolled-table {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .enrolled-table th,
        .enrolled-table td {
            text-align: right;
        }

        .me-1 { margin-left: 0.25rem !important; margin-right: 0 !important; }
        .me-2 { margin-left: 0.5rem !important; margin-right: 0 !important; }
        .me-3 { margin-left: 1rem !important; margin-right: 0 !important; }
        .ms-1 { margin-right: 0.25rem !important; margin-left: 0 !important; }
        .ms-2 { margin-right: 0.5rem !important; margin-left: 0 !important; }
        .ms-3 { margin-right: 1rem !important; margin-left: 0 !important; }

        @media (max-width: 768px) {
            .page-header {
                padding: 20px;
            }
            .page-header h1 {
                font-size: 1.8rem;
            }
            .content-card-header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
        
        .text-start {
            text-align: left !important;
        }
        
        .text-end {
            text-align: right !important;
        }
        
        ul {
            padding-right: 20px;
        }
        
        .list-group-item {
            text-align: right;
        }
        
        .subject-type-select {
            max-width: 250px;
        }
        
        .type-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .type-1 { background: linear-gradient(135deg, #28a745, #20c997); color: white; }
        .type-2 { background: linear-gradient(135deg, #dc3545, #c82333); color: white; }
        .type-3 { background: linear-gradient(135deg, #ffc107, #e0a800); color: #1e4620; }
        .type-4 { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .type-5 { background: linear-gradient(135deg, #6f42c1, #5a32a3); color: white; }
        .type-6 { background: linear-gradient(135deg, #fd7e14, #e36209); color: white; }




        <style>
/* تحسين عرض التنبيهات المنبثقة */
@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* تحسين مربع البحث */
#studentSearch, #subjectSearch {
    border-radius: 25px;
    padding: 8px 15px;
    font-size: 0.85rem;
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
}

#studentSearch:focus, #subjectSearch:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    outline: none;
}

/* تحسين العناصر المخفية */
.student-item[style*="display: none"], 
.subject-item[style*="display: none"] {
    display: none !important;
}

/* تأثيرات إضافية */
.btn-cancel {
    transition: all 0.3s ease;
}

.btn-cancel:hover {
    transform: scale(1.05);
}

/* تنسيق شريط التمرير */
.scrollable-area::-webkit-scrollbar {
    width: 6px;
}

.scrollable-area::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.scrollable-area::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-radius: 10px;
}

.scrollable-area::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #5a67d8, #6b46a0);
}

/* تحسين عرض الأكواد */
code {
    direction: ltr;
    display: inline-block;
}

/* تنسيق رسائل التأكيد في الـ confirm */
@media (max-width: 768px) {
    .alert {
        position: fixed;
        top: 10px;
        right: 10px;
        left: 10px;
        z-index: 9999;
    }
}
</style>
    </style>
</head>
<body>
<div class="main-wrapper">
    <div class="container-fluid px-4">
        <!-- Page Header -->
        <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
            <div>
                <h1 class="mb-2">
                    <i class="fas fa-user-graduate ms-3"></i>
                    تسجيل المقررات للطلاب
                </h1>
                <p class="mb-0">
                    <i class="fas fa-layer-group ms-2"></i>
                    تسجيل المقررات الدراسية للطلاب حسب الخطة الدراسية المرتبطة بالدفعة
                </p>
            </div>
            <div class="d-flex gap-3 mt-3 mt-md-0">
                <a href="admin_dashboard.php" class="btn-outline-gradient">
                    <i class="fas fa-arrow-right ms-2"></i>
                    العودة للوحة التحكم
                </a>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle ms-2"></i>
                <?php foreach ($errors as $error): ?>
                    <div><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
                <?php endforeach; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle ms-2"></i>
                <?= htmlspecialchars($success_message, ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Filter Card -->
        <div class="filter-card">
            <form method="get" class="row g-4" id="filterForm">
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-university ms-1"></i>
                        الكلية
                    </label>
                    <select class="form-select" name="college_id" id="college_id" required
                            <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                        <option value="">اختر الكلية</option>
                        <?php foreach ($colleges as $college): ?>
                            <option value="<?= (int)$college['id'] ?>" 
                                <?= ($college_id == $college['id']) || (!$canAll && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$canAll && $scopeCollege !== null): ?>
                        <input type="hidden" name="college_id" value="<?= (int)$scopeCollege ?>">
                    <?php endif; ?>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-layer-group ms-1"></i>
                        القسم
                    </label>
                    <select class="form-select" name="section_id" id="section_id" required>
                        <option value="">اختر القسم</option>
                    </select>
                    <small class="text-muted" id="sectionStatus"></small>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-graduation-cap ms-1"></i>
                        البرنامج
                    </label>
                    <select class="form-select" name="program_id" id="program_id" required>
                        <option value="">اختر البرنامج</option>
                    </select>
                    <small class="text-muted" id="programStatus"></small>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label">
                        <i class="fas fa-tag ms-1"></i>
                        التخصص
                    </label>
                    <select class="form-select" name="specialization_id" id="specialization_id">
                        <option value="">جميع التخصصات</option>
                    </select>
                    <small class="text-muted" id="specializationStatus"></small>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-users ms-1"></i>
                        الدفعة
                    </label>
                    <select class="form-select" name="batch_id" id="batch_id" required>
                        <option value="">اختر الدفعة</option>
                        <?php foreach ($batches as $batch): ?>
                            <option value="<?= (int)$batch['id'] ?>" 
                                <?= ($batch_id == $batch['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label required-field">
                        <i class="fas fa-calendar-alt ms-1"></i>
                        الفصل الدراسي
                    </label>
                    <select class="form-select" name="semester_id" id="semester_id" required>
                        <option value="">اختر الفصل</option>
                        <?php foreach ($semesters as $semester): ?>
                            <option value="<?= (int)$semester['id'] ?>" 
                                <?= ($semester_id == $semester['id']) ? 'selected' : '' ?>>
                                الفصل <?= htmlspecialchars($semester['name'], ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-12">
                    <div class="d-flex gap-3 justify-content-end">
                        <a href="subject_enrollment.php" class="btn-reset">
                            <i class="fas fa-redo-alt ms-2"></i>
                            إعادة تعيين الفلاتر
                        </a>
                        <button type="submit" class="btn-gradient">
                            <i class="fas fa-search ms-2"></i>
                            بحث
                        </button>
                    </div>
                </div>
            </form>
            
            <!-- Active Filters Display -->
            <?php if ($college_id || $section_id || $program_id || $specialization_id || $batch_id || $semester_id): ?>
                <div class="active-filters">
                    <div class="d-flex align-items-center flex-wrap gap-2">
                        <span class="fw-bold text-secondary ms-2">
                            <i class="fas fa-filter ms-1"></i>
                            الفلاتر النشطة:
                        </span>
                        <?php if ($college_id && $college_name): ?>
                            <span class="filter-badge">
                                <i class="fas fa-university"></i>
                                <?= htmlspecialchars($college_name) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($section_id && $section_name): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #28a745, #20c997);">
                                <i class="fas fa-layer-group"></i>
                                <?= htmlspecialchars($section_name) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($program_id && $program_name): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #ff6b6b, #ee5253);">
                                <i class="fas fa-graduation-cap"></i>
                                <?= htmlspecialchars($program_name) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($specialization_id && $selected_specialization_name): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #f39c12, #e67e22);">
                                <i class="fas fa-tag"></i>
                                <?= htmlspecialchars($selected_specialization_name) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($batch_id): 
                            $batchValue = '';
                            foreach($batches as $b) {
                                if($b['id'] == $batch_id) {
                                    $batchValue = $b['value'];
                                    break;
                                }
                            }
                        ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #9b59b6, #8e44ad);">
                                <i class="fas fa-users"></i>
                                دفعة <?= htmlspecialchars($batchValue) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($semester_id): 
                            $semesterName = '';
                            foreach($semesters as $s) {
                                if($s['id'] == $semester_id) {
                                    $semesterName = $s['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #2596be, #2596be);">
                                <i class="fas fa-calendar-alt"></i>
                                الفصل <?= htmlspecialchars($semesterName) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($subject_source === 'plan'): ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #1abc9c, #16a085);">
                                <i class="fas fa-layer-group"></i>
                                مواد الخطة
                            </span>
                        <?php else: ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #34495e, #2c3e50);">
                                <i class="fas fa-list"></i>
                                جميع المقررات
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
            
            <?php if ($college_id && $section_id && $program_id && $batch_id && $semester_id): ?>
                <!-- Subject Source Toggle -->
                <div class="source-toggle mt-4">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <div class="d-flex gap-3 flex-wrap">
                                <a href="?<?= http_build_query(array_merge($_GET, ['subject_source' => 'plan'])) ?>" 
                                   class="btn-toggle <?= $subject_source === 'plan' ? 'active' : '' ?>">
                                    <i class="fas fa-layer-group"></i>
                                    مواد الخطة الدراسية
                                </a>
                                <a href="?<?= http_build_query(array_merge($_GET, ['subject_source' => 'all'])) ?>" 
                                   class="btn-toggle <?= $subject_source === 'all' ? 'active' : '' ?>">
                                    <i class="fas fa-list"></i>
                                    جميع مواد البرنامج
                                </a>
                            </div>
                        </div>
                        <div class="col-md-6 text-start">
                            <?php if ($subject_source === 'plan' && $plan_info): ?>
                                <span class="badge" style="background: linear-gradient(135deg, #28a745, #20c997); color: white; padding: 8px 15px; border-radius: 50px;">
                                    <i class="fas fa-check-circle me-1"></i>
                                    الخطة: <?= htmlspecialchars($plan_info['plan_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($specialization_id > 0 && $selected_specialization_name): ?>
                                <span class="badge ms-2" style="background: linear-gradient(135deg, #6610f2, #6f42c1); color: white; padding: 8px 15px; border-radius: 50px;">
                                    <i class="fas fa-tag me-1"></i>
                                    التخصص: <?= htmlspecialchars($selected_specialization_name, ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($college_id && $section_id && $program_id && $batch_id && $semester_id): ?>
            
            <!-- Plan Info -->
            <?php if ($plan_info && $subject_source === 'plan'): ?>
                <div class="plan-info-card">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                        <div>
                            <h5 class="fw-bold mb-2">
                                <i class="fas fa-layer-group me-2"></i>
                                <?= htmlspecialchars($plan_info['plan_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                            </h5>
                            <p class="mb-0 small opacity-75">
                                <i class="fas fa-hashtag me-1"></i> <?= htmlspecialchars($plan_info['plan_code'] ?? '', ENT_QUOTES, 'UTF-8') ?> •
                                <i class="fas fa-calendar me-1 ms-2"></i> 
                                من: <?= !empty($plan_info['start_date']) ? htmlspecialchars($plan_info['start_date'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?> 
                                إلى: <?= !empty($plan_info['end_date']) ? htmlspecialchars($plan_info['end_date'], ENT_QUOTES, 'UTF-8') : 'غير محدد' ?>
                                <?php if (!empty($plan_info['is_current'])): ?>
                                    <span class="badge bg-warning text-dark ms-2">الدفعة الحالية</span>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div>
                            <span class="badge bg-white text-dark p-3 rounded-pill">
                                <i class="fas fa-book me-1"></i>
                                مواد الفصل <?= (int)$semester_id ?>
                            </span>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Subject Type Selection -->
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="content-card" style="border-right-color: #f39c12;">
                        <div class="d-flex align-items-center gap-3">
                            <i class="fas fa-tag fa-2x" style="color: #f39c12;"></i>
                            <div class="flex-grow-1">
                                <label class="form-label fw-bold mb-1">
                                    <i class="fas fa-info-circle ms-1"></i>
                                    نوع التسجيل <span class="text-danger">*</span>
                                </label>
                                <select class="form-select subject-type-select" name="subjecttype_id" id="subjecttype_id" required>
                                    <option value="">اختر نوع التسجيل</option>
                                    <?php foreach ($subjectTypes as $type): ?>
                                        <option value="<?= (int)$type['id'] ?>">
                                            <?= htmlspecialchars($type['name'], ENT_QUOTES, 'UTF-8') ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="text-muted">يتم تسجيل المقررات بنوع التسجيل المحدد (عادي، إزالة رسوب، لم يؤخذ، ترفيع، فروقات منهج، تعليق دراسة)</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Enrollment Form -->
            <form method="POST" action="" id="enrollmentForm">
                <input type="hidden" name="semester_id" value="<?= (int)$semester_id ?>">
                <input type="hidden" name="batch_id" value="<?= (int)$batch_id ?>">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                
                <div class="row g-4">
                    <!-- LEFT SIDE: Students Column -->
                    <div class="col-lg-6">
                        <div class="content-card">
                            <div class="content-card-header">
                                <h5>
                                    <i class="fas fa-users"></i>
                                    الطلاب
                                </h5>
                                <div class="d-flex align-items-center gap-3 flex-wrap">
                                    <span class="badge" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 5px 15px; border-radius: 50px;" id="selectedStudentsCount">0</span>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-sm btn-outline-primary" id="selectAllStudents">
                                            الكل
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary" id="deselectAllStudents">
                                            لا شيء
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="scrollable-area">
                                <?php if (empty($students)): ?>
                                    <div class="text-center py-5">
                                        <i class="fas fa-user-slash fa-3x text-muted mb-3"></i>
                                        <p class="text-muted">لا توجد طلاب مطابقين للترشيح</p>
                                    </div>
                                <?php else: ?>
                                    <div class="mb-3">
                                        <div class="d-flex align-items-center p-2 bg-light rounded-3">
                                            <input class="form-check-input ms-3" type="checkbox" id="masterStudentCheckbox" style="transform: scale(1.2);">
                                            <label class="fw-bold" for="masterStudentCheckbox">تحديد/إلغاء الكل</label>
                                        </div>
                                    </div>
                                    <?php foreach ($students as $student): ?>
                                        <div class="student-item" id="student-item-<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>">
                                            <div class="d-flex align-items-start">
                                                <input class="form-check-input student-checkbox ms-3" 
                                                       type="checkbox" 
                                                       name="student_ids[]" 
                                                       value="<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>"
                                                       id="student_<?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>"
                                                       style="transform: scale(1.2); margin-top: 5px;">
                                                <div class="flex-grow-1">
                                                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                                                        <strong><?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?></strong>
                                                        <code class="bg-light p-1 rounded"><?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?></code>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- RIGHT SIDE: Subjects Column -->
                    <div class="col-lg-6">
                        <div class="content-card">
                            <div class="content-card-header">
                                <h5>
                                    <i class="fas fa-book"></i>
                                    <?= $subject_source === 'plan' ? 'مواد الخطة للفصل ' . (int)$semester_id : 'المقررات المتاحة' ?>
                                </h5>
                                <div class="d-flex align-items-center gap-3 flex-wrap">
                                    <span class="badge" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 5px 15px; border-radius: 50px;" id="selectedSubjectsCount">0</span>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="selectAllSubjects" style="transform: scale(1.2);">
                                        <label class="form-check-label fw-bold me-2" for="selectAllSubjects">
                                            اختيار الكل
                                        </label>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="scrollable-area">
                                <?php if (empty($subjects)): ?>
                                    <div class="text-center py-5">
                                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                                        <?php if ($subject_source === 'plan' && !$plan_info): ?>
                                            <p class="text-muted">⚠️ لا توجد خطة دراسية مرتبطة بهذه الدفعة</p>
                                            <div class="text-end mt-3">
                                                <small class="d-block text-danger mb-2">تأكد من:</small>
                                                <ul class="text-end">
                                                    <li>وجود خطة دراسية نشطة للبرنامج "<?= htmlspecialchars($program_name ?? '', ENT_QUOTES, 'UTF-8') ?>"</li>
                                                    <li>ربط الخطة بالدفعة المحددة</li>
                                                    <li>تطابق القسم والكلية مع الخطة</li>
                                                </ul>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-outline-primary mt-3" onclick="window.location.href='subject_enrollment.php?<?= http_build_query(array_merge($_GET, ['subject_source' => 'all'])) ?>'">
                                                <i class="fas fa-list"></i> عرض جميع مواد البرنامج بدلاً من ذلك
                                            </button>
                                        <?php elseif ($subject_source === 'plan' && $plan_info): ?>
                                            <p class="text-muted">لا توجد مواد متاحة للفصل الدراسي المحدد</p>
                                            <small class="d-block mt-2">قد لا توجد مواد مرتبطة بالفصل <?= (int)$semester_id ?> في هذه الخطة</small>
                                        <?php else: ?>
                                            <p class="text-muted">لا توجد مواد متاحة</p>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <?php foreach ($subjects as $subject): ?>
                                        <?php 
                                        $key = $subject['subjectcode'] . '_1';
                                        $isSelected = isset($selected_subjects[$key]);
                                        $isCore = isset($subject['is_core']) && $subject['is_core'];
                                        ?>
                                        <div class="subject-item <?= $isSelected ? 'enrolled' : '' ?> <?= ($subject_source === 'plan') ? 'plan-subject' : '' ?>" 
                                             data-subject-id="<?= (int)$subject['id'] ?>">
                                            <div class="d-flex align-items-start">
                                                <input class="form-check-input subject-checkbox ms-3" 
                                                       type="checkbox" 
                                                       name="subject_ids[]" 
                                                       value="<?= (int)$subject['id'] ?>"
                                                       id="subject_<?= (int)$subject['id'] ?>"
                                                       <?= $isSelected ? 'checked' : '' ?>
                                                       style="transform: scale(1.2); margin-top: 5px;">
                                                <div class="flex-grow-1">
                                                    <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
                                                        <div>
                                                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                                                <strong><?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?></strong>
                                                                <?php if ($isCore && $subject_source === 'plan'): ?>
                                                                    <span class="badge-core">أساسي</span>
                                                                <?php endif; ?>
                                                                <?php if ($isSelected): ?>
                                                                    <span class="badge-enrolled">
                                                                        <i class="fas fa-check-circle me-1"></i> مسجل
                                                                    </span>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div class="mt-1"><?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                                                            <?php if (!empty($subject['subjectnamee'])): ?>
                                                                <small class="text-muted"><?= htmlspecialchars($subject['subjectnamee'], ENT_QUOTES, 'UTF-8') ?></small>
                                                            <?php endif; ?>
                                                        </div>
                                                        <span class="badge-credit"><?= (int)($subject['credit_hours'] ?? 0) ?> ساعة</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Submit Button -->
                <?php if (!empty($students) && !empty($subjects)): ?>
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="content-card">
                                <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
                                    <div>
                                        <h6 class="mb-2 fw-bold">
                                            <i class="fas fa-info-circle text-primary me-2"></i>
                                            ملخص التحديد
                                        </h6>
                                        <p class="text-muted mb-0">
                                            تم اختيار <span class="fw-bold text-primary" id="selectedStudentsText">0</span> طالب و 
                                            <span class="fw-bold text-primary" id="selectedSubjectsText">0</span> مادة
                                        </p>
                                    </div>
                                    <button type="submit" name="enroll_students" class="btn-gradient">
                                        <i class="fas fa-save ms-2"></i>
                                        تسجيل/تحديث المقررات المحددة
                                    </button>
                                </div>
                                <div class="mt-3 text-muted small">
                                    <i class="fas fa-lightbulb me-1"></i>
                                    سيتم تسجيل المقررات المختارة لجميع الطلاب المحددين بنوع التسجيل المختار
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </form>
            
            <!-- Currently Enrolled Subjects -->
            <?php if (!empty($enrolled_details)): ?>
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="content-card">
                            <div class="content-card-header">
                                <h5>
                                    <i class="fas fa-list-check"></i>
                                    المقررات المسجلة حالياً
                                </h5>
                                <span class="badge" style="background: linear-gradient(135deg, #28a745, #20c997); color: white; padding: 5px 15px; border-radius: 50px;">
                                    <?= (int)count($enrolled_details) ?> تسجيل
                                </span>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="table table-hover enrolled-table">
                                    <thead>
                                        <tr>
                                            <th>رقم الطالب</th>
                                            <th>اسم الطالب</th>
                                            <th>كود المادة</th>
                                            <th>اسم المادة</th>
                                            <th>نوع التسجيل</th>
                                            <th>الإجراءات</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($enrolled_details as $enrolled): ?>
                                            <?php 
                                            $cleanStudentId = urlencode($enrolled['student_id']);
                                            $cleanSubjectCode = urlencode($enrolled['subjectcode']);
                                            
                                            $cancelUrl = "subject_enrollment.php?" . http_build_query([
                                                'college_id' => (int)$college_id,
                                                'section_id' => (int)$section_id,
                                                'program_id' => (int)$program_id,
                                                'specialization_id' => (int)$specialization_id,
                                                'batch_id' => (int)$batch_id,
                                                'semester_id' => (int)$semester_id,
                                                'subject_source' => $subject_source,
                                                'action' => 'cancel',
                                                'student_id' => $cleanStudentId,
                                                'subjectcode' => $cleanSubjectCode,
                                                'subjecttype_id' => (int)$enrolled['subjecttype_id']
                                            ]);
                                            
                                            $typeClass = 'type-' . ((int)$enrolled['subjecttype_id']);
                                            ?>
                                            <tr>
                                                <td><code><?= htmlspecialchars($enrolled['student_id'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                                <td><?= htmlspecialchars($enrolled['student_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                                <td><strong><?= htmlspecialchars($enrolled['subjectcode'], ENT_QUOTES, 'UTF-8') ?></strong></td>
                                                <td><?= htmlspecialchars($enrolled['subjectnamea'], ENT_QUOTES, 'UTF-8') ?></td>
                                                <td>
                                                    <span class="type-badge <?= $typeClass ?>">
                                                        <?= htmlspecialchars($enrolled['subjecttype_name'] ?? 'عادي', ENT_QUOTES, 'UTF-8') ?>
                                                    </span>
                                                 </div>
                                                <td>
                                                    <a href="<?= htmlspecialchars($cancelUrl, ENT_QUOTES, 'UTF-8') ?>" 
                                                       class="btn-cancel"
                                                       onclick="return confirm('هل أنت متأكد من إلغاء تسجيل المادة <?= htmlspecialchars($enrolled['subjectcode'], ENT_QUOTES, 'UTF-8') ?> للطالب <?= htmlspecialchars($enrolled['student_name'], ENT_QUOTES, 'UTF-8') ?>؟')">
                                                        <i class="fas fa-trash-alt me-1"></i>إلغاء
                                                    </a>
                                                 </div>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Statistics -->
            <div class="row g-4 mt-2">
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-number"><?= (int)count($students) ?></div>
                        <div class="stat-label">عدد الطلاب</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-book"></i>
                        </div>
                        <div class="stat-number"><?= (int)count($subjects) ?></div>
                        <div class="stat-label">عدد المقررات</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="stat-number"><?= (int)count($selected_subjects) ?></div>
                        <div class="stat-label">المقررات المسجلة</div>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-plus-circle"></i>
                        </div>
                        <div class="stat-number"><?= (int)(count($subjects) - count($selected_subjects)) ?></div>
                        <div class="stat-label">المتاحة للتسجيل</div>
                    </div>
                </div>
            </div>
            
        <?php else: ?>
            <!-- Initial Instructions -->
            <div class="content-card">
                <div class="text-center py-5">
                    <div class="mb-4">
                        <i class="fas fa-filter fa-4x" style="color: #667eea; opacity: 0.5;"></i>
                    </div>
                    <h4 class="fw-bold mb-3">اختر معايير الترشيح</h4>
                    <p class="text-muted mb-4">الرجاء اختيار الكلية، القسم، البرنامج، الدفعة، والفصل الدراسي للبدء</p>
                    
                    <div class="row justify-content-center">
                        <div class="col-md-8">
                            <div class="list-group text-end">
                                <div class="list-group-item d-flex align-items-center gap-3 p-3 border-0 bg-light rounded-3 mb-2">
                                    <span class="badge rounded-circle p-3" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">1</span>
                                    <span><strong>الكلية:</strong> اختر الكلية أولاً</span>
                                </div>
                                <div class="list-group-item d-flex align-items-center gap-3 p-3 border-0 bg-light rounded-3 mb-2">
                                    <span class="badge rounded-circle p-3" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">2</span>
                                    <span><strong>القسم:</strong> سيتم تحديث الأقسام حسب الكلية المختارة</span>
                                </div>
                                <div class="list-group-item d-flex align-items-center gap-3 p-3 border-0 bg-light rounded-3 mb-2">
                                    <span class="badge rounded-circle p-3" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">3</span>
                                    <span><strong>البرنامج:</strong> اختر البرنامج المراد</span>
                                </div>
                                <div class="list-group-item d-flex align-items-center gap-3 p-3 border-0 bg-light rounded-3 mb-2">
                                    <span class="badge rounded-circle p-3" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">4</span>
                                    <span><strong>التخصص:</strong> (اختياري) يمكن تحديد تخصص معين</span>
                                </div>
                                <div class="list-group-item d-flex align-items-center gap-3 p-3 border-0 bg-light rounded-3 mb-2">
                                    <span class="badge rounded-circle p-3" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">5</span>
                                    <span><strong>الدفعة:</strong> اختر دفعة الطلاب</span>
                                </div>
                                <div class="list-group-item d-flex align-items-center gap-3 p-3 border-0 bg-light rounded-3">
                                    <span class="badge rounded-circle p-3" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">6</span>
                                    <span><strong>الفصل الدراسي:</strong> اختر الفصل الدراسي للتسجيل</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {
    // ============================================
    // تحسين رسالة التأكيد بتنسيق RTL
    // ============================================
    $('#enrollmentForm').on('submit', function(e) {
        const subjectTypeId = $('#subjecttype_id').val();
        if (!subjectTypeId || subjectTypeId === '') {
            e.preventDefault();
            showAlert('warning', '⚠️ الرجاء اختيار نوع التسجيل أولاً');
            return false;
        }
        
        const selectedSubjects = $('.subject-checkbox:checked').length;
        const selectedStudents = $('.student-checkbox:checked').length;
        
        if (selectedSubjects === 0) {
            e.preventDefault();
            showAlert('warning', '⚠️ الرجاء اختيار مادة واحدة على الأقل');
            return false;
        }
        
        if (selectedStudents === 0) {
            e.preventDefault();
            showAlert('warning', '⚠️ الرجاء اختيار طالب واحد على الأقل');
            return false;
        }
        
        const enrolledSubjects = $('.subject-item.enrolled .subject-checkbox:checked').length;
        const newSubjects = selectedSubjects - enrolledSubjects;
        const subjectTypeName = $('#subjecttype_id option:selected').text();
        
        // بناء رسالة منسقة RTL
        let message = '';
        message += '═══════════════════════════════════════\n';
        message += '            📋 تأكيد تسجيل المقررات\n';
        message += '═══════════════════════════════════════\n\n';
        message += `📚 عدد المقررات: ${selectedSubjects} مادة\n`;
        message += `🏷️ نوع التسجيل: ${subjectTypeName}\n`;
        message += `👥 عدد الطلاب: ${selectedStudents} طالب\n\n`;
        
        if (enrolledSubjects > 0) {
            message += '⚠️ ملاحظة: هناك مواد مسجلة مسبقاً\n';
            message += `   • ${enrolledSubjects} مادة سيتم تحديثها\n`;
            if (newSubjects > 0) {
                message += `   • ${newSubjects} مادة جديدة سيتم إضافتها\n`;
            }
            message += '\n💡 سيتم استبدال البيانات القديمة بالجديدة\n\n';
        }
        
        message += '═══════════════════════════════════════\n';
        message += '🤔 هل أنت متأكد من المتابعة؟';
        
        if (!confirm(message)) {
            e.preventDefault();
            return false;
        }
    });
    
    // ============================================
    // دالة عرض تنبيهات مخصصة
    // ============================================
    function showAlert(type, message) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert" style="position: fixed; top: 20px; right: 20px; left: auto; z-index: 9999; min-width: 300px; animation: slideInRight 0.5s ease;">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : (type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle')} ms-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('body').append(alertHtml);
        setTimeout(function() {
            $('.alert').fadeOut(500, function() {
                $(this).remove();
            });
        }, 3000);
    }
    
    // ============================================
    // تحميل الأقسام عند تغيير الكلية
    // ============================================
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        const sectionSelect = $('#section_id');
        const programSelect = $('#program_id');
        const specializationSelect = $('#specialization_id');
        
        // إعادة تعيين القوائم
        sectionSelect.html('<option value="">اختر القسم</option>').prop('disabled', true);
        programSelect.html('<option value="">اختر البرنامج</option>').prop('disabled', true);
        specializationSelect.html('<option value="">جميع التخصصات</option>').prop('disabled', true);
        
        $('#sectionStatus').html('<span class="spinner-border spinner-border-sm text-primary"></span> جاري تحميل الأقسام...');
        $('#programStatus').html('');
        $('#specializationStatus').html('');
        
        if (collegeId) {
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(sections) {
                    let options = '<option value="">اختر القسم</option>';
                    
                    if (sections.length > 0) {
                        sections.forEach(function(section) {
                            const selected = (section.id == <?= $section_id ?>) ? 'selected' : '';
                            options += `<option value="${section.id}" ${selected}>${escapeHtml(section.name)}</option>`;
                        });
                        $('#sectionStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + sections.length + ' قسم</span>');
                    } else {
                        options = '<option value="">لا توجد أقسام</option>';
                        $('#sectionStatus').html('<span class="text-muted"><i class="fas fa-info-circle me-1"></i> لا توجد أقسام</span>');
                    }
                    
                    sectionSelect.html(options).prop('disabled', false);
                    loadPrograms(collegeId);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sections:', error);
                    sectionSelect.html('<option value="">خطأ في تحميل الأقسام</option>').prop('disabled', false);
                    $('#sectionStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
                    showAlert('danger', 'حدث خطأ في تحميل الأقسام');
                }
            });
        } else {
            sectionSelect.prop('disabled', true);
            $('#sectionStatus').html('');
        }
    });
    
    // ============================================
    // تحميل البرامج
    // ============================================
    function loadPrograms(collegeId) {
        const programSelect = $('#program_id');
        
        programSelect.html('<option value="">اختر البرنامج</option>').prop('disabled', true);
        $('#programStatus').html('<span class="spinner-border spinner-border-sm text-primary"></span> جاري تحميل البرامج...');
        
        $.ajax({
            url: 'ajax/get_programs.php',
            method: 'GET',
            data: { college_id: collegeId },
            dataType: 'json',
            success: function(programs) {
                let options = '<option value="">اختر البرنامج</option>';
                
                if (programs.length > 0) {
                    programs.forEach(function(program) {
                        const selected = (program.id == <?= $program_id ?>) ? 'selected' : '';
                        options += `<option value="${program.id}" ${selected}>${escapeHtml(program.name)}</option>`;
                    });
                    $('#programStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + programs.length + ' برنامج</span>');
                } else {
                    options = '<option value="">لا توجد برامج</option>';
                    $('#programStatus').html('<span class="text-muted"><i class="fas fa-info-circle me-1"></i> لا توجد برامج</span>');
                }
                
                programSelect.html(options).prop('disabled', false);
            },
            error: function(xhr, status, error) {
                console.error('Error loading programs:', error);
                programSelect.html('<option value="">خطأ في تحميل البرامج</option>').prop('disabled', false);
                $('#programStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
                showAlert('danger', 'حدث خطأ في تحميل البرامج');
            }
        });
    }
    
    // ============================================
    // تحميل التخصصات
    // ============================================
    function loadSpecializations() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        const currentSpecialization = <?= $specialization_id ? $specialization_id : 'null' ?>;
        
        if (sectionId && programId && sectionId !== '' && programId !== '') {
            $('#specialization_id').prop('disabled', true);
            $('#specializationStatus').html('<span class="spinner-border spinner-border-sm text-primary"></span> جاري تحميل التخصصات...');
            
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { 
                    section_id: sectionId,
                    program_id: programId 
                },
                dataType: 'json',
                success: function(specializations) {
                    let options = '<option value="">جميع التخصصات</option>';
                    
                    if (specializations && specializations.length > 0) {
                        specializations.forEach(function(spec) {
                            const selected = (currentSpecialization == spec.specialization_id) ? 'selected' : '';
                            options += `<option value="${spec.specialization_id}" ${selected}>${escapeHtml(spec.specialization_name_ar)}</option>`;
                        });
                        $('#specializationStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + specializations.length + ' تخصص</span>');
                    } else {
                        options = '<option value="">لا توجد تخصصات متاحة</option>';
                        $('#specializationStatus').html('<span class="text-muted"><i class="fas fa-info-circle me-1"></i> لا توجد تخصصات</span>');
                    }
                    
                    $('#specialization_id').html(options).prop('disabled', false);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading specializations:', error);
                    $('#specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                    $('#specializationStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
                    showAlert('danger', 'حدث خطأ في تحميل التخصصات');
                }
            });
        } else {
            $('#specialization_id').html('<option value="">جميع التخصصات</option>').prop('disabled', true);
            $('#specializationStatus').html('<span class="text-muted"><i class="fas fa-info-circle me-1"></i> اختر القسم والبرنامج أولاً</span>');
        }
    }
    
    // ============================================
    // دالة تنقية النصوص (مقاومة XSS)
    // ============================================
    function escapeHtml(text) {
        if (!text) return '';
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // ============================================
    // تحميل البيانات الأولية
    // ============================================
    <?php if ($section_id && $program_id): ?>
        loadSpecializations();
    <?php endif; ?>
    
    <?php if ($college_id): ?>
        $('#college_id').trigger('change');
    <?php endif; ?>
    
    // ============================================
    // مراقبة تغييرات القسم والبرنامج
    // ============================================
    $('#section_id, #program_id').on('change', function() {
        loadSpecializations();
    });
    
    // ============================================
    // تحديث العدادات
    // ============================================
    function updateCounters() {
        const selectedSubjects = $('.subject-checkbox:checked').length;
        const totalSubjects = $('.subject-checkbox').length;
        $('#selectedSubjectsCount').text(selectedSubjects);
        $('#selectedSubjectsText').text(selectedSubjects);
        
        const selectedStudents = $('.student-checkbox:checked').length;
        const totalStudents = $('.student-checkbox').length;
        $('#selectedStudentsCount').text(selectedStudents);
        $('#selectedStudentsText').text(selectedStudents);
        
        // تحديث أنماط العناصر المحددة
        $('.subject-item').removeClass('selected');
        $('.subject-checkbox:checked').each(function() {
            $(this).closest('.subject-item').addClass('selected');
        });
        
        $('.student-item').removeClass('selected');
        $('.student-checkbox:checked').each(function() {
            $(this).closest('.student-item').addClass('selected');
        });
        
        // تحديث خانات الاختيار الرئيسية
        const allStudentsChecked = totalStudents > 0 && selectedStudents === totalStudents;
        $('#masterStudentCheckbox').prop('checked', allStudentsChecked);
        
        const allSubjectsChecked = totalSubjects > 0 && selectedSubjects === totalSubjects;
        $('#selectAllSubjects').prop('checked', allSubjectsChecked);
        
        // عرض ملخص التحديد في وحدة التحكم (للتطوير)
        console.log(`✅ تم التحديث: ${selectedStudents} طالب, ${selectedSubjects} مادة`);
    }
    
    // ============================================
    // اختيار الكل للمواد
    // ============================================
    $('#selectAllSubjects').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('.subject-checkbox').prop('checked', isChecked);
        updateCounters();
        
        if (isChecked) {
            showAlert('info', '✅ تم اختيار جميع المقررات');
        } else {
            showAlert('info', '📖 تم إلغاء اختيار جميع المقررات');
        }
    });
    
    // ============================================
    // اختيار الكل للطلاب
    // ============================================
    $('#selectAllStudents').on('click', function() {
        $('.student-checkbox').prop('checked', true);
        updateCounters();
        showAlert('info', '✅ تم اختيار جميع الطلاب');
    });
    
    // ============================================
    // إلغاء اختيار الكل للطلاب
    // ============================================
    $('#deselectAllStudents').on('click', function() {
        $('.student-checkbox').prop('checked', false);
        updateCounters();
        showAlert('info', '📋 تم إلغاء اختيار جميع الطلاب');
    });
    
    // ============================================
    // خانة اختيار رئيسية للطلاب
    // ============================================
    $('#masterStudentCheckbox').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('.student-checkbox').prop('checked', isChecked);
        updateCounters();
    });
    
    // ============================================
    // مراقبة تغييرات الخانات الفردية
    // ============================================
    $(document).on('change', '.student-checkbox, .subject-checkbox', updateCounters);
    
    // ============================================
    // إضافة تأثيرات hover للعناصر
    // ============================================
    $(document).on('mouseenter', '.student-item, .subject-item', function() {
        $(this).css('transform', 'translateY(-2px)');
    }).on('mouseleave', '.student-item, .subject-item', function() {
        $(this).css('transform', 'translateY(0)');
    });
    
    // ============================================
    // إضافة زر "بحث سريع" للطلاب
    // ============================================
    const searchInput = `
        <div class="mb-3">
            <input type="text" id="studentSearch" class="form-control form-control-sm" placeholder="🔍 بحث سريع عن طالب...">
        </div>
    `;
    $('.scrollable-area').first().prepend(searchInput);
    
    $('#studentSearch').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        $('.student-item').each(function() {
            const studentName = $(this).find('strong').text().toLowerCase();
            const studentId = $(this).find('code').text().toLowerCase();
            if (studentName.includes(searchTerm) || studentId.includes(searchTerm)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
    
    // ============================================
    // إضافة زر "بحث سريع" للمواد
    // ============================================
    const subjectSearchInput = `
        <div class="mb-3">
            <input type="text" id="subjectSearch" class="form-control form-control-sm" placeholder="🔍 بحث سريع عن مادة...">
        </div>
    `;
    $('.scrollable-area').last().prepend(subjectSearchInput);
    
    $('#subjectSearch').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        $('.subject-item').each(function() {
            const subjectCode = $(this).find('strong').text().toLowerCase();
            const subjectName = $(this).find('.mt-1').text().toLowerCase();
            if (subjectCode.includes(searchTerm) || subjectName.includes(searchTerm)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
    
    // ============================================
    // تهيئة العدادات
    // ============================================
    updateCounters();
    
    // ============================================
    // إخفاء التنبيهات تلقائياً
    // ============================================
    setTimeout(function() {
        $('.alert').fadeOut(500, function() {
            $(this).remove();
        });
    }, 5000);
    
    // ============================================
    // إضافة تأكيد قبل إلغاء التسجيل (لجميع أزرار الإلغاء)
    // ============================================
    $(document).on('click', '.btn-cancel', function(e) {
        const confirmMessage = '⚠️ هل أنت متأكد من إلغاء تسجيل هذه المادة؟\n\nلا يمكن التراجع عن هذا الإجراء.';
        if (!confirm(confirmMessage)) {
            e.preventDefault();
            return false;
        }
    });
    
    // ============================================
    // تحسين عرض الجدول على الأجهزة المحمولة
    // ============================================
    if ($(window).width() < 768) {
        $('.enrolled-table').addClass('table-responsive');
    }
    
    // ============================================
    // إضافة رسالة ترحيب عند تحميل الصفحة (اختياري)
    // ============================================
    console.log('✅ تم تحميل صفحة تسجيل المقررات بنجاح');
});
</script>


<?php include 'footer.php'; ?>
