<?php
// student_enrollment.php - Enroll subjects for a specific student
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

// Start session only once at the beginning
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// التحقق من CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// وظائف الأمان
function validateInt($input, $default = 0) {
    if (isset($input) && ctype_digit((string)$input)) {
        return (int)$input;
    }
    return $default;
}

function validateString($input, $default = '') {
    if (isset($input) && is_string($input)) {
        $clean = trim($input);
        $clean = strip_tags($clean);
        $clean = htmlspecialchars($clean, ENT_QUOTES, 'UTF-8');
        return $clean;
    }
    return $default;
}

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

// Initialize variables
$errors = [];
$success_message = '';
$info_message = '';

// Filter variables
$college_filter = validateString($_GET['college_id'] ?? '');
$section_filter = validateString($_GET['section_id'] ?? '');
$program_filter = validateString($_GET['program_id'] ?? '');
$specialization_filter = validateInt($_GET['specialization_id'] ?? 0);
$batch_filter = validateString($_GET['batch_id'] ?? '');
$semester_filter = validateInt($_GET['semester_id'] ?? 0);
$search_term = validateString($_GET['search_term'] ?? '');
$search_type = validateString($_GET['search_type'] ?? 'id');
$subject_source = isset($_GET['subject_source']) ? validateString($_GET['subject_source']) : 'plan';

// Selected student
$selected_student_id = validateString($_GET['student_id'] ?? '');
$selected_student = null;
$student_subjects = [];
$available_semesters = [];

// Handle cancellation (hard delete)
$action = validateString($_GET['action'] ?? '');
$student_id_to_cancel = validateString($_GET['student_id'] ?? '');
$subjectcode_to_cancel = validateString($_GET['subjectcode'] ?? '');

if ($action === 'cancel' && $student_id_to_cancel && $subjectcode_to_cancel) {
    // Get semester and batch from URL
    $semester_id = validateInt($_GET['semester_id'] ?? 0);
    $batch_id = validateString($_GET['batch_id'] ?? '');
    
    if ($semester_id && $batch_id) {
        // Hard delete the enrollment
        $deleteStmt = $mysqli1->prepare("
            DELETE FROM studentsubjects 
            WHERE student_id = ? 
            AND subjectcode = ? 
            AND semester_id = ? 
            AND batch_id = ?
        ");
        $deleteStmt->bind_param('ssis', $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
        $redirect_params = [
            'student_id' => $selected_student_id,
            'college_id' => $college_filter,
            'section_id' => $section_filter,
            'program_id' => $program_filter,
            'specialization_id' => $specialization_filter,
            'batch_id' => $batch_filter,
            'semester_id' => $semester_filter,
            'search_term' => $search_term,
            'search_type' => $search_type,
            'subject_source' => $subject_source
        ];
        header("Location: student_enrollment.php?" . http_build_query($redirect_params));
        exit();
    }
}

// Get filter data for dropdowns
$colleges = [];
$result = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $colleges[] = [
            'id' => validateString($row['id']),
            'name' => validateString($row['name'])
        ];
    }
}

$sections = [];
$result = $mysqli1->query("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $sections[] = [
            'id' => validateString($row['id']),
            'name' => validateString($row['name'])
        ];
    }
}

$programs = [];
$result = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $programs[] = [
            'id' => validateString($row['id']),
            'name' => validateString($row['name'])
        ];
    }
}

$batches = [];
$result = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $batches[] = [
            'id' => validateString($row['id']),
            'value' => validateString($row['value'])
        ];
    }
}

$semesters = [];
$result = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $semesters[] = [
            'id' => (int)$row['id'],
            'name' => validateString($row['name'])
        ];
    }
}

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

// Get students list based on filters and search
$students_list = [];
if (!empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter) || !empty($search_term)) {
    
    $query = "
        SELECT 
            s.student_id,
            s.student_name,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            spec.specialization_name_ar as specialization_name,
            b.value as batch_name,
            (SELECT COUNT(*) FROM studentsubjects WHERE student_id = s.student_id) as subjects_count
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations spec ON s.specialization_id = spec.specialization_id AND spec.deleted_at IS NULL
        LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
        WHERE s.deleted_at IS NULL
    ";
    
    $conditions = [];
    $params = [];
    $types = "";
    
    // Add committee restriction
    if (!$canAll && $scopeCollege !== null) {
        $conditions[] = "s.college_id = ?";
        $params[] = $scopeCollege;
        $types .= "s";
    }
    
    // Add search term
    if (!empty($search_term)) {
        if ($search_type === 'id') {
            $conditions[] = "s.student_id LIKE ?";
            $params[] = "%$search_term%";
            $types .= "s";
        } else {
            $conditions[] = "s.student_name LIKE ?";
            $params[] = "%$search_term%";
            $types .= "s";
        }
    }
    
    // Add filters
    if (!empty($college_filter)) {
        $conditions[] = "s.college_id = ?";
        $params[] = $college_filter;
        $types .= "s";
    }
    
    if (!empty($section_filter)) {
        $conditions[] = "s.section_id = ?";
        $params[] = $section_filter;
        $types .= "s";
    }
    
    if (!empty($program_filter)) {
        $conditions[] = "s.program_id = ?";
        $params[] = $program_filter;
        $types .= "s";
    }
    
    if ($specialization_filter > 0) {
        $conditions[] = "s.specialization_id = ?";
        $params[] = $specialization_filter;
        $types .= "i";
    }
    
    if (!empty($batch_filter)) {
        $conditions[] = "s.batch_id = ?";
        $params[] = $batch_filter;
        $types .= "s";
    }
    
    if (!empty($conditions)) {
        $query .= " AND " . implode(" AND ", $conditions);
    }
    
    $query .= " ORDER BY s.student_name LIMIT 100";
    
    $stmt = $mysqli1->prepare($query);
    if ($stmt) {
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $students_list[] = [
                'student_id' => validateString($row['student_id']),
                'student_name' => validateString($row['student_name']),
                'college_name' => validateString($row['college_name'] ?? ''),
                'section_name' => validateString($row['section_name'] ?? ''),
                'program_name' => validateString($row['program_name'] ?? ''),
                'specialization_name' => validateString($row['specialization_name'] ?? ''),
                'batch_name' => validateString($row['batch_name'] ?? ''),
                'batch_id' => validateString($row['batch_id'] ?? ''),
                'subjects_count' => (int)$row['subjects_count']
            ];
        }
        $stmt->close();
    }
}

// If a specific student is selected
if (!empty($selected_student_id)) {
    // Get student basic info
    $studentQuery = "
        SELECT 
            s.id,
            s.student_id,
            s.student_name,
            s.email,
            s.phone_number,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            spec.specialization_name_ar as specialization_name,
            b.value as batch_name
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations spec ON s.specialization_id = spec.specialization_id AND spec.deleted_at IS NULL
        LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
        WHERE s.student_id = ? AND s.deleted_at IS NULL
        LIMIT 1
    ";
    
    $stmt = $mysqli1->prepare($studentQuery);
    if ($stmt) {
        $stmt->bind_param('s', $selected_student_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $selected_student = [
                'id' => (int)$row['id'],
                'student_id' => validateString($row['student_id']),
                'student_name' => validateString($row['student_name']),
                'email' => validateString($row['email'] ?? ''),
                'phone' => validateString($row['phone_number'] ?? ''),
                'college_id' => validateString($row['college_id'] ?? ''),
                'college_name' => validateString($row['college_name'] ?? ''),
                'section_id' => validateString($row['section_id'] ?? ''),
                'section_name' => validateString($row['section_name'] ?? ''),
                'program_id' => validateString($row['program_id'] ?? ''),
                'program_name' => validateString($row['program_name'] ?? ''),
                'specialization_id' => (int)$row['specialization_id'],
                'specialization_name' => validateString($row['specialization_name'] ?? ''),
                'batch_id' => validateString($row['batch_id'] ?? ''),
                'batch_name' => validateString($row['batch_name'] ?? '')
            ];
            
            // Check committee permissions
            if (!$canAll && $scopeCollege !== null && $row['college_id'] != $scopeCollege) {
                die('غير مصرح لك بالوصول لبيانات هذا الطالب');
            }
            
            // Get available semesters for this student
            $semesterQuery = "
                SELECT DISTINCT 
                    ss.semester_id,
                    s.name as semester_name
                FROM studentsubjects ss
                JOIN semesters s ON ss.semester_id = s.id AND s.deleted_at IS NULL
                WHERE ss.student_id = ?
                ORDER BY ss.semester_id DESC
            ";
            
            $semesterStmt = $mysqli1->prepare($semesterQuery);
            if ($semesterStmt) {
                $semesterStmt->bind_param('s', $selected_student_id);
                $semesterStmt->execute();
                $semesterResult = $semesterStmt->get_result();
                
                while ($row = $semesterResult->fetch_assoc()) {
                    $available_semesters[] = [
                        'id' => (int)$row['semester_id'],
                        'name' => validateString($row['semester_name'])
                    ];
                }
                $semesterStmt->close();
            }
        }
        $stmt->close();
    }
    
    // Get subjects based on student's program and filters
    $subjects = [];
    $selected_subjects = [];
    $plan_info = null;
    
    if ($selected_student && $semester_filter > 0) {
        // Find which academic plan is linked to this student's 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('ssss', 
            $selected_student['program_id'], 
            $selected_student['college_id'], 
            $selected_student['section_id'], 
            $selected_student['batch_id']
        );
        $planStmt->execute();
        $plan_info = $planStmt->get_result()->fetch_assoc();
        $planStmt->close();
        
        // Get subjects based on source
        if ($subject_source === 'plan' && $plan_info) {
            // 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_filter);
        } 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 = "sss";
            $params = [$selected_student['program_id'], $selected_student['college_id'], $selected_student['section_id']];
            
            // Add specialization filter if selected
            if ($specialization_filter > 0) {
                $subjectQuery .= " AND (s.specialization_id = ? OR s.specialization_id = 0 OR s.specialization_id IS NULL)";
                $types .= "i";
                $params[] = $specialization_filter;
            }
            
            $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 student and semester
        $enrolledQuery = "
            SELECT ss.subjectcode, ss.id as enrollment_id, ss.batch_id
            FROM studentsubjects ss
            WHERE ss.student_id = ? 
            AND ss.semester_id = ?
        ";
        $enrolledStmt = $mysqli1->prepare($enrolledQuery);
        $enrolledStmt->bind_param('si', $selected_student_id, $semester_filter);
        $enrolledStmt->execute();
        $enrolledResult = $enrolledStmt->get_result();
        
        while ($enrolled = $enrolledResult->fetch_assoc()) {
            $selected_subjects[$enrolled['subjectcode']] = true;
        }
        $enrolledStmt->close();
    }
}

// Handle enrollment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enroll_student'])) {
    // Verify CSRF token
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    }
    
    $student_id = validateString($_POST['student_id'] ?? '');
    $semester_id = validateInt($_POST['semester_id'] ?? 0);
    $batch_id = validateString($_POST['batch_id'] ?? '');
    $subject_ids = $_POST['subject_ids'] ?? [];
    
    // Validate
    if (empty($student_id)) {
        $errors[] = 'رقم الطالب مطلوب';
    }
    
    if (empty($semester_id)) {
        $errors[] = 'الرجاء اختيار الفصل الدراسي';
    }
    
    if (empty($batch_id)) {
        $errors[] = 'الرجاء اختيار الدفعة';
    }
    
    if (empty($subject_ids) || !is_array($subject_ids)) {
        $errors[] = 'الرجاء اختيار مادة واحدة على الأقل';
    }
    
    if (empty($errors)) {
        $success_count = 0;
        $update_count = 0;
        $error_count = 0;
        
        // Begin transaction
        $mysqli1->begin_transaction();
        
        try {
            foreach ($subject_ids as $subject_id) {
                $subject_id = validateInt($subject_id);
                if ($subject_id <= 0) continue;
                
                // 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('ssis', $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('ssis', $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('ssis', $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 حالة)";
                }
                
                // Refresh the page
                $redirect_params = [
                    'student_id' => $student_id,
                    'college_id' => $college_filter,
                    'section_id' => $section_filter,
                    'program_id' => $program_filter,
                    'specialization_id' => $specialization_filter,
                    'batch_id' => $batch_filter,
                    'semester_id' => $semester_id,
                    'search_term' => $search_term,
                    'search_type' => $search_type,
                    'subject_source' => $subject_source
                ];
                echo "<meta http-equiv='refresh' content='1;url=student_enrollment.php?" . http_build_query($redirect_params) . "'>";
            } else {
                if ($error_count > 0) {
                    $errors[] = "حدث خطأ في تسجيل $error_count مادة";
                } else {
                    $errors[] = "لم يتم تنفيذ أي عملية";
                }
            }
            
        } catch (Exception $e) {
            $mysqli1->rollback();
            $errors[] = "حدث خطأ أثناء الحفظ: " . $e->getMessage();
        }
    }
}

// Get selected specialization name if any
$selected_specialization_name = '';
if ($specialization_filter > 0) {
    $specStmt = $mysqli1->prepare("SELECT specialization_name_ar FROM specializations WHERE specialization_id = ?");
    $specStmt->bind_param('i', $specialization_filter);
    $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);
        --enroll-gradient: linear-gradient(135deg, #11998e, #38ef7d);
    }

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

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

    .enroll-header {
        background: var(--enroll-gradient);
        border-radius: 30px;
        padding: 40px;
        margin-bottom: 30px;
        box-shadow: 0 20px 60px rgba(17, 153, 142, 0.3);
        position: relative;
        overflow: hidden;
        color: white;
    }

    .enroll-header::before {
        content: '\f02d';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        position: absolute;
        bottom: -20px;
        left: -20px;
        font-size: 200px;
        opacity: 0.1;
        color: white;
        transform: rotate(-10deg);
    }

    .enroll-header h1 {
        font-size: 2.5rem;
        font-weight: 800;
        margin-bottom: 10px;
        text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
    }

    .enroll-header p {
        font-size: 1.1rem;
        opacity: 0.95;
        margin-bottom: 0;
    }

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

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

    .students-list-box {
        max-height: 400px;
        overflow-y: auto;
        border: 2px solid #e2e8f0;
        border-radius: 20px;
        padding: 10px;
    }

    .students-list-box::-webkit-scrollbar {
        width: 8px;
    }

    .students-list-box::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 10px;
    }

    .students-list-box::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        border-radius: 10px;
    }

    .student-item {
        padding: 12px 15px;
        margin-bottom: 5px;
        background: #f8fafc;
        border-radius: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
        border: 2px solid transparent;
    }

    .student-item:hover {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        color: white;
        transform: translateX(-5px);
    }

    .student-item:hover .student-item-id,
    .student-item:hover .student-item-name,
    .student-item:hover .student-item-info {
        color: white;
    }

    .student-item.selected {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        color: white;
        border-color: #11998e;
    }

    .student-item.selected .student-item-id,
    .student-item.selected .student-item-name,
    .student-item.selected .student-item-info {
        color: white;
    }

    .student-item-id {
        font-size: 0.85rem;
        color: #718096;
        font-family: monospace;
    }

    .student-item-name {
        font-weight: 600;
        color: #2d3748;
    }

    .student-item-info {
        font-size: 0.8rem;
        color: #718096;
    }

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

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

    .form-control:focus, .form-select:focus {
        border-color: #11998e;
        box-shadow: 0 0 0 4px rgba(17, 153, 142, 0.1);
        outline: none;
    }

    .btn-enroll {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        border: none;
        color: white;
        padding: 12px 35px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4);
    }

    .btn-enroll:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(17, 153, 142, 0.6);
        color: white;
    }

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

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

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

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

    .selected-student-header {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        color: white;
        border-radius: 30px;
        padding: 25px;
        margin-bottom: 25px;
        position: relative;
        overflow: hidden;
    }

    .selected-student-header::before {
        content: '\f007';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
        position: absolute;
        bottom: -20px;
        left: -20px;
        font-size: 150px;
        opacity: 0.1;
        color: white;
        transform: rotate(-5deg);
    }

    .semester-filter-card {
        background: white;
        border-radius: 30px;
        padding: 20px;
        margin-bottom: 25px;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        border-right: 5px solid #11998e;
    }

    .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 #11998e;
    }

    .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: #11998e;
        margin-left: 10px;
    }

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

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(17, 153, 142, 0.2);
    }

    .stat-icon {
        font-size: 2.2rem;
        margin-bottom: 10px;
        background: linear-gradient(135deg, #11998e, #38ef7d);
        -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;
    }

    .subjects-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 15px;
        max-height: 500px;
        overflow-y: auto;
        padding: 10px;
    }

    .subjects-grid::-webkit-scrollbar {
        width: 8px;
    }

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

    .subjects-grid::-webkit-scrollbar-thumb {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        border-radius: 10px;
    }

    .subject-card {
        background: #f8fafc;
        border-radius: 20px;
        padding: 15px;
        border: 2px solid transparent;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .subject-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(17, 153, 142, 0.2);
        border-color: #11998e;
    }

    .subject-card.enrolled {
        background: #d4edda;
        border-color: #28a745;
    }

    .subject-card.plan-subject {
        border-right: 4px solid #11998e;
    }

    .subject-card .checkbox-wrapper {
        position: absolute;
        top: 10px;
        right: 10px;
    }

    .subject-card .checkbox-wrapper input {
        transform: scale(1.3);
        cursor: pointer;
    }

    .subject-code {
        font-weight: 700;
        color: #2d3748;
        margin-bottom: 5px;
        font-size: 1.1rem;
    }

    .subject-name {
        color: #4a5568;
        margin-bottom: 10px;
        font-size: 0.95rem;
    }

    .subject-meta {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .badge-credit {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        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;
    }

    .badge-filter {
        background: #edf2f7;
        color: #4a5568;
        padding: 8px 15px;
        border-radius: 50px;
        font-size: 0.9rem;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .badge-filter.active {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        color: white;
    }

    .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, #11998e, #38ef7d);
        color: white;
        border-color: transparent;
        box-shadow: 0 4px 10px rgba(17, 153, 142, 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;
    }

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

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

    .no-results {
        text-align: center;
        padding: 40px 20px;
        background: #f8fafc;
        border-radius: 30px;
    }

    .no-results i {
        font-size: 3rem;
        color: #cbd5e0;
        margin-bottom: 15px;
    }

    .students-count {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        color: white;
        padding: 5px 15px;
        border-radius: 50px;
        font-size: 0.9rem;
        font-weight: 600;
    }

    .loading-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        justify-content: center;
        align-items: center;
        backdrop-filter: blur(5px);
    }

    .loading-spinner {
        width: 60px;
        height: 60px;
        border: 6px solid #f3f3f3;
        border-top: 6px solid #11998e;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .search-section {
        background: linear-gradient(135deg, #11998e, #38ef7d);
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 20px;
        color: white;
    }

    .search-section .form-label {
        color: white;
    }

    .search-section .form-control,
    .search-section .form-select {
        background: rgba(255, 255, 255, 0.9);
        border: none;
    }

    .plan-info-card {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        color: white;
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 25px;
        box-shadow: 0 10px 30px rgba(17, 153, 142, 0.4);
    }

    @media (max-width: 768px) {
        .enroll-header {
            padding: 25px;
        }
        .enroll-header h1 {
            font-size: 1.8rem;
        }
        .subjects-grid {
            grid-template-columns: 1fr;
        }
    }
</style>

<div class="main-wrapper" dir="rtl">
    <div class="container-fluid px-4">
        <!-- Page Header -->
        <div class="enroll-header">
            <div class="row align-items-center">
                <div class="col-lg-8">
                    <h1>
                        <i class="fas fa-book-open ms-3"></i>
                        تسجيل المقررات للطالب
                    </h1>
                    <p>اختر طالباً ثم قم بتسجيل المقررات الدراسية له حسب الخطة أو من جميع المقررات المتاحة</p>
                </div>
                <div class="col-lg-4 text-lg-start text-center mt-3 mt-lg-0">
                    <a href="subject_enrollment.php" class="btn btn-light rounded-pill px-4 py-2 me-2">
                        <i class="fas fa-users ms-2"></i>
                        تسجيل لمجموعة طلاب
                    </a>
                    <a href="student_grades.php" class="btn btn-light rounded-pill px-4 py-2">
                        <i class="fas fa-chart-line ms-2"></i>
                        إدارة التقديرات
                    </a>
                </div>
            </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; ?>

        <!-- Search and Filters Form -->
        <form method="get" action="" id="filterForm">
            <!-- Quick Search Section -->
            <div class="search-section">
                <div class="row g-3 align-items-center">
                    <div class="col-md-2">
                        <label class="form-label">بحث بـ</label>
                        <select class="form-select" name="search_type" id="search_type">
                            <option value="id" <?= $search_type === 'id' ? 'selected' : '' ?>>الرقم الجامعي</option>
                            <option value="name" <?= $search_type === 'name' ? 'selected' : '' ?>>الاسم</option>
                        </select>
                    </div>
                    <div class="col-md-8">
                        <label class="form-label">كلمة البحث</label>
                        <input type="text" 
                               class="form-control" 
                               name="search_term" 
                               id="search_term"
                               value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>"
                               placeholder="أدخل الرقم الجامعي أو اسم الطالب...">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-light w-100 rounded-pill">
                            <i class="fas fa-search ms-2"></i>
                            بحث
                        </button>
                    </div>
                </div>
            </div>

            <!-- Advanced Filters -->
            <div class="filter-card">
                <h6 class="fw-bold mb-3">
                    <i class="fas fa-filter ms-2" style="color: #11998e;"></i>
                    فلاتر إضافية
                </h6>
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">الكلية</label>
                        <select class="form-select" name="college_id" id="college_id">
                            <option value="">جميع الكليات</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?= htmlspecialchars($college['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($college_filter == $college['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($college['name'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">القسم</label>
                        <select class="form-select" name="section_id" id="section_id">
                            <option value="">جميع الأقسام</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">البرنامج</label>
                        <select class="form-select" name="program_id" id="program_id">
                            <option value="">جميع البرامج</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">التخصص</label>
                        <select class="form-select" name="specialization_id" id="specialization_id">
                            <option value="">جميع التخصصات</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">الدفعة</label>
                        <select class="form-select" name="batch_id" id="batch_id">
                            <option value="">جميع الدفعات</option>
                            <?php foreach ($batches as $batch): ?>
                                <option value="<?= htmlspecialchars($batch['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($batch_filter == $batch['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($batch['value'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3 d-flex align-items-end">
                        <a href="student_enrollment.php" class="btn-reset w-100">
                            <i class="fas fa-redo-alt ms-2"></i>
                            إعادة تعيين
                        </a>
                    </div>
                </div>
            </div>
        </form>

        <!-- Students List -->
        <?php if (!empty($students_list)): ?>
            <div class="students-list-card">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="fw-bold mb-0">
                        <i class="fas fa-users ms-2" style="color: #11998e;"></i>
                        قائمة الطلاب
                    </h5>
                    <span class="students-count">
                        <i class="fas fa-user-graduate ms-1"></i>
                        <?= count($students_list) ?> طالب
                    </span>
                </div>
                
                <div class="students-list-box">
                    <?php foreach ($students_list as $student): ?>
                        <div class="student-item <?= ($selected_student_id == $student['student_id']) ? 'selected' : '' ?>" 
                             onclick="window.location.href='?student_id=<?= urlencode($student['student_id']) ?>&college_id=<?= urlencode($college_filter) ?>&section_id=<?= urlencode($section_filter) ?>&program_id=<?= urlencode($program_filter) ?>&specialization_id=<?= $specialization_filter ?>&batch_id=<?= urlencode($batch_filter) ?>&search_term=<?= urlencode($search_term) ?>&search_type=<?= $search_type ?>&subject_source=<?= urlencode($subject_source) ?>'">
                            <div class="row">
                                <div class="col-8">
                                    <div class="student-item-name">
                                        <?= htmlspecialchars($student['student_name'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                    <div class="student-item-id">
                                        <i class="fas fa-id-card ms-1"></i>
                                        <?= htmlspecialchars($student['student_id'], ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </div>
                                <div class="col-4 text-start">
                                    <div class="student-item-info">
                                        <span class="badge bg-light text-dark"><?= $student['subjects_count'] ?> مواد</span>
                                    </div>
                                    <div class="student-item-info">
                                        <?= htmlspecialchars($student['batch_name'] ?: '', ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php elseif (!empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter) || !empty($search_term)): ?>
            <div class="students-list-card">
                <div class="no-results">
                    <i class="fas fa-user-slash"></i>
                    <h5>لا يوجد طلاب</h5>
                    <p class="text-muted">لم يتم العثور على طلاب تطابق معايير البحث</p>
                </div>
            </div>
        <?php endif; ?>

        <!-- Selected Student Details -->
        <?php if ($selected_student): ?>
            <div class="selected-student-header">
                <div class="row align-items-center">
                    <div class="col-lg-8">
                        <h4 class="mb-2">
                            <i class="fas fa-user-graduate ms-2"></i>
                            <?= htmlspecialchars($selected_student['student_name'], ENT_QUOTES, 'UTF-8') ?>
                        </h4>
                        <div class="d-flex flex-wrap gap-3">
                            <span>
                                <i class="fas fa-id-card ms-1"></i>
                                <?= htmlspecialchars($selected_student['student_id'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span>
                                <i class="fas fa-university ms-1"></i>
                                <?= htmlspecialchars($selected_student['college_name'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span>
                                <i class="fas fa-layer-group ms-1"></i>
                                <?= htmlspecialchars($selected_student['section_name'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <span>
                                <i class="fas fa-graduation-cap ms-1"></i>
                                <?= htmlspecialchars($selected_student['program_name'], ENT_QUOTES, 'UTF-8') ?>
                            </span>
                            <?php if ($selected_student['specialization_name']): ?>
                                <span>
                                    <i class="fas fa-tag ms-1"></i>
                                    <?= htmlspecialchars($selected_student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endif; ?>
                            <?php if ($selected_student['batch_name']): ?>
                                <span>
                                    <i class="fas fa-users ms-1"></i>
                                    دفعة <?= htmlspecialchars($selected_student['batch_name'], ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="col-lg-4 text-lg-start text-center mt-3 mt-lg-0">
                        <a href="?college_id=<?= urlencode($college_filter) ?>&section_id=<?= urlencode($section_filter) ?>&program_id=<?= urlencode($program_filter) ?>&specialization_id=<?= $specialization_filter ?>&batch_id=<?= urlencode($batch_filter) ?>&search_term=<?= urlencode($search_term) ?>&search_type=<?= $search_type ?>&subject_source=<?= urlencode($subject_source) ?>" class="btn btn-light rounded-pill px-4">
                            <i class="fas fa-arrow-right ms-2"></i>
                            عودة للقائمة
                        </a>
                    </div>
                </div>
            </div>

            <!-- Semester Filter -->
            <div class="semester-filter-card">
                <form method="get" action="" id="semesterForm">
                    <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="college_id" value="<?= htmlspecialchars($college_filter, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="section_id" value="<?= htmlspecialchars($section_filter, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="program_id" value="<?= htmlspecialchars($program_filter, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="specialization_id" value="<?= (int)$specialization_filter ?>">
                    <input type="hidden" name="batch_id" value="<?= htmlspecialchars($batch_filter, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="search_term" value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="search_type" value="<?= htmlspecialchars($search_type, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="subject_source" value="<?= htmlspecialchars($subject_source, ENT_QUOTES, 'UTF-8') ?>">
                    
                    <div class="row g-3 align-items-center">
                        <div class="col-md-8">
                            <label class="form-label">
                                <i class="fas fa-calendar-alt ms-1"></i>
                                اختر الفصل الدراسي للتسجيل
                            </label>
                            <select class="form-select" name="semester_id" id="semesterSelect" onchange="this.form.submit()">
                                <option value="">-- اختر الفصل --</option>
                                <?php foreach ($semesters as $sem): ?>
                                    <option value="<?= (int)$sem['id'] ?>" <?= ($semester_filter == $sem['id']) ? 'selected' : '' ?>>
                                        الفصل <?= htmlspecialchars($sem['name'], ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <?php if ($semester_filter > 0 && isset($selected_student['batch_name'])): ?>
                                <div class="semester-badge mt-4">
                                    <i class="fas fa-check-circle ms-1"></i>
                                    التسجيل في الفصل <?= htmlspecialchars($semester_filter, ENT_QUOTES, 'UTF-8') ?> - دفعة <?= htmlspecialchars($selected_student['batch_name'], ENT_QUOTES, 'UTF-8') ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
            </div>

            <?php if ($semester_filter > 0): ?>
                <!-- Subject Source Toggle -->
                <div class="source-toggle">
                    <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, #11998e, #38ef7d); 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_filter > 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>

                <!-- Enrollment Form -->
                <?php if (!empty($subjects)): ?>
                    <form method="POST" action="" id="enrollmentForm">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="semester_id" value="<?= (int)$semester_filter ?>">
                        <input type="hidden" name="batch_id" value="<?= htmlspecialchars($selected_student['batch_id'] ?? $batch_filter, ENT_QUOTES, 'UTF-8') ?>">
                        
                        <!-- Statistics Cards -->
                        <div class="row g-4 mb-4">
                            <?php
                            $total_subjects = count($subjects);
                            $enrolled_count = count($selected_subjects);
                            $available_count = $total_subjects - $enrolled_count;
                            ?>
                            <div class="col-md-4">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-book"></i>
                                    </div>
                                    <div class="stat-number"><?= $total_subjects ?></div>
                                    <div class="stat-label">إجمالي المقررات</div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-check-circle" style="color: #28a745;"></i>
                                    </div>
                                    <div class="stat-number"><?= $enrolled_count ?></div>
                                    <div class="stat-label">مقررات مسجلة</div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="stat-card">
                                    <div class="stat-icon">
                                        <i class="fas fa-plus-circle" style="color: #11998e;"></i>
                                    </div>
                                    <div class="stat-number"><?= $available_count ?></div>
                                    <div class="stat-label">متاحة للتسجيل</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Subjects Grid -->
                        <div class="content-card">
                            <div class="content-card-header">
                                <h5>
                                    <i class="fas fa-book-open ms-2"></i>
                                    اختر المقررات للتسجيل
                                </h5>
                                <div class="d-flex align-items-center gap-3">
                                    <span class="badge" style="background: linear-gradient(135deg, #11998e, #38ef7d); 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="subjects-grid">
                                <?php foreach ($subjects as $subject): ?>
                                    <?php 
                                    $isSelected = isset($selected_subjects[$subject['subjectcode']]);
                                    $isCore = isset($subject['is_core']) && $subject['is_core'];
                                    ?>
                                    <div class="subject-card <?= $isSelected ? 'enrolled' : '' ?> <?= ($subject_source === 'plan' && $isCore) ? 'plan-subject' : '' ?>" 
                                         data-subject-id="<?= (int)$subject['id'] ?>">
                                        <div class="checkbox-wrapper">
                                            <input class="form-check-input subject-checkbox" 
                                                   type="checkbox" 
                                                   name="subject_ids[]" 
                                                   value="<?= (int)$subject['id'] ?>"
                                                   id="subject_<?= (int)$subject['id'] ?>"
                                                   <?= $isSelected ? 'checked' : '' ?>>
                                        </div>
                                        <div class="subject-code">
                                            <?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                            <?php if ($isCore && $subject_source === 'plan'): ?>
                                                <span class="badge-core me-2">أساسي</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="subject-name">
                                            <?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                        <?php if (!empty($subject['subjectnamee'])): ?>
                                            <div class="subject-name text-muted small">
                                                <?= htmlspecialchars($subject['subjectnamee'], ENT_QUOTES, 'UTF-8') ?>
                                            </div>
                                        <?php endif; ?>
                                        <div class="subject-meta">
                                            <span class="badge-credit"><?= (int)($subject['credit_hours'] ?? 0) ?> ساعة</span>
                                            <?php if ($isSelected): ?>
                                                <span class="badge-enrolled">
                                                    <i class="fas fa-check-circle me-1"></i> مسجل
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        
                        <!-- Submit Button -->
                        <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" id="selectedSubjectsText">0</span> مقرر للتسجيل
                                            </p>
                                        </div>
                                        <button type="submit" name="enroll_student" class="btn-enroll 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>
                    </form>
                    
                    <!-- Currently Enrolled Subjects (for cancellation) -->
                    <?php if (!empty($selected_subjects)): ?>
                        <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($selected_subjects) ?> تسجيل
                                        </span>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-hover enrolled-table">
                                            <thead>
                                                <tr>
                                                    <th>كود المادة</th>
                                                    <th>اسم المادة</th>
                                                    <th>الدفعة</th>
                                                    <th>الإجراءات</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($subjects as $subject): ?>
                                                    <?php if (isset($selected_subjects[$subject['subjectcode']])): ?>
                                                        <?php 
                                                        $cancelUrl = "student_enrollment.php?" . http_build_query([
                                                            'student_id' => $selected_student_id,
                                                            'college_id' => $college_filter,
                                                            'section_id' => $section_filter,
                                                            'program_id' => $program_filter,
                                                            'specialization_id' => $specialization_filter,
                                                            'batch_id' => $selected_student['batch_id'] ?? $batch_filter,
                                                            'semester_id' => $semester_filter,
                                                            'search_term' => $search_term,
                                                            'search_type' => $search_type,
                                                            'subject_source' => $subject_source,
                                                            'action' => 'cancel',
                                                            'subjectcode' => $subject['subjectcode']
                                                        ]);
                                                        ?>
                                                        <tr>
                                                            <td><strong><?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?></strong></td>
                                                            <td><?= htmlspecialchars($subject['subjectnamea'], ENT_QUOTES, 'UTF-8') ?></td>
                                                            <td><?= htmlspecialchars($selected_student['batch_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                                                            <td>
                                                                <a href="<?= htmlspecialchars($cancelUrl, ENT_QUOTES, 'UTF-8') ?>" 
                                                                   class="btn-cancel"
                                                                   onclick="return confirm('هل أنت متأكد من إلغاء تسجيل المادة <?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>؟')">
                                                                    <i class="fas fa-trash-alt me-1"></i>إلغاء
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                <?php else: ?>
                    <!-- No subjects message -->
                    <div class="content-card">
                        <div class="no-results">
                            <i class="fas fa-book-open"></i>
                            <h5>لا توجد مقررات</h5>
                            <p class="text-muted mb-4">
                                <?php if ($subject_source === 'plan' && !$plan_info): ?>
                                    لا توجد خطة دراسية مرتبطة بهذه الدفعة
                                <?php else: ?>
                                    لا توجد مقررات متاحة للفصل المحدد
                                <?php endif; ?>
                            </p>
                            <?php if ($subject_source === 'plan' && !$plan_info): ?>
                                <a href="?<?= http_build_query(array_merge($_GET, ['subject_source' => 'all'])) ?>" class="btn-enroll">
                                    <i class="fas fa-list ms-2"></i>
                                    عرض جميع المقررات
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php elseif ($selected_student): ?>
                <!-- No semester selected message -->
                <div class="content-card">
                    <div class="no-results">
                        <i class="fas fa-calendar-alt"></i>
                        <h5>اختر الفصل الدراسي</h5>
                        <p class="text-muted mb-4">الرجاء اختيار الفصل الدراسي لتسجيل المقررات</p>
                    </div>
                </div>
            <?php endif; ?>
            
        <?php elseif (empty($students_list) && empty($selected_student) && (empty($college_filter) && empty($section_filter) && empty($program_filter) && empty($specialization_filter) && empty($batch_filter) && empty($search_term))): ?>
            <!-- Initial State -->
            <div class="content-card">
                <div class="no-results">
                    <i class="fas fa-search"></i>
                    <h5>ابحث عن طالب</h5>
                    <p class="text-muted">يمكنك البحث بالرقم الجامعي أو الاسم، أو استخدام الفلاتر لعرض قائمة الطلاب</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></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>
// Load sections based on college
function loadSections(collegeId, selectedSection = '') {
    if (!collegeId) {
        $('#section_id').html('<option value="">جميع الأقسام</option>');
        return;
    }
    
    $.ajax({
        url: 'ajax/get_sections.php',
        method: 'GET',
        data: { college_id: collegeId },
        dataType: 'json',
        success: function(sections) {
            let options = '<option value="">جميع الأقسام</option>';
            sections.forEach(function(section) {
                const selected = (section.id == selectedSection) ? 'selected' : '';
                options += `<option value="${section.id}" ${selected}>${section.name}</option>`;
            });
            $('#section_id').html(options);
        },
        error: function(xhr, status, error) {
            console.error('Error loading sections:', error);
        }
    });
}

// Load programs based on college
function loadPrograms(collegeId, selectedProgram = '') {
    if (!collegeId) {
        $('#program_id').html('<option value="">جميع البرامج</option>');
        return;
    }
    
    $.ajax({
        url: 'ajax/get_programs.php',
        method: 'GET',
        data: { college_id: collegeId },
        dataType: 'json',
        success: function(programs) {
            let options = '<option value="">جميع البرامج</option>';
            programs.forEach(function(program) {
                const selected = (program.id == selectedProgram) ? 'selected' : '';
                options += `<option value="${program.id}" ${selected}>${program.name}</option>`;
            });
            $('#program_id').html(options);
        },
        error: function(xhr, status, error) {
            console.error('Error loading programs:', error);
        }
    });
}

// Load specializations based on section and program
function loadSpecializations(sectionId, programId, selectedSpecialization = 0) {
    if (!sectionId || !programId) {
        $('#specialization_id').html('<option value="">جميع التخصصات</option>');
        return;
    }
    
    $.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>';
            specializations.forEach(function(spec) {
                const selected = (spec.specialization_id == selectedSpecialization) ? 'selected' : '';
                options += `<option value="${spec.specialization_id}" ${selected}>${spec.specialization_name_ar}</option>`;
            });
            $('#specialization_id').html(options);
        },
        error: function(xhr, status, error) {
            console.error('Error loading specializations:', error);
        }
    });
}

// Auto-submit form when any filter changes
function setupAutoSubmit() {
    $('#college_id, #section_id, #program_id, #specialization_id, #batch_id, #search_type').on('change', function() {
        $('#filterForm').submit();
    });
    
    // Debounced search for text input
    let searchTimeout;
    let lastSearchValue = $('#search_term').val();
    
    $('#search_term').on('keyup', function() {
        const currentValue = $(this).val();
        
        if (currentValue === lastSearchValue) {
            return;
        }
        
        lastSearchValue = currentValue;
        clearTimeout(searchTimeout);
        
        const delay = (currentValue.length < 3) ? 1000 : 500;
        
        searchTimeout = setTimeout(function() {
            if ($('#search_term').val() === currentValue) {
                $('#filterForm').submit();
            }
        }, delay);
    });
    
    $('#search_term').on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            clearTimeout(searchTimeout);
            $('#filterForm').submit();
        }
    });
}

// Update counters
function updateCounters() {
    const selectedSubjects = $('.subject-checkbox:checked').length;
    $('#selectedSubjectsCount').text(selectedSubjects);
    $('#selectedSubjectsText').text(selectedSubjects);
    
    const totalSubjects = $('.subject-checkbox').length;
    $('#selectAllSubjects').prop('checked', totalSubjects > 0 && selectedSubjects === totalSubjects);
    
    // Update subject card styles
    $('.subject-card').removeClass('selected');
    $('.subject-checkbox:checked').each(function() {
        $(this).closest('.subject-card').addClass('selected');
    });
}

$(document).ready(function() {
    // Initialize dependent dropdowns
    const collegeId = $('#college_id').val();
    if (collegeId) {
        loadSections(collegeId, '<?= $section_filter ?>');
        loadPrograms(collegeId, '<?= $program_filter ?>');
        
        const sectionId = '<?= $section_filter ?>';
        const programId = '<?= $program_filter ?>';
        if (sectionId && programId) {
            loadSpecializations(sectionId, programId, <?= $specialization_filter ?>);
        }
    }
    
    // College change event
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        loadSections(collegeId, '');
        loadPrograms(collegeId, '');
        $('#specialization_id').html('<option value="">جميع التخصصات</option>');
    });
    
    // Section and Program change events
    $('#section_id, #program_id').on('change', function() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            loadSpecializations(sectionId, programId, 0);
        }
    });
    
    // Setup auto-submit for filters
    setupAutoSubmit();
    
    // Select all subjects
    $('#selectAllSubjects').on('change', function() {
        const isChecked = $(this).prop('checked');
        $('.subject-checkbox').prop('checked', isChecked);
        updateCounters();
    });
    
    // Individual subject checkbox
    $(document).on('change', '.subject-checkbox', updateCounters);
    
    // Initialize counters
    updateCounters();
    
    // Form validation
    $('#enrollmentForm').on('submit', function(e) {
        const selectedSubjects = $('.subject-checkbox:checked').length;
        
        if (selectedSubjects === 0) {
            e.preventDefault();
            alert('الرجاء اختيار مادة واحدة على الأقل');
            return false;
        }
        
        const enrolledSubjects = $('.subject-card.enrolled .subject-checkbox:checked').length;
        const newSubjects = selectedSubjects - enrolledSubjects;
        
        let message = `هل أنت متأكد من تسجيل ${selectedSubjects} مادة للطالب؟`;
        if (enrolledSubjects > 0) {
            message += `\n\n${enrolledSubjects} مادة مسجلة مسبقاً سيتم تحديثها`;
            if (newSubjects > 0) {
                message += `\n${newSubjects} مادة جديدة سيتم تسجيلها`;
            }
        }
        
        if (!confirm(message)) {
            e.preventDefault();
            return false;
        }
        
        $('#loadingOverlay').fadeIn();
        return true;
    });
    
    // Auto-hide alerts
    setTimeout(function() {
        $('.alert').fadeOut(500, function() {
            $(this).remove();
        });
    }, 5000);
});
</script>

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