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

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

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

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

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

// Validate integer with range
function validateInt($value, $min = 0, $max = PHP_INT_MAX) {
    $int = (int)$value;
    return ($int >= $min && $int <= $max) ? $int : 0;
}

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

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

// Handle bulk delete enrolled subjects
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete_enrolled'])) {
    header('Content-Type: application/json');
    
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        echo json_encode(['success' => false, 'message' => 'طلب غير مصرح به']);
        exit();
    }
    
    $semester_id = validateInt($_POST['semester_id'] ?? 0, 1);
    $batch_id = validateInt($_POST['batch_id'] ?? 0, 1);
    $delete_items = isset($_POST['delete_items']) ? json_decode($_POST['delete_items'], true) : [];
    
    if (empty($semester_id) || empty($batch_id) || empty($delete_items)) {
        echo json_encode(['success' => false, 'message' => 'الرجاء تحديد المقررات المراد حذفها']);
        exit();
    }
    
    $success_count = 0;
    $error_count = 0;
    
    $mysqli1->begin_transaction();
    
    try {
        $deleteStmt = $mysqli1->prepare("
            DELETE FROM studentsubjects 
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ?
        ");
        
        foreach ($delete_items as $item) {
            $student_id = sanitizeInput($item['student_id'] ?? '', 'student_id');
            $subjectcode = sanitizeInput($item['subjectcode'] ?? '', 'subjectcode');
            
            if (empty($student_id) || empty($subjectcode)) {
                $error_count++;
                continue;
            }
            
            $deleteStmt->bind_param('ssii', $student_id, $subjectcode, $semester_id, $batch_id);
            if ($deleteStmt->execute()) {
                $success_count++;
            } else {
                $error_count++;
            }
        }
        $deleteStmt->close();
        
        $mysqli1->commit();
        
        echo json_encode([
            'success' => true,
            'success_count' => $success_count,
            'error_count' => $error_count,
            'message' => "✅ تم حذف $success_count مقرر" . ($error_count > 0 ? " (فشل في $error_count)" : ""),
            'clear_selection' => true
        ]);
        
    } catch (Exception $e) {
        $mysqli1->rollback();
        echo json_encode(['success' => false, 'message' => 'حدث خطأ أثناء عملية الحذف: ' . $e->getMessage()]);
    }
    exit();
}

// Get filter data for dropdowns - SECURE QUERIES
$colleges = [];
$result = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    $colleges = $result->fetch_all(MYSQLI_ASSOC);
}

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

$all_sections = [];
$result = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    $all_sections = $result->fetch_all(MYSQLI_ASSOC);
}

$batches = [];
$result = $mysqli1->query("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value");
if ($result) {
    $batches = $result->fetch_all(MYSQLI_ASSOC);
}

$semesters = [];
$result = $mysqli1->query("SELECT id, name FROM semesters WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    $semesters = $result->fetch_all(MYSQLI_ASSOC);
}

// Get subject types from database - SECURE QUERY
$subjectTypes = [];
$result = $mysqli1->query("SELECT id, name FROM subjecttypes WHERE deleted_at IS NULL ORDER BY id");
if ($result) {
    $subjectTypes = $result->fetch_all(MYSQLI_ASSOC);
}

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

// Handle subject type persistence
$selected_subjecttype_id = validateInt($_GET['subjecttype_id'] ?? 0);
if ($selected_subjecttype_id <= 0 && isset($_POST['subjecttype_id'])) {
    $selected_subjecttype_id = validateInt($_POST['subjecttype_id']);
}
if ($selected_subjecttype_id <= 0 && isset($_SESSION['last_subjecttype_id'])) {
    $selected_subjecttype_id = validateInt($_SESSION['last_subjecttype_id']);
}
if ($selected_subjecttype_id > 0) {
    $_SESSION['last_subjecttype_id'] = $selected_subjecttype_id;
}

// 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 - SECURE VALIDATION
$college_id = isset($_GET['college_id']) && ctype_digit($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$section_id = isset($_GET['section_id']) && ctype_digit($_GET['section_id']) ? (int)$_GET['section_id'] : 0;
$program_id = isset($_GET['program_id']) && ctype_digit($_GET['program_id']) ? (int)$_GET['program_id'] : 0;
$specialization_id = isset($_GET['specialization_id']) && ctype_digit($_GET['specialization_id']) ? (int)$_GET['specialization_id'] : 0;
$batch_id = isset($_GET['batch_id']) && ctype_digit($_GET['batch_id']) ? (int)$_GET['batch_id'] : 0;
$semester_id = isset($_GET['semester_id']) && ctype_digit($_GET['semester_id']) ? (int)$_GET['semester_id'] : 0;
$subject_source = isset($_GET['subject_source']) && in_array($_GET['subject_source'], ['plan', 'all']) ? $_GET['subject_source'] : 'plan';

// Handle edit action (update subject type) - NON-AJAX VERSION (WITH PAGE RELOAD)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_action']) && $_POST['edit_action'] === 'update_type') {
    // CSRF Protection
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $errors[] = 'طلب غير مصرح به. يرجى تحديث الصفحة والمحاولة مرة أخرى.';
    } else {
        $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
        $subjectcode = sanitizeInput($_POST['subjectcode'] ?? '', 'subjectcode');
        $new_subjecttype_id = validateInt($_POST['new_subjecttype_id'] ?? 0, 1);
        $semester_id = validateInt($_POST['semester_id'] ?? 0, 1);
        $batch_id = validateInt($_POST['batch_id'] ?? 0, 1);
        
        if (empty($student_id) || empty($subjectcode) || $new_subjecttype_id <= 0 || $semester_id <= 0 || $batch_id <= 0) {
            $errors[] = 'بيانات غير صالحة للتعديل';
        } else {
            // Get credit hours from subjects table
            $creditStmt = $mysqli1->prepare("SELECT credit_hours FROM subjects WHERE subjectcode = ? AND deleted_at IS NULL");
            $creditStmt->bind_param('s', $subjectcode);
            $creditStmt->execute();
            $creditResult = $creditStmt->get_result()->fetch_assoc();
            $credit_hours = $creditResult['credit_hours'] ?? 3.00;
            $creditStmt->close();
            
            $updateStmt = $mysqli1->prepare("
                UPDATE studentsubjects 
                SET subjecttype_id = ?,
                    credit_hours = ?,
                    updated_at = NOW()
                WHERE student_id = ? 
                AND subjectcode = ? 
                AND semester_id = ? 
                AND batch_id = ?
            ");
            
            $updateStmt->bind_param('idssii', $new_subjecttype_id, $credit_hours, $student_id, $subjectcode, $semester_id, $batch_id);
            
            if ($updateStmt->execute()) {
                $success_message = "✅ تم تحديث نوع التسجيل بنجاح";
            } else {
                $errors[] = "❌ حدث خطأ أثناء تحديث نوع التسجيل";
            }
            $updateStmt->close();
        }
    }
    
    // إعادة التوجيه إلى نفس الصفحة مع الحفاظ على المعاملات
    $redirectParams = [
        '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,
        'clear_selection' => 1
    ];
    
    header("Location: subject_enrollment.php?" . http_build_query($redirectParams));
    exit();
}

// Handle enrollment submission - WITH DETAILED STATISTICS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enroll_students'])) {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $errors[] = "طلب غير مصرح به. يرجى تحديث الصفحة والمحاولة مرة أخرى.";
    } else {
        $semester_id = validateInt($_POST['semester_id'] ?? 0, 1);
        $batch_id = validateInt($_POST['batch_id'] ?? 0, 1);
        $subject_ids = isset($_POST['subject_ids']) ? array_map('intval', $_POST['subject_ids']) : [];
        $subject_ids = array_filter($subject_ids, function($id) { return $id > 0; });
        $subjecttype_id = validateInt($_POST['subjecttype_id'] ?? 0, 1);
        
        if (empty($semester_id)) {
            $errors[] = 'الرجاء اختيار الفصل الدراسي';
        }
        if (empty($batch_id)) {
            $errors[] = 'الرجاء اختيار الدفعة';
        }
        if (empty($subject_ids)) {
            $errors[] = 'الرجاء اختيار مقرر واحد على الأقل';
        }
        if ($subjecttype_id <= 0) {
            $errors[] = 'نوع التسجيل غير صالح - الرجاء اختيار نوع التسجيل من القائمة';
        }
        
        $student_ids = isset($_POST['student_ids']) ? array_map('sanitizeInput', $_POST['student_ids']) : [];
        $student_ids = array_filter($student_ids, function($id) { return !empty($id); });
        
        if (empty($student_ids)) {
            $errors[] = 'الرجاء اختيار طالب واحد على الأقل';
        }
        
        if (empty($errors)) {
            $insert_count = 0;
            $update_count = 0;
            $error_count = 0;
            $insert_details = [];
            $update_details = [];
            $error_details = [];
            
            $mysqli1->begin_transaction();
            
            try {
                $subjectStmt = $mysqli1->prepare("SELECT subjectcode, credit_hours, subjectnamea FROM subjects WHERE id = ? AND deleted_at IS NULL");
                $checkStmt = $mysqli1->prepare("
                    SELECT id, subjecttype_id, credit_hours, deleted_at FROM studentsubjects 
                    WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ?
                ");
                $updateStmt = $mysqli1->prepare("
                    UPDATE studentsubjects 
                    SET subjecttype_id = ?, credit_hours = ?, updated_at = NOW(), deleted_at = NULL
                    WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND batch_id = ?
                ");
                $insertStmt = $mysqli1->prepare("
                    INSERT INTO studentsubjects 
                    (subjectcode, student_id, semester_id, batch_id, subjecttype_id, credit_hours, weight, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, 100.00, NOW(), NOW())
                ");
                
                foreach ($student_ids as $student_id) {
                    $studentNameStmt = $mysqli1->prepare("SELECT student_name FROM students WHERE student_id = ?");
                    $studentNameStmt->bind_param('s', $student_id);
                    $studentNameStmt->execute();
                    $studentName = $studentNameStmt->get_result()->fetch_assoc()['student_name'] ?? $student_id;
                    $studentNameStmt->close();
                    
                    foreach ($subject_ids as $subject_id) {
                        $subjectStmt->bind_param('i', $subject_id);
                        $subjectStmt->execute();
                        $subjectResult = $subjectStmt->get_result()->fetch_assoc();
                        $subjectcode = $subjectResult['subjectcode'] ?? '';
                        $credit_hours = $subjectResult['credit_hours'] ?? 3.00;
                        $subjectname = $subjectResult['subjectnamea'] ?? $subjectcode;
                        
                        if (!$subjectcode) {
                            $error_count++;
                            $error_details[] = "$subjectname (كود غير موجود)";
                            continue;
                        }
                        
                        $checkStmt->bind_param('ssii', $student_id, $subjectcode, $semester_id, $batch_id);
                        $checkStmt->execute();
                        $existing = $checkStmt->get_result()->fetch_assoc();
                        
                        if ($existing) {
                            // UPDATE existing enrollment (restore if deleted)
                            $updateStmt->bind_param('idssii', $subjecttype_id, $credit_hours, $student_id, $subjectcode, $semester_id, $batch_id);
                            if ($updateStmt->execute()) {
                                $update_count++;
                                $update_details[] = "$subjectname لـ $studentName";
                            } else {
                                $error_count++;
                                $error_details[] = "$subjectname لـ $studentName (تحديث)";
                            }
                        } else {
                            // INSERT new enrollment
                            $insertStmt->bind_param('ssiiid', $subjectcode, $student_id, $semester_id, $batch_id, $subjecttype_id, $credit_hours);
                            if ($insertStmt->execute()) {
                                $insert_count++;
                                $insert_details[] = "$subjectname لـ $studentName";
                            } else {
                                $error_count++;
                                $error_details[] = "$subjectname لـ $studentName (إضافة)";
                            }
                        }
                    }
                }
                
                $subjectStmt->close();
                $checkStmt->close();
                $updateStmt->close();
                $insertStmt->close();
                
                $mysqli1->commit();
                
                if ($insert_count > 0 || $update_count > 0) {
                    $_SESSION['last_subjecttype_id'] = $subjecttype_id;
                    
                    // إعادة التوجيه مع معامل clear_selection
                    $redirectParams = [
                        '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,
                        'clear_selection' => 1,
                        'success_insert' => $insert_count,
                        'success_update' => $update_count,
                        'success_error' => $error_count
                    ];
                    
                    header("Location: subject_enrollment.php?" . http_build_query($redirectParams));
                    exit();
                } else {
                    $errors[] = "لم يتم تنفيذ أي عملية";
                }
                
            } catch (Exception $e) {
                $mysqli1->rollback();
                $errors[] = "حدث خطأ أثناء الحفظ: " . $e->getMessage();
            }
        }
    }
}

// Build success message from GET parameters
if (isset($_GET['success_insert']) || isset($_GET['success_update'])) {
    $insert_count = isset($_GET['success_insert']) ? (int)$_GET['success_insert'] : 0;
    $update_count = isset($_GET['success_update']) ? (int)$_GET['success_update'] : 0;
    $error_count = isset($_GET['success_error']) ? (int)$_GET['success_error'] : 0;
    
    if ($insert_count > 0 || $update_count > 0) {
        $success_message = "<div class='enrollment-stats'>";
        $success_message .= "<strong>✅ تمت عملية التسجيل بنجاح</strong><br>";
        $success_message .= "<div class='stats-details mt-2'>";
        
        if ($insert_count > 0) {
            $success_message .= "📚 <strong class='text-success'>تسجيلات جديدة:</strong> $insert_count مقرر<br>";
        }
        
        if ($update_count > 0) {
            $success_message .= "🔄 <strong class='text-warning'>تحديثات نوع التسجيل:</strong> $update_count مقرر<br>";
        }
        
        if ($error_count > 0) {
            $success_message .= "❌ <strong class='text-danger'>فشل:</strong> $error_count حالة<br>";
        }
        
        $success_message .= "</div></div>";
    }
}

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

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

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

include 'header.php';
?>

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل المقررات للطلاب</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { text-align: right; direction: rtl; }
        body { font-family: 'Cairo', sans-serif; background-color: #f8fafc; min-height: 100vh; }
        .main-wrapper { padding: 30px 20px; }
        
        .page-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border-radius: 30px;
            padding: 30px 40px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            color: white;
            position: relative;
            overflow: hidden;
        }
        .page-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: rotate 20s linear infinite;
        }
        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        .page-header h1 { font-size: 2.2rem; font-weight: 800; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3); position: relative; z-index: 2; text-align: right; }
        .page-header p { font-size: 1rem; margin-top: 5px; opacity: 0.9; position: relative; z-index: 2; text-align: right; }
        
        .btn-gradient {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 176, 155, 0.4);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-gradient:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6); color: white; }
        
        .btn-danger-gradient {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(231, 76, 60, 0.4);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-danger-gradient:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(231, 76, 60, 0.6); color: white; }
        
        .btn-outline-gradient {
            background: transparent;
            border: 2px solid rgba(255, 255, 255, 0.5);
            color: white;
            padding: 10px 25px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-outline-gradient:hover { background: rgba(255, 255, 255, 0.2); color: white; transform: translateY(-2px); }
        
        .btn-reset {
            background: linear-gradient(135deg, #6b7280, #4b5563);
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .filter-card {
            background: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
        }
        
        .form-label { font-weight: 600; color: #2d3748; margin-bottom: 8px; font-size: 0.95rem; text-align: right; }
        .required-field::after { content: " *"; color: #e53e3e; }
        
        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 10px 15px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            text-align: right;
            background-position: left 0.75rem center !important;
            padding-right: 0.75rem !important;
            padding-left: 2rem !important;
        }
        .form-control:focus, .form-select:focus { border-color: #667eea; box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1); outline: none; }
        
        .content-card {
            background: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            border-right: 5px solid #667eea;
        }
        
        .content-card-header {
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 15px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .content-card-header h5 { font-weight: 700; color: #2d3748; margin: 0; text-align: right; }
        .content-card-header h5 i { color: #667eea; margin-left: 10px; }
        
        .scrollable-area {
            max-height: 400px;
            overflow-y: auto;
            padding: 10px;
            background: #f8fafc;
            border-radius: 20px;
        }
        
        .student-item, .subject-item {
            background: white;
            border-radius: 15px;
            padding: 12px 15px;
            margin-bottom: 8px;
            border: 2px solid transparent;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            text-align: right;
            cursor: pointer;
        }
        .student-item:hover, .subject-item:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .student-item.selected, .subject-item.selected { background: #e3f2fd; border-color: #2196f3; }
        .student-item.enrolled, .subject-item.enrolled { background: #d4edda; border-color: #28a745; }
        .subject-item.will-update { background: #fff3cd; border-color: #ffc107; }
        
        .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;
        }
        .badge-update {
            background: linear-gradient(135deg, #ffc107, #ff9800);
            color: #1e4620;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .plan-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
            text-align: right;
        }
        
        .source-toggle {
            background: #f8fafc;
            border-radius: 15px;
            padding: 15px;
            margin-top: 15px;
            border: 1px solid #e2e8f0;
        }
        
        .btn-toggle {
            background: white;
            border: 2px solid #e2e8f0;
            color: #4a5568;
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-toggle.active {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border-color: transparent;
            box-shadow: 0 4px 10px rgba(102, 126, 234, 0.3);
        }
        
        .btn-edit {
            background: linear-gradient(135deg, #4a90e2, #357abd);
            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-edit:hover { transform: translateY(-2px); background: linear-gradient(135deg, #357abd, #2c6ea3); color: white; }
        
        .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); background: linear-gradient(135deg, #c0392b, #a93226); color: white; }
        
        .stat-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 25px;
            padding: 25px 20px;
            text-align: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            height: 100%;
        }
        
        .alert {
            border-radius: 20px;
            border: none;
            padding: 20px 30px;
            font-weight: 600;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.5s ease;
            margin-bottom: 25px;
            text-align: right;
        }
        @keyframes slideIn {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        .alert-success {
            background: linear-gradient(135deg, #dcfce7, #bbf7d0);
            color: #166534;
            border-right: 4px solid #22c55e;
        }
        .alert-danger {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #991b1b;
            border-right: 4px solid #ef4444;
        }
        
        .enrollment-stats {
            background: linear-gradient(135deg, #f0fdf4, #dcfce7);
            padding: 15px 20px;
            border-radius: 16px;
            border-right: 4px solid #22c55e;
        }
        .enrollment-stats .stats-details { font-size: 0.9rem; }
        .enrollment-stats .text-success { color: #16a34a !important; }
        .enrollment-stats .text-warning { color: #eab308 !important; }
        .enrollment-stats .text-danger { color: #dc2626 !important; }
        
        .active-filters {
            background: #f8fafc;
            border-radius: 15px;
            padding: 15px;
            margin-top: 15px;
            border: 1px solid #e2e8f0;
        }
        
        .filter-badge {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 5px 12px;
            border-radius: 50px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .enrolled-table {
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .enrolled-table th, .enrolled-table td { text-align: right; }
        
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 10000;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(3px);
        }
        .loading-spinner {
            width: 60px;
            height: 60px;
            border: 6px solid #f3f3f3;
            border-top: 6px solid #f5576c;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .toast-notification {
            position: fixed;
            top: 20px;
            left: 20px;
            right: auto;
            z-index: 9999;
            min-width: 300px;
            animation: slideInRight 0.5s ease;
        }
        
        .me-1 { margin-left: 0.25rem !important; margin-right: 0 !important; }
        .me-2 { margin-left: 0.5rem !important; margin-right: 0 !important; }
        .me-3 { margin-left: 1rem !important; margin-right: 0 !important; }
        .ms-1 { margin-right: 0.25rem !important; margin-left: 0 !important; }
        .ms-2 { margin-right: 0.5rem !important; margin-left: 0 !important; }
        .ms-3 { margin-right: 1rem !important; margin-left: 0 !important; }
        
        @media (max-width: 768px) {
            .page-header { padding: 20px; }
            .page-header h1 { font-size: 1.8rem; }
            .content-card-header { flex-direction: column; align-items: flex-start; }
        }
        
        .text-start { text-align: left !important; }
        .text-end { text-align: right !important; }
        ul { padding-right: 20px; }
        .list-group-item { text-align: right; }
        .subject-type-select { max-width: 250px; }
        
        .type-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .type-1 { background: linear-gradient(135deg, #28a745, #20c997); color: white; }
        .type-2 { background: linear-gradient(135deg, #dc3545, #c82333); color: white; }
        .type-3 { background: linear-gradient(135deg, #ffc107, #e0a800); color: #1e4620; }
        .type-4 { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .type-5 { background: linear-gradient(135deg, #6f42c1, #5a32a3); color: white; }
        .type-6 { background: linear-gradient(135deg, #fd7e14, #e36209); color: white; }

        #studentSearch, #subjectSearch {
            border-radius: 25px;
            padding: 8px 15px;
            font-size: 0.85rem;
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }
        #studentSearch:focus, #subjectSearch:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            outline: none;
        }
        
        .student-item[style*="display: none"], .subject-item[style*="display: none"] { display: none !important; }
        
        .scrollable-area::-webkit-scrollbar { width: 6px; }
        .scrollable-area::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
        .scrollable-area::-webkit-scrollbar-thumb { background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 10px; }
        .scrollable-area::-webkit-scrollbar-thumb:hover { background: linear-gradient(135deg, #5a67d8, #6b46a0); }
        
        code { direction: ltr; display: inline-block; }
        
        .modal-content { border-radius: 20px; border: none; }
        .modal-header { border-radius: 20px 20px 0 0; padding: 20px; }
        .modal-body { padding: 25px; }
        .modal-footer { border-top: 1px solid #e2e8f0; padding: 20px; }
        
        .form-check-input { cursor: pointer; }
        .form-check-label { cursor: pointer; }
        button:disabled, .btn:disabled { opacity: 0.6; cursor: not-allowed; }
    </style>
</head>
<body>
<div class="main-wrapper">
    <div class="container-fluid px-4">
        <!-- Page Header -->
        <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
            <div>
                <h1 class="mb-2"><i class="fas fa-user-graduate ms-3"></i> تسجيل المقررات للطلاب</h1>
                <p class="mb-0"><i class="fas fa-layer-group ms-2"></i> تسجيل المقررات الدراسية للطلاب حسب الخطة الدراسية المرتبطة بالدفعة</p>
            </div>
            <div class="d-flex gap-3 mt-3 mt-md-0">
                <a href="admin_dashboard.php" class="btn-outline-gradient"><i class="fas fa-arrow-right ms-2"></i> العودة للوحة التحكم</a>
            </div>
        </div>

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

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

        <!-- Loading Overlay -->
        <div class="loading-overlay" id="loadingOverlay">
            <div class="loading-spinner"></div>
            <div class="mt-3 text-white">جاري المعالجة...</div>
        </div>

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

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

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #667eea, #764ba2); color: white;">
                <h5 class="modal-title" id="editModalLabel"><i class="fas fa-edit me-2"></i> تعديل نوع التسجيل</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="" id="editEnrollmentForm">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
                <input type="hidden" name="edit_action" value="update_type">
                <input type="hidden" name="college_id" value="<?= (int)$college_id ?>">
                <input type="hidden" name="section_id" value="<?= (int)$section_id ?>">
                <input type="hidden" name="program_id" value="<?= (int)$program_id ?>">
                <input type="hidden" name="specialization_id" value="<?= (int)$specialization_id ?>">
                <input type="hidden" name="batch_id" value="<?= (int)$batch_id ?>">
                <input type="hidden" name="semester_id" value="<?= (int)$semester_id ?>">
                <input type="hidden" name="subject_source" value="<?= htmlspecialchars($subject_source) ?>">
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-bold"><i class="fas fa-user-graduate me-1"></i> الطالب</label>
                        <input type="text" id="edit_student_name" class="form-control" readonly disabled>
                        <input type="hidden" id="edit_student_id" name="student_id">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold"><i class="fas fa-book me-1"></i> المقرر</label>
                        <input type="text" id="edit_subject_name" class="form-control" readonly disabled>
                        <input type="hidden" id="edit_subject_code" name="subjectcode">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold required-field"><i class="fas fa-tag me-1"></i> نوع التسجيل الحالي</label>
                        <div class="mb-2"><span id="current_type_badge" class="type-badge"></span></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold required-field"><i class="fas fa-exchange-alt me-1"></i> تغيير نوع التسجيل إلى</label>
                        <select class="form-select" name="new_subjecttype_id" id="new_subjecttype_id" required>
                            <option value="">اختر نوع التسجيل الجديد</option>
                            <?php foreach ($subjectTypes as $type): ?>
                                <option value="<?= (int)$type['id'] ?>"><?= htmlspecialchars($type['name'], ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted">اختر نوع التسجيل الجديد للمقرر</small>
                    </div>
                    
                    <div class="alert alert-info mt-3"><i class="fas fa-info-circle me-2"></i> <strong>ملاحظة:</strong> سيتم تحديث نوع التسجيل للمقرر المحدد مع الاحتفاظ بجميع البيانات الأخرى.</div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><i class="fas fa-times me-1"></i> إلغاء</button>
                    <button type="submit" class="btn-gradient" id="confirmEditBtn"><i class="fas fa-save me-1"></i> حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </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() {
    function showLoadingOverlay(show) {
        if (show) { $('#loadingOverlay').fadeIn(200); } 
        else { $('#loadingOverlay').fadeOut(200); }
    }

    function showToast(type, message) {
        $('.toast-notification').remove();
        const icon = type === 'success' ? 'fa-check-circle' : (type === 'warning' ? 'fa-exclamation-triangle' : 'fa-times-circle');
        const bgClass = type === 'success' ? 'alert-success' : (type === 'warning' ? 'alert-warning' : 'alert-danger');
        const toastHtml = `<div class="alert ${bgClass} toast-notification" role="alert" style="position: fixed; top: 20px; left: 20px; right: auto; z-index: 9999; min-width: 300px; animation: slideInRight 0.5s ease;">
            <i class="fas ${icon} ms-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>`;
        $('body').append(toastHtml);
        setTimeout(function() { $('.toast-notification').fadeOut(500, function() { $(this).remove(); }); }, 3000);
    }

    // Clear all selections function
    function clearAllSelections() {
        $('.student-checkbox').prop('checked', false);
        $('.subject-checkbox').prop('checked', false);
        $('#masterStudentCheckbox').prop('checked', false);
        $('#selectAllSubjects').prop('checked', false);
        updateCounters();
        console.log('✅ تم إلغاء تحديد جميع الطلاب والمقررات');
    }

    // Clear selections button
    $('#clearAllSelectionsBtn').on('click', function() {
        clearAllSelections();
        showToast('info', '✅ تم إلغاء تحديد جميع الطلاب والمقررات');
    });

    // Bulk Delete Enrolled Subjects
    $('#bulkDeleteEnrolledBtn').on('click', function() {
        const enrolledItems = [];
        $('#enrolledSubjectsTableBody tr').each(function() {
            const $row = $(this);
            const studentId = $row.find('td:eq(0) code').text();
            const studentName = $row.find('td:eq(1)').text();
            const subjectCode = $row.find('td:eq(2) strong').text();
            
            enrolledItems.push({
                student_id: studentId,
                student_name: studentName,
                subjectcode: subjectCode
            });
        });
        
        if (enrolledItems.length === 0) {
            showToast('warning', '⚠️ لا توجد مقررات مسجلة حالياً للحذف');
            return;
        }
        
        let message = '═══════════════════════════════════════\n';
        message += '            ⚠️ تأكيد حذف المقررات المسجلة\n';
        message += '═══════════════════════════════════════\n\n';
        message += `📚 عدد المقررات المسجلة: ${enrolledItems.length} مقرر\n\n`;
        message += 'سيتم حذف جميع المقررات المسجلة حالياً للطلاب في هذا الفصل.\n';
        message += '⚠️ هذا الإجراء لا يمكن التراجع عنه!\n\n';
        message += '═══════════════════════════════════════\n';
        message += '🤔 هل أنت متأكد من حذف جميع المقررات المسجلة؟';
        
        if (!confirm(message)) return;
        
        const finalConfirm = prompt('لتأكيد الحذف، اكتب كلمة "حذف" في المربع أدناه:');
        if (finalConfirm !== 'حذف') {
            showToast('warning', 'تم إلغاء عملية الحذف');
            return;
        }
        
        showLoadingOverlay(true);
        
        $.ajax({
            url: 'subject_enrollment.php',
            method: 'POST',
            data: {
                csrf_token: '<?= $_SESSION['csrf_token'] ?>',
                bulk_delete_enrolled: 1,
                semester_id: <?= (int)$semester_id ?>,
                batch_id: <?= (int)$batch_id ?>,
                delete_items: JSON.stringify(enrolledItems)
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast('success', response.message);
                    if (response.clear_selection) {
                        clearAllSelections();
                    }
                    setTimeout(function() { location.reload(); }, 1500);
                } else {
                    showToast('danger', response.message || 'حدث خطأ أثناء حذف المقررات');
                }
            },
            error: function() {
                showToast('danger', 'حدث خطأ في الاتصال بالخادم');
            },
            complete: function() {
                showLoadingOverlay(false);
            }
        });
    });

    // Edit modal - populate data and allow normal form submission
    $('#editModal').on('show.bs.modal', function(event) {
        const button = $(event.relatedTarget);
        $('#edit_student_id').val(button.data('student-id'));
        $('#edit_student_name').val(button.data('student-name'));
        $('#edit_subject_code').val(button.data('subject-code'));
        $('#edit_subject_name').val(button.data('subject-name') + ' (' + button.data('subject-code') + ')');
        const currentTypeId = button.data('current-type-id');
        const currentTypeName = button.data('current-type-name');
        $('#current_type_badge').removeClass().addClass(`type-badge type-${currentTypeId}`).text(currentTypeName);
        $('#new_subjecttype_id').val('');
    });
    
    $('#editEnrollmentForm').on('submit', function(e) {
        const newTypeId = $('#new_subjecttype_id').val();
        if (!newTypeId || newTypeId === '') {
            e.preventDefault();
            alert('⚠️ الرجاء اختيار نوع التسجيل الجديد');
            return false;
        }
        showLoadingOverlay(true);
        return true;
    });
    
    $('#enrollmentForm').on('submit', function(e) {
        const subjectTypeId = $('#subjecttype_id').val();
        if (!subjectTypeId || subjectTypeId === '') {
            e.preventDefault();
            showToast('warning', '⚠️ الرجاء اختيار نوع التسجيل أولاً');
            return false;
        }
        
        const selectedSubjects = $('.subject-checkbox:checked').length;
        const selectedStudents = $('.student-checkbox:checked').length;
        
        if (selectedSubjects === 0) {
            e.preventDefault();
            showToast('warning', '⚠️ الرجاء اختيار مقرر واحد على الأقل');
            return false;
        }
        
        if (selectedStudents === 0) {
            e.preventDefault();
            showToast('warning', '⚠️ الرجاء اختيار طالب واحد على الأقل');
            return false;
        }
        
        $('#enrollmentForm input[name="subjecttype_id"]').remove();
        $('<input>').attr({ type: 'hidden', name: 'subjecttype_id', value: subjectTypeId }).appendTo('#enrollmentForm');
        
        let updateCount = 0;
        $('.subject-checkbox:checked').each(function() {
            if ($(this).closest('.subject-item').hasClass('enrolled')) updateCount++;
        });
        
        const subjectTypeName = $('#subjecttype_id option:selected').text();
        let message = '═══════════════════════════════════════\n';
        message += '            📋 تأكيد تسجيل المقررات\n';
        message += '═══════════════════════════════════════\n\n';
        message += `📚 عدد المقررات: ${selectedSubjects} مقرر\n`;
        message += `🏷️ نوع التسجيل: ${subjectTypeName}\n`;
        message += `👥 عدد الطلاب: ${selectedStudents} طالب\n\n`;
        if (updateCount > 0) {
            message += '⚠️ ملاحظة مهمة:\n';
            message += `   • ${updateCount} مقرر مسجل مسبقاً\n`;
            message += `   • سيتم تحديث نوع التسجيل إلى "${subjectTypeName}"\n\n`;
        }
        message += '═══════════════════════════════════════\n🤔 هل أنت متأكد من المتابعة؟';
        
        if (!confirm(message)) {
            e.preventDefault();
            return false;
        }
        showLoadingOverlay(true);
        return true;
    });
    
    $(document).ajaxComplete(function() { showLoadingOverlay(false); });
    
    // On page load, clear selections if parameter exists
    <?php if (isset($_GET['clear_selection']) && $_GET['clear_selection'] == 1): ?>
        clearAllSelections();
        // Remove the parameter from URL without reloading
        var url = new URL(window.location.href);
        url.searchParams.delete('clear_selection');
        url.searchParams.delete('success_insert');
        url.searchParams.delete('success_update');
        url.searchParams.delete('success_error');
        window.history.replaceState({}, document.title, url.toString());
    <?php endif; ?>
    
    $('#college_id').on('change', function() {
        const collegeId = $(this).val();
        if (collegeId) {
            $.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) {
                        options += `<option value="${section.id}">${escapeHtml(section.name)}</option>`;
                    });
                    $('#section_id').html(options).prop('disabled', false);
                    $('#sectionStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + sections.length + ' قسم</span>');
                    loadPrograms(collegeId);
                },
                error: function() {
                    $('#section_id').html('<option value="">خطأ في تحميل الأقسام</option>').prop('disabled', false);
                    $('#sectionStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
                }
            });
        }
    });
    
    function loadPrograms(collegeId) {
        $.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) {
                    options += `<option value="${program.id}">${escapeHtml(program.name)}</option>`;
                });
                $('#program_id').html(options).prop('disabled', false);
                $('#programStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + programs.length + ' برنامج</span>');
            },
            error: function() {
                $('#program_id').html('<option value="">خطأ في تحميل البرامج</option>').prop('disabled', false);
                $('#programStatus').html('<span class="text-danger"><i class="fas fa-exclamation-circle me-1"></i> خطأ في التحميل</span>');
            }
        });
    }
    
    function loadSpecializations() {
        const sectionId = $('#section_id').val();
        const programId = $('#program_id').val();
        if (sectionId && programId) {
            $.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) {
                        options += `<option value="${spec.specialization_id}">${escapeHtml(spec.specialization_name_ar)}</option>`;
                    });
                    $('#specialization_id').html(options).prop('disabled', false);
                    $('#specializationStatus').html('<span class="text-success"><i class="fas fa-check-circle me-1"></i> ' + specializations.length + ' تخصص</span>');
                },
                error: function() {
                    $('#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>');
                }
            });
        }
    }
    
    function escapeHtml(text) {
        if (!text) return '';
        const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    <?php if ($section_id && $program_id): ?> loadSpecializations(); <?php endif; ?>
    <?php if ($college_id): ?> $('#college_id').trigger('change'); <?php endif; ?>
    
    $('#section_id, #program_id').on('change', function() { loadSpecializations(); });
    
    function updateCounters() {
        const selectedSubjects = $('.subject-checkbox:checked').length;
        const selectedStudents = $('.student-checkbox:checked').length;
        $('#selectedSubjectsCount').text(selectedSubjects);
        $('#selectedSubjectsText').text(selectedSubjects);
        $('#selectedStudentsCount').text(selectedStudents);
        $('#selectedStudentsText').text(selectedStudents);
        
        const allStudentsChecked = $('.student-checkbox').length > 0 && selectedStudents === $('.student-checkbox').length;
        $('#masterStudentCheckbox').prop('checked', allStudentsChecked);
        
        const allSubjectsChecked = $('.subject-checkbox').length > 0 && selectedSubjects === $('.subject-checkbox').length;
        $('#selectAllSubjects').prop('checked', allSubjectsChecked);
    }
    
    $('#selectAllSubjects').on('change', function() {
        $('.subject-checkbox').prop('checked', $(this).prop('checked'));
        updateCounters();
    });
    
    $('#selectAllStudents').on('click', function() { $('.student-checkbox').prop('checked', true); updateCounters(); });
    $('#deselectAllStudents').on('click', function() { $('.student-checkbox').prop('checked', false); updateCounters(); });
    $('#masterStudentCheckbox').on('change', function() { $('.student-checkbox').prop('checked', $(this).prop('checked')); updateCounters(); });
    $(document).on('change', '.student-checkbox, .subject-checkbox', updateCounters);
    
    $(document).on('click', '.student-item', function(e) {
        if ($(e.target).is('input[type="checkbox"]')) return;
        $(this).find('.student-checkbox').prop('checked', function(i, val) { return !val; }).change();
    });
    $(document).on('click', '.subject-item', function(e) {
        if ($(e.target).is('input[type="checkbox"]')) return;
        $(this).find('.subject-checkbox').prop('checked', function(i, val) { return !val; }).change();
    });
    
    if ($('.scrollable-area').first().find('#studentSearch').length === 0) {
        $('.scrollable-area').first().prepend('<div class="mb-3"><input type="text" id="studentSearch" class="form-control form-control-sm" placeholder="🔍 بحث سريع عن طالب..."></div>');
        $('#studentSearch').on('keyup', function() {
            const term = $(this).val().toLowerCase();
            $('.student-item').each(function() {
                const name = $(this).find('strong').text().toLowerCase();
                const id = $(this).find('code').text().toLowerCase();
                $(this).toggle(name.includes(term) || id.includes(term));
            });
        });
    }
    
    if ($('.scrollable-area').last().find('#subjectSearch').length === 0) {
        $('.scrollable-area').last().prepend('<div class="mb-3"><input type="text" id="subjectSearch" class="form-control form-control-sm" placeholder="🔍 بحث سريع عن مقرر..."></div>');
        $('#subjectSearch').on('keyup', function() {
            const term = $(this).val().toLowerCase();
            $('.subject-item').each(function() {
                const code = $(this).find('strong').first().text().toLowerCase();
                const name = $(this).find('.mt-1').first().text().toLowerCase();
                $(this).toggle(code.includes(term) || name.includes(term));
            });
        });
    }
    
    updateCounters();
    setTimeout(function() { $('.alert').fadeOut(500, function() { $(this).remove(); }); }, 5000);
    
    $(document).on('click', '.btn-cancel', function(e) {
        if (!confirm('⚠️ هل أنت متأكد من إلغاء تسجيل هذا المقرر؟\n\nلا يمكن التراجع عن هذا الإجراء.')) {
            e.preventDefault();
            return false;
        }
    });
    
    console.log('✅ تم تحميل صفحة تسجيل المقررات بنجاح');
    console.log('✅ إضافة زر حذف المقررات المسجلة حالياً');
    console.log('✅ إضافة زر إلغاء تحديد الكل');
    console.log('✅ مسح التحديدات تلقائياً بعد الحذف والتسجيل');
});
</script>

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