<?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();

$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;

// Initialize variables
$errors = [];
$success_message = '';
$action = $_GET['action'] ?? '';
$student_id_to_cancel = $_GET['student_id'] ?? '';
$subjectcode_to_cancel = $_GET['subjectcode'] ?? '';

// Handle cancellation (hard delete)
if ($action === 'cancel' && $student_id_to_cancel && $subjectcode_to_cancel) {
    // Get semester and batch from URL
    $semester_id = $_GET['semester_id'] ?? 0;
    $batch_id = $_GET['batch_id'] ?? 0;
    
    if ($semester_id && $batch_id) {
        // التحقق من المدخلات
        if (!ctype_digit((string)$semester_id) || !ctype_digit((string)$batch_id)) {
            $errors[] = "معرف الفصل أو الدفعة غير صالح";
        } else {
            // Hard delete the enrollment
            $deleteStmt = $mysqli1->prepare("
                DELETE FROM studentsubjects 
                WHERE student_id = ? 
                AND subjectcode = ? 
                AND semester_id = ? 
                AND batch_id = ?
            ");
            $deleteStmt->bind_param('ssii', $student_id_to_cancel, $subjectcode_to_cancel, $semester_id, $batch_id);
            
            if ($deleteStmt->execute()) {
                $success_message = "تم إلغاء تسجيل المادة بنجاح";
            } else {
                $errors[] = "حدث خطأ أثناء إلغاء التسجيل";
            }
            $deleteStmt->close();
        }
        
        // Redirect back to same page with filters
        header("Location: subject_enrollment.php?" . http_build_query($_GET));
        exit();
    }
}

// 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);

// 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
$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']) ? $_GET['subject_source'] : 'plan';

// Handle enrollment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enroll_students'])) {
    $semester_id = (int)$_POST['semester_id'];
    $batch_id = (int)$_POST['batch_id'];
    $subject_ids = $_POST['subject_ids'] ?? [];
    
    // Validate
    if (empty($semester_id)) {
        $errors[] = 'الرجاء اختيار الفصل الدراسي';
    }
    
    if (empty($batch_id)) {
        $errors[] = 'الرجاء اختيار الدفعة';
    }
    
    if (empty($subject_ids)) {
        $errors[] = 'الرجاء اختيار مادة واحدة على الأقل';
    }
    
    // Get selected student IDs
    $student_ids = $_POST['student_ids'] ?? [];
    if (empty($student_ids)) {
        $errors[] = 'الرجاء اختيار طالب واحد على الأقل';
    }
    
    if (empty($errors)) {
        $success_count = 0;
        $update_count = 0;
        $error_count = 0;
        
        // Begin transaction
        $mysqli1->begin_transaction();
        
        try {
            foreach ($student_ids as $student_id) {
                foreach ($subject_ids as $subject_id) {
                    // Get subject code
                    $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
                    $checkStmt = $mysqli1->prepare("
                        SELECT id FROM studentsubjects 
                        WHERE student_id = ? 
                        AND subjectcode = ? 
                        AND semester_id = ? 
                        AND batch_id = ?
                    ");
                    $checkStmt->bind_param('ssii', $student_id, $subjectcode, $semester_id, $batch_id);
                    $checkStmt->execute();
                    $exists = $checkStmt->get_result()->fetch_assoc();
                    $checkStmt->close();
                    
                    if (!$exists) {
                        // Insert new enrollment
                        $insertStmt = $mysqli1->prepare("
                            INSERT INTO studentsubjects 
                            (subjectcode, student_id, semester_id, batch_id, weight, created_at, updated_at) 
                            VALUES (?, ?, ?, ?, 100.00, NOW(), NOW())
                        ");
                        $insertStmt->bind_param('ssii', $subjectcode, $student_id, $semester_id, $batch_id);
                        
                        if ($insertStmt->execute()) {
                            $success_count++;
                        } else {
                            $error_count++;
                        }
                        $insertStmt->close();
                    } else {
                        // Update existing enrollment (overwrite)
                        $updateStmt = $mysqli1->prepare("
                            UPDATE studentsubjects 
                            SET weight = 100.00, updated_at = NOW()
                            WHERE student_id = ? 
                            AND subjectcode = ? 
                            AND semester_id = ? 
                            AND batch_id = ?
                        ");
                        $updateStmt->bind_param('ssii', $student_id, $subjectcode, $semester_id, $batch_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 ($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;

if ($college_id && $section_id && $program_id && $batch_id) {
    // 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 which academic plan is linked to this batch
    $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();
    
    // Get subjects based on source
    if ($subject_source === 'plan' && $plan_info && $semester_id) {
        // Get subjects from the plan for the selected semester
        $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 {
        // Get all subjects for this program - إضافة التخصص للاستعلام
        $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 already enrolled subjects for this batch and semester
    if ($semester_id) {
        $enrolledQuery = "
            SELECT ss.student_id, ss.subjectcode, ss.id as enrollment_id, 
                   s.student_name, sub.subjectnamea
            FROM studentsubjects ss
            JOIN students s ON ss.student_id = s.student_id
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode
            WHERE ss.batch_id = ? 
            AND ss.semester_id = ?
            ORDER BY s.student_name, ss.subjectcode
        ";
        $enrolledStmt = $mysqli1->prepare($enrolledQuery);
        $enrolledStmt->bind_param('ii', $batch_id, $semester_id);
        $enrolledStmt->execute();
        $enrolledResult = $enrolledStmt->get_result();
        $enrolled_details = $enrolledResult->fetch_all(MYSQLI_ASSOC);
        $enrolledStmt->close();
        
        // Create array of enrolled subject codes for highlighting
        $selected_subjects = [];
        foreach ($enrolled_details as $enrolled) {
            $selected_subjects[$enrolled['subjectcode']] = true;
        }
    }
}

// Get selected specialization name if any
$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';
?>

<style>
    /* تنسيقات متوافقة مع الصفحات السابقة */
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --header-gradient: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
        --success-gradient: linear-gradient(135deg, #00b09b, #96c93d);
        --danger-gradient: linear-gradient(135deg, #fc6767, #ec008c);
        --info-gradient: linear-gradient(135deg, #667eea, #764ba2);
    }

    body {
        font-family: 'Cairo', sans-serif;
           background-color: #f8fafc;
        min-height: 100vh;
    }

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

    /* Glassmorphism Cards */
    .glass-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 30px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .glass-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 30px 80px rgba(0, 0, 0, 0.4);
    }

    /* Header Styles */
    .page-header {
        background: var(--header-gradient);
        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;
    }

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

    /* Buttons */
    .btn-gradient {
        background: var(--success-gradient);
        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;
        border: 2px solid transparent;
    }

    .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;
        border: 2px solid transparent;
    }

    .btn-reset:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 10px rgba(75, 85, 99, 0.4);
        color: white;
    }

    /* Filter Card */
    .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;
    }

    .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;
    }

    .form-control:focus, .form-select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        outline: none;
    }

    /* Content Cards */
    .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;
    }

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

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

    /* Statistics Cards */
    .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;
        border: 1px solid rgba(102, 126, 234, 0.1);
        height: 100%;
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(102, 126, 234, 0.2);
    }

    .stat-icon {
        font-size: 2.2rem;
        margin-bottom: 10px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }

    .stat-number {
        font-size: 2.2rem;
        font-weight: 800;
        color: #2d3748;
        margin-bottom: 5px;
    }

    .stat-label {
        color: #718096;
        font-weight: 600;
        font-size: 0.95rem;
    }

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

    .scrollable-area::-webkit-scrollbar {
        width: 8px;
    }

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

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

    /* Items */
    .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);
    }

    .student-item:hover, .subject-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.15);
        border-color: #667eea;
    }

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

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

    .student-item.plan-subject {
        border-right: 4px solid #6610f2;
    }

    /* Badges */
    .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 */
    .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);
    }

    /* Source Toggle */
    .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);
    }

    /* Cancel Button */
    .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;
    }

    .btn-cancel:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 10px rgba(231, 76, 60, 0.4);
        color: white;
    }

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

    .enrolled-table th {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        font-weight: 700;
        color: #2d3748;
        padding: 15px;
    }

    .enrolled-table td {
        padding: 12px 15px;
        border-bottom: 1px solid #e2e8f0;
    }

    /* Alerts */
    .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;
    }

    @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 */
    .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;
    }

    .filter-badge i {
        font-size: 0.8rem;
    }

    /* RTL Specific */
    .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;
        }
        .stat-number {
            font-size: 1.8rem;
        }
        .content-card-header {
            flex-direction: column;
            gap: 10px;
        }
    }
</style>

<div class="main-wrapper" dir="rtl">
    <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"></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"></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>
                        <?php if ($section_id > 0): ?>
                            <?php
                            $sectionStmt = $mysqli1->prepare("SELECT id, name FROM sections WHERE id = ?");
                            $sectionStmt->bind_param('i', $section_id);
                            $sectionStmt->execute();
                            $sectionResult = $sectionStmt->get_result();
                            if ($sectionRow = $sectionResult->fetch_assoc()) {
                                echo '<option value="' . (int)$section_id . '" selected>' . htmlspecialchars($sectionRow['name']) . '</option>';
                            }
                            $sectionStmt->close();
                            ?>
                        <?php endif; ?>
                    </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>
                        <?php if ($program_id > 0): ?>
                            <?php
                            $programStmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE id = ?");
                            $programStmt->bind_param('i', $program_id);
                            $programStmt->execute();
                            $programResult = $programStmt->get_result();
                            if ($programRow = $programResult->fetch_assoc()) {
                                echo '<option value="' . (int)$program_id . '" selected>' . htmlspecialchars($programRow['name']) . '</option>';
                            }
                            $programStmt->close();
                            ?>
                        <?php endif; ?>
                    </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>
                        <?php if ($specialization_id > 0 && $selected_specialization_name): ?>
                            <option value="<?= (int)$specialization_id ?>" selected>
                                <?= htmlspecialchars($selected_specialization_name, ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endif; ?>
                    </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): 
                            $collegeName = '';
                            foreach($colleges as $c) {
                                if($c['id'] == $college_id) {
                                    $collegeName = $c['name'];
                                    break;
                                }
                            }
                        ?>
                            <span class="filter-badge">
                                <i class="fas fa-university"></i>
                                <?= htmlspecialchars($collegeName) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($section_id): 
                            $sectionStmt = $mysqli1->prepare("SELECT name FROM sections WHERE id = ?");
                            $sectionStmt->bind_param('i', $section_id);
                            $sectionStmt->execute();
                            $sectionResult = $sectionStmt->get_result();
                            $sectionName = $sectionResult->fetch_assoc()['name'] ?? '';
                            $sectionStmt->close();
                        ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #28a745, #20c997);">
                                <i class="fas fa-layer-group"></i>
                                <?= htmlspecialchars($sectionName) ?>
                            </span>
                        <?php endif; ?>
                        
                        <?php if ($program_id): 
                            $programStmt = $mysqli1->prepare("SELECT name FROM programs WHERE id = ?");
                            $programStmt->bind_param('i', $program_id);
                            $programStmt->execute();
                            $programResult = $programStmt->get_result();
                            $programName = $programResult->fetch_assoc()['name'] ?? '';
                            $programStmt->close();
                        ?>
                            <span class="filter-badge" style="background: linear-gradient(135deg, #ff6b6b, #ee5253);">
                                <i class="fas fa-graduation-cap"></i>
                                <?= htmlspecialchars($programName) ?>
                            </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-8">
                            <div class="d-flex gap-3">
                                <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-4 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 (if available) -->
            <?php if ($plan_info && $subject_source === 'plan'): ?>
                <div class="plan-info-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <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; ?>
            
            <!-- 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 ?>">
                
                <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">
                                    <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">
                                                        <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">
                                    <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>
                                            <small class="d-block mt-2">يمكنك اختيار "جميع مواد البرنامج" لعرض المقررات</small>
                                        <?php else: ?>
                                            <p class="text-muted">لا توجد مواد متاحة</p>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <?php foreach ($subjects as $subject): ?>
                                        <?php 
                                        $isSelected = isset($selected_subjects[$subject['subjectcode']]);
                                        $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">
                                                        <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">
                                    <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 mt-3 mt-md-0" style="padding: 12px 40px;">
                                        <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 (for cancellation) -->
            <?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>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($enrolled_details as $enrolled): ?>
                                            <?php 
                                            $cancelUrl = "subject_enrollment.php?" . http_build_query([
                                                'college_id' => $college_id,
                                                'section_id' => $section_id,
                                                'program_id' => $program_id,
                                                'specialization_id' => $specialization_id,
                                                'batch_id' => $batch_id,
                                                'semester_id' => $semester_id,
                                                'subject_source' => $subject_source,
                                                'action' => 'cancel',
                                                'student_id' => $enrolled['student_id'],
                                                'subjectcode' => $enrolled['subjectcode']
                                            ]);
                                            ?>
                                            <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>
                                                    <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>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Statistics -->
            <div class="row g-4 mt-2">
                <div class="col-md-3">
                    <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">
                    <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">
                    <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">
                    <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-start">
                                <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() {
    // Load sections when college changes
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        const sectionSelect = $('#section_id');
        const programSelect = $('#program_id');
        const specializationSelect = $('#specialization_id');
        
        // Reset dependent selects
        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) {
            // Load sections
            $.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}>${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);
                    
                    // Load programs
                    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>');
                }
            });
        } else {
            sectionSelect.prop('disabled', true);
            $('#sectionStatus').html('');
        }
    });
    
    // Load programs when college changes
    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}>${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>');
            }
        });
    }
    
    // Load specializations when section and program change
    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.length > 0) {
                        specializations.forEach(function(spec) {
                            const selected = (currentSpecialization == spec.specialization_id) ? 'selected' : '';
                            options += `<option value="${spec.specialization_id}" ${selected}>${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>');
                }
            });
        } 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>');
        }
    }
    
    // Load specializations on page load if section and program are selected
    <?php if ($section_id && $program_id): ?>
        loadSpecializations();
    <?php endif; ?>
    
    // Trigger college change on page load if college is selected
    <?php if ($college_id): ?>
        $('#college_id').trigger('change');
    <?php endif; ?>
    
    // Attach loadSpecializations to section and program change events
    $('#section_id, #program_id').on('change', function() {
        loadSpecializations();
    });
    
    // Update counters
    function updateCounters() {
        // Subject counters
        const selectedSubjects = $('.subject-checkbox:checked').length;
        const totalSubjects = $('.subject-checkbox').length;
        $('#selectedSubjectsCount').text(selectedSubjects);
        $('#selectedSubjectsText').text(selectedSubjects);
        
        // Student counters
        const selectedStudents = $('.student-checkbox:checked').length;
        const totalStudents = $('.student-checkbox').length;
        $('#selectedStudentsCount').text(selectedStudents);
        $('#selectedStudentsText').text(selectedStudents);
        
        // Update subject item styles
        $('.subject-item').removeClass('selected');
        $('.subject-checkbox:checked').each(function() {
            $(this).closest('.subject-item').addClass('selected');
        });
        
        // Update student item styles
        $('.student-item').removeClass('selected');
        $('.student-checkbox:checked').each(function() {
            $(this).closest('.student-item').addClass('selected');
        });
        
        // Update master checkbox
        const allStudentsChecked = totalStudents > 0 && selectedStudents === totalStudents;
        $('#masterStudentCheckbox').prop('checked', allStudentsChecked);
        
        // Update select all subjects checkbox
        const allSubjectsChecked = totalSubjects > 0 && selectedSubjects === totalSubjects;
        $('#selectAllSubjects').prop('checked', allSubjectsChecked);
    }
    
    // Select all subjects
    $('#selectAllSubjects').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('.subject-checkbox').prop('checked', isChecked);
        updateCounters();
    });
    
    // Select all students
    $('#selectAllStudents').on('click', function() {
        $('.student-checkbox').prop('checked', true);
        updateCounters();
    });
    
    // Deselect all students
    $('#deselectAllStudents').on('click', function() {
        $('.student-checkbox').prop('checked', false);
        updateCounters();
    });
    
    // Master student checkbox
    $('#masterStudentCheckbox').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('.student-checkbox').prop('checked', isChecked);
        updateCounters();
    });
    
    // Individual student checkbox
    $(document).on('change', '.student-checkbox', updateCounters);
    
    // Individual subject checkbox
    $(document).on('change', '.subject-checkbox', updateCounters);
    
    // Form validation
    $('#enrollmentForm').on('submit', function(e) {
        const selectedSubjects = $('.subject-checkbox:checked').length;
        const selectedStudents = $('.student-checkbox:checked').length;
        
        if (selectedSubjects === 0) {
            e.preventDefault();
            alert('الرجاء اختيار مادة واحدة على الأقل');
            return false;
        }
        
        if (selectedStudents === 0) {
            e.preventDefault();
            alert('الرجاء اختيار طالب واحد على الأقل');
            return false;
        }
        
        // Get enrolled subjects count
        const enrolledSubjects = $('.subject-item.enrolled .subject-checkbox:checked').length;
        const newSubjects = selectedSubjects - enrolledSubjects;
        
        // Confirm before submission
        let message = `هل أنت متأكد من تسجيل ${selectedSubjects} مادة لـ ${selectedStudents} طالب؟`;
        if (enrolledSubjects > 0) {
            message += `\n\n${enrolledSubjects} مادة مسجلة مسبقاً سيتم تحديثها`;
            if (newSubjects > 0) {
                message += `\n${newSubjects} مادة جديدة سيتم تسجيلها`;
            }
        }
        
        if (!confirm(message)) {
            e.preventDefault();
            return false;
        }
    });
    
    // Initialize counters
    updateCounters();
    
    // Auto-hide alerts
    setTimeout(function() {
        $('.alert').fadeOut(500, function() {
            $(this).remove();
        });
    }, 5000);
});
</script>

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