<?php
// student_subject.php - إدارة العبء الأكاديمي للطالب
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

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

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

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

// Sanitization functions
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');
}

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

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

// Filter variables
$college_filter = isset($_GET['college_id']) ? sanitizeInput($_GET['college_id']) : '';
$section_filter = isset($_GET['section_id']) ? sanitizeInput($_GET['section_id']) : '';
$program_filter = isset($_GET['program_id']) ? sanitizeInput($_GET['program_id']) : '';
$specialization_filter = validateInt($_GET['specialization_id'] ?? 0);
$batch_filter = isset($_GET['batch_id']) ? sanitizeInput($_GET['batch_id']) : '';
$search_term = isset($_GET['search_term']) ? sanitizeInput($_GET['search_term']) : '';
$search_type = isset($_GET['search_type']) && in_array($_GET['search_type'], ['id', 'name']) ? $_GET['search_type'] : 'id';

// Selected student
$selected_student_id = isset($_GET['student_id']) ? sanitizeInput($_GET['student_id'], 'student_id') : '';
$selected_student = null;
$student_subjects = [];
$deleted_subjects = [];

// Get filter data for dropdowns
$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);
}

$sections = [];
$result = $mysqli1->query("SELECT id, name FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($result) {
    $sections = $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);
}

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

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

// Get subject types from database
$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 (empty($subjectTypes)) {
    $subjectTypes = [
        ['id' => 1, 'name' => 'عادي'],
        ['id' => 2, 'name' => 'إزالة رسوب'],
        ['id' => 3, 'name' => 'لم يؤخذ'],
        ['id' => 4, 'name' => 'ترفيع'],
        ['id' => 5, 'name' => 'فروقات منهج'],
        ['id' => 6, 'name' => 'تعليق دراسة']
    ];
}

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

// ============================================
// HANDLE SOFT DELETE (حذف ناعم)
// ============================================
if (isset($_GET['delete_subject']) && isset($_GET['subjectcode']) && isset($_GET['semester_id'])) {
    $delete_subjectcode = sanitizeInput($_GET['subjectcode'], 'subjectcode');
    $delete_semester_id = validateInt($_GET['semester_id']);
    $delete_student_id = sanitizeInput($_GET['student_id'], 'student_id');
    
    if (!hash_equals($_SESSION['csrf_token'], $_GET['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    } else {
        $deleteStmt = $mysqli1->prepare("
            UPDATE studentsubjects 
            SET deleted_at = NOW() 
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND deleted_at IS NULL
        ");
        $deleteStmt->bind_param('ssi', $delete_student_id, $delete_subjectcode, $delete_semester_id);
        
        if ($deleteStmt->execute()) {
            $success_message = "تم حذف المقرر بنجاح";
        } else {
            $errors[] = "حدث خطأ أثناء حذف المقرر";
        }
        $deleteStmt->close();
    }
    
    header("Location: student_subject.php?student_id=" . urlencode($selected_student_id));
    exit();
}

// ============================================
// HANDLE PERMANENT DELETE (حذف نهائي)
// ============================================
if (isset($_GET['permanent_delete']) && isset($_GET['subjectcode']) && isset($_GET['semester_id'])) {
    $delete_subjectcode = sanitizeInput($_GET['subjectcode'], 'subjectcode');
    $delete_semester_id = validateInt($_GET['semester_id']);
    $delete_student_id = sanitizeInput($_GET['student_id'], 'student_id');
    
    if (!hash_equals($_SESSION['csrf_token'], $_GET['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    } else {
        $deleteStmt = $mysqli1->prepare("
            DELETE FROM studentsubjects 
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
        ");
        $deleteStmt->bind_param('ssi', $delete_student_id, $delete_subjectcode, $delete_semester_id);
        
        if ($deleteStmt->execute()) {
            $success_message = "تم حذف المقرر نهائياً بنجاح";
        } else {
            $errors[] = "حدث خطأ أثناء الحذف النهائي للمقرر";
        }
        $deleteStmt->close();
    }
    
    header("Location: student_subject.php?student_id=" . urlencode($selected_student_id));
    exit();
}

// ============================================
// HANDLE RESTORE SUBJECT (استعادة مقرر)
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_subject'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    } else {
        $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
        $subjectcode = sanitizeInput($_POST['subjectcode'] ?? '', 'subjectcode');
        $semester_id = validateInt($_POST['semester_id'] ?? 0);
        $subjecttype_id = validateInt($_POST['subjecttype_id'] ?? 0);
        $batch_id = validateInt($_POST['batch_id'] ?? 0);
        
        $restoreStmt = $mysqli1->prepare("
            UPDATE studentsubjects 
            SET deleted_at = NULL, 
                subjecttype_id = ?, 
                batch_id = ?,
                updated_at = NOW()
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
        ");
        $restoreStmt->bind_param('iissi', $subjecttype_id, $batch_id, $student_id, $subjectcode, $semester_id);
        
        if ($restoreStmt->execute()) {
            $success_message = "تم استعادة المقرر ($subjectcode) بنجاح";
        } else {
            $errors[] = "حدث خطأ أثناء استعادة المقرر";
        }
        $restoreStmt->close();
        
        header("Location: student_subject.php?student_id=" . urlencode($student_id));
        exit();
    }
}

// ============================================
// HANDLE BULK RESTORE (استعادة جماعية)
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_restore'])) {
    header('Content-Type: application/json');
    
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'طلب غير مصرح به']);
        exit();
    }
    
    $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
    $subjects = json_decode($_POST['subjects'] ?? '[]', true);
    $batch_id = validateInt($_POST['batch_id'] ?? 0);
    
    if (empty($student_id) || empty($subjects)) {
        echo json_encode(['success' => false, 'message' => 'بيانات غير صالحة']);
        exit();
    }
    
    $success_count = 0;
    $error_count = 0;
    
    foreach ($subjects as $subject) {
        $subjectcode = sanitizeInput($subject['subjectcode'] ?? '', 'subjectcode');
        $semester_id = validateInt($subject['semester_id'] ?? 0);
        $subjecttype_id = validateInt($subject['subjecttype_id'] ?? 1);
        
        $restoreStmt = $mysqli1->prepare("
            UPDATE studentsubjects 
            SET deleted_at = NULL, 
                batch_id = ?,
                updated_at = NOW()
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
        ");
        $restoreStmt->bind_param('issi', $batch_id, $student_id, $subjectcode, $semester_id);
        
        if ($restoreStmt->execute()) {
            $success_count++;
        } else {
            $error_count++;
        }
        $restoreStmt->close();
    }
    
    echo json_encode([
        'success' => true,
        'success_count' => $success_count,
        'error_count' => $error_count,
        'message' => "تم استعادة $success_count مقرر" . ($error_count > 0 ? " وفشل $error_count" : "")
    ]);
    exit();
}

// ============================================
// HANDLE BULK PERMANENT DELETE (حذف نهائي جماعي)
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_permanent_delete'])) {
    header('Content-Type: application/json');
    
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        echo json_encode(['success' => false, 'message' => 'طلب غير مصرح به']);
        exit();
    }
    
    $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
    $subjects = json_decode($_POST['subjects'] ?? '[]', true);
    
    if (empty($student_id) || empty($subjects)) {
        echo json_encode(['success' => false, 'message' => 'بيانات غير صالحة']);
        exit();
    }
    
    $success_count = 0;
    $error_count = 0;
    
    foreach ($subjects as $subject) {
        $subjectcode = sanitizeInput($subject['subjectcode'] ?? '', 'subjectcode');
        $semester_id = validateInt($subject['semester_id'] ?? 0);
        
        $deleteStmt = $mysqli1->prepare("
            DELETE FROM studentsubjects 
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
        ");
        $deleteStmt->bind_param('ssi', $student_id, $subjectcode, $semester_id);
        
        if ($deleteStmt->execute()) {
            $success_count++;
        } else {
            $error_count++;
        }
        $deleteStmt->close();
    }
    
    echo json_encode([
        'success' => true,
        'success_count' => $success_count,
        'error_count' => $error_count,
        'message' => "تم حذف $success_count مقرر نهائياً" . ($error_count > 0 ? " وفشل $error_count" : "")
    ]);
    exit();
}

// ============================================
// HANDLE ADD SUBJECT (إضافة مقرر)
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_subject'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    } else {
        $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
        $subjectcode = sanitizeInput($_POST['subjectcode'] ?? '', 'subjectcode');
        $semester_id = validateInt($_POST['semester_id'] ?? 0);
        $batch_id = validateInt($_POST['batch_id'] ?? 0);
        $subjecttype_id = validateInt($_POST['subjecttype_id'] ?? 0);
        
        if (empty($student_id) || empty($subjectcode) || $semester_id <= 0 || $batch_id <= 0 || $subjecttype_id <= 0) {
            $errors[] = 'جميع الحقول مطلوبة';
        } else {
            // التحقق من وجود المقرر (بما في ذلك المحذوف)
            $checkStmt = $mysqli1->prepare("
                SELECT id, deleted_at, subjecttype_id, semester_id, batch_id 
                FROM studentsubjects 
                WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
            ");
            $checkStmt->bind_param('ssi', $student_id, $subjectcode, $semester_id);
            $checkStmt->execute();
            $existing = $checkStmt->get_result()->fetch_assoc();
            $checkStmt->close();
            
            if ($existing) {
                if ($existing['deleted_at'] === null) {
                    $errors[] = "المقرر ($subjectcode) مسجل بالفعل للطالب في هذا الفصل";
                } else {
                    $restoreStmt = $mysqli1->prepare("
                        UPDATE studentsubjects 
                        SET deleted_at = NULL, 
                            subjecttype_id = ?, 
                            batch_id = ?,
                            updated_at = NOW()
                        WHERE student_id = ? AND subjectcode = ? AND semester_id = ?
                    ");
                    $restoreStmt->bind_param('iissi', $subjecttype_id, $batch_id, $student_id, $subjectcode, $semester_id);
                    
                    if ($restoreStmt->execute()) {
                        $success_message = "تم استعادة المقرر ($subjectcode) بنجاح";
                    } else {
                        $errors[] = "حدث خطأ أثناء استعادة المقرر";
                    }
                    $restoreStmt->close();
                }
            } else {
                $subjectStmt = $mysqli1->prepare("SELECT credit_hours FROM subjects WHERE subjectcode = ? AND deleted_at IS NULL");
                $subjectStmt->bind_param('s', $subjectcode);
                $subjectStmt->execute();
                $subjectInfo = $subjectStmt->get_result()->fetch_assoc();
                $credit_hours = $subjectInfo['credit_hours'] ?? 3.00;
                $subjectStmt->close();
                
                $insertStmt = $mysqli1->prepare("
                    INSERT INTO studentsubjects 
                    (student_id, subjectcode, semester_id, batch_id, subjecttype_id, credit_hours, weight, degree, created_at, updated_at)
                    VALUES (?, ?, ?, ?, ?, ?, 00.00, 0.00, NOW(), NOW())
                ");
                $insertStmt->bind_param('ssiiid', $student_id, $subjectcode, $semester_id, $batch_id, $subjecttype_id, $credit_hours);
                
                if ($insertStmt->execute()) {
                    $success_message = "تم إضافة المقرر ($subjectcode) بنجاح";
                } else {
                    $errors[] = "حدث خطأ أثناء إضافة المقرر";
                }
                $insertStmt->close();
            }
        }
    }
}

// ============================================
// HANDLE UPDATE SUBJECT TYPE (تحديث نوع التسجيل)
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_subject_type'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'طلب غير مصرح به';
    } else {
        $student_id = sanitizeInput($_POST['student_id'] ?? '', 'student_id');
        $subjectcode = sanitizeInput($_POST['subjectcode'] ?? '', 'subjectcode');
        $semester_id = validateInt($_POST['semester_id'] ?? 0);
        $subjecttype_id = validateInt($_POST['subjecttype_id'] ?? 0);
        
        $updateStmt = $mysqli1->prepare("
            UPDATE studentsubjects 
            SET subjecttype_id = ?, updated_at = NOW()
            WHERE student_id = ? AND subjectcode = ? AND semester_id = ? AND deleted_at IS NULL
        ");
        $updateStmt->bind_param('issi', $subjecttype_id, $student_id, $subjectcode, $semester_id);
        
        if ($updateStmt->execute()) {
            $success_message = "تم تحديث نوع التسجيل بنجاح";
        } else {
            $errors[] = "حدث خطأ أثناء تحديث نوع التسجيل";
        }
        $updateStmt->close();
    }
}

// ============================================
// GET STUDENTS LIST (قائمة الطلاب)
// ============================================
$students_list = [];
if (!empty($college_filter) || !empty($section_filter) || !empty($program_filter) || !empty($specialization_filter) || !empty($batch_filter) || !empty($search_term)) {
    
    $query = "
        SELECT 
            s.student_id,
            s.student_name,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            spec.specialization_name_ar as specialization_name,
            b.value as batch_name,
            (SELECT COUNT(*) FROM studentsubjects WHERE student_id = s.student_id AND deleted_at IS NULL) as subjects_count,
            (SELECT SUM(credit_hours) 
             FROM studentsubjects 
             WHERE student_id = s.student_id AND deleted_at IS NULL) as total_hours
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations spec ON s.specialization_id = spec.specialization_id AND spec.deleted_at IS NULL
        LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
        WHERE s.deleted_at IS NULL
    ";
    
    $conditions = [];
    $params = [];
    $types = "";
    
    if (!$canAll && $scopeCollege !== null) {
        $conditions[] = "s.college_id = ?";
        $params[] = $scopeCollege;
        $types .= "s";
    }
    
    if (!empty($search_term)) {
        if ($search_type === 'id') {
            $conditions[] = "s.student_id LIKE ?";
            $params[] = "%$search_term%";
            $types .= "s";
        } else {
            $conditions[] = "s.student_name LIKE ?";
            $params[] = "%$search_term%";
            $types .= "s";
        }
    }
    
    if (!empty($college_filter)) {
        $conditions[] = "s.college_id = ?";
        $params[] = $college_filter;
        $types .= "s";
    }
    
    if (!empty($section_filter)) {
        $conditions[] = "s.section_id = ?";
        $params[] = $section_filter;
        $types .= "s";
    }
    
    if (!empty($program_filter)) {
        $conditions[] = "s.program_id = ?";
        $params[] = $program_filter;
        $types .= "s";
    }
    
    if ($specialization_filter > 0) {
        $conditions[] = "s.specialization_id = ?";
        $params[] = $specialization_filter;
        $types .= "i";
    }
    
    if (!empty($batch_filter)) {
        $conditions[] = "s.batch_id = ?";
        $params[] = $batch_filter;
        $types .= "s";
    }
    
    if (!empty($conditions)) {
        $query .= " AND " . implode(" AND ", $conditions);
    }
    
    $query .= " ORDER BY s.student_name LIMIT 100";
    
    $stmt = $mysqli1->prepare($query);
    if ($stmt) {
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $students_list = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
}

// ============================================
// GET SELECTED STUDENT DATA (بيانات الطالب المختار)
// ============================================
if (!empty($selected_student_id)) {
    $studentQuery = "
        SELECT 
            s.id,
            s.student_id,
            s.student_name,
            s.email,
            s.phone_number,
            s.college_id,
            s.section_id,
            s.program_id,
            s.specialization_id,
            s.batch_id,
            c.name as college_name,
            sec.name as section_name,
            p.name as program_name,
            spec.specialization_name_ar as specialization_name,
            b.value as batch_name
        FROM students s
        LEFT JOIN colleges c ON s.college_id = c.id AND c.deleted_at IS NULL
        LEFT JOIN sections sec ON s.section_id = sec.id AND sec.deleted_at IS NULL
        LEFT JOIN programs p ON s.program_id = p.id AND p.deleted_at IS NULL
        LEFT JOIN specializations spec ON s.specialization_id = spec.specialization_id AND spec.deleted_at IS NULL
        LEFT JOIN batches b ON s.batch_id = b.id AND b.deleted_at IS NULL
        WHERE s.student_id = ? AND s.deleted_at IS NULL
        LIMIT 1
    ";
    
    $stmt = $mysqli1->prepare($studentQuery);
    if ($stmt) {
        $stmt->bind_param('s', $selected_student_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $selected_student = [
                'id' => (int)$row['id'],
                'student_id' => sanitizeInput($row['student_id']),
                'student_name' => sanitizeInput($row['student_name']),
                'email' => sanitizeInput($row['email'] ?? ''),
                'phone' => sanitizeInput($row['phone_number'] ?? ''),
                'college_id' => sanitizeInput($row['college_id'] ?? ''),
                'college_name' => sanitizeInput($row['college_name'] ?? ''),
                'section_id' => sanitizeInput($row['section_id'] ?? ''),
                'section_name' => sanitizeInput($row['section_name'] ?? ''),
                'program_id' => sanitizeInput($row['program_id'] ?? ''),
                'program_name' => sanitizeInput($row['program_name'] ?? ''),
                'specialization_id' => (int)$row['specialization_id'],
                'specialization_name' => sanitizeInput($row['specialization_name'] ?? ''),
                'batch_id' => sanitizeInput($row['batch_id'] ?? ''),
                'batch_name' => sanitizeInput($row['batch_name'] ?? '')
            ];
            
            if (!$canAll && $scopeCollege !== null && $row['college_id'] != $scopeCollege) {
                die('غير مصرح لك بالوصول لبيانات هذا الطالب');
            }
        }
        $stmt->close();
    }
    
    // Get active subjects
    if ($selected_student) {
        $subjectsQuery = "
            SELECT DISTINCT
                ss.subjectcode,
                ss.semester_id,
                ss.batch_id,
                ss.subjecttype_id,
                ss.credit_hours,
                ss.grade,
                ss.weight,
                ss.degree,
                ss.created_at,
                ss.updated_at,
                sub.subjectnamea,
                s.name as semester_name,
                st.name as subjecttype_name
            FROM studentsubjects ss
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode AND sub.deleted_at IS NULL
            JOIN semesters s ON ss.semester_id = s.id AND s.deleted_at IS NULL
            LEFT JOIN subjecttypes st ON ss.subjecttype_id = st.id
            WHERE ss.student_id = ? AND ss.deleted_at IS NULL
            GROUP BY ss.subjectcode, ss.semester_id
            ORDER BY s.id ASC, sub.subjectcode
        ";
        
        $stmt = $mysqli1->prepare($subjectsQuery);
        if ($stmt) {
            $stmt->bind_param('s', $selected_student_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $semester_id = (int)$row['semester_id'];
                if (!isset($student_subjects[$semester_id])) {
                    $student_subjects[$semester_id] = [
                        'semester_id' => $semester_id,
                        'semester_name' => sanitizeInput($row['semester_name']),
                        'subjects' => [],
                        'total_hours' => 0,
                        'total_subjects' => 0
                    ];
                }
                
                $student_subjects[$semester_id]['subjects'][] = [
                    'subjectcode' => sanitizeInput($row['subjectcode']),
                    'subjectnamea' => sanitizeInput($row['subjectnamea']),
                    'credit_hours' => (float)$row['credit_hours'],
                    'subjecttype_id' => (int)$row['subjecttype_id'],
                    'subjecttype_name' => sanitizeInput($row['subjecttype_name'] ?? 'عادي'),
                    'grade' => $row['grade'] ? sanitizeInput($row['grade']) : null,
                    'weight' => $row['weight'] ? (float)$row['weight'] : null,  // إضافة الوزن
                    'degree' => $row['degree'] ? (float)$row['degree'] : null,
                    'updated_at' => $row['updated_at']
                ];
                
                $student_subjects[$semester_id]['total_hours'] += (float)$row['credit_hours'];
                $student_subjects[$semester_id]['total_subjects']++;
            }
            $stmt->close();
        }
        
        // Get deleted subjects
        $deletedQuery = "
            SELECT DISTINCT
                ss.subjectcode,
                ss.semester_id,
                ss.batch_id,
                ss.subjecttype_id,
                ss.credit_hours,
                 ss.weight,
                ss.deleted_at,
                sub.subjectnamea,
                s.name as semester_name,
                st.name as subjecttype_name
            FROM studentsubjects ss
            JOIN subjects sub ON ss.subjectcode = sub.subjectcode AND sub.deleted_at IS NULL
            JOIN semesters s ON ss.semester_id = s.id AND s.deleted_at IS NULL
            LEFT JOIN subjecttypes st ON ss.subjecttype_id = st.id
            WHERE ss.student_id = ? AND ss.deleted_at IS NOT NULL
            GROUP BY ss.subjectcode, ss.semester_id
            ORDER BY ss.deleted_at DESC
        ";
        
        $stmt = $mysqli1->prepare($deletedQuery);
        if ($stmt) {
            $stmt->bind_param('s', $selected_student_id);
            $stmt->execute();
            $deleted_subjects = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->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">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" 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: '\f0e4';
            font-family: 'Font Awesome 6 Free';
            font-weight: 900;
            position: absolute;
            bottom: -20px;
            left: -20px;
            font-size: 150px;
            opacity: 0.1;
            color: white;
        }
        .page-header h1 { font-size: 2.2rem; font-weight: 800; margin: 0; position: relative; z-index: 2; }
        .page-header p { font-size: 1rem; margin-top: 5px; opacity: 0.9; position: relative; z-index: 2; }
        
        .btn-gradient {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            border: none;
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 176, 155, 0.4);
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-gradient:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6); color: white; }
        
        .btn-outline-gradient {
            background: transparent;
            border: 2px solid rgba(255, 255, 255, 0.5);
            color: white;
            padding: 10px 25px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-outline-gradient:hover { background: rgba(255, 255, 255, 0.2); color: white; transform: translateY(-2px); }
        
        .btn-reset {
            background: linear-gradient(135deg, #6b7280, #4b5563);
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .filter-card {
            background: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
        }
        
        .form-label { font-weight: 600; color: #2d3748; margin-bottom: 8px; font-size: 0.95rem; }
        .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;
            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; }
        
        .students-list-card {
            background: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        }
        
        .students-list-box {
            max-height: 400px;
            overflow-y: auto;
            border: 2px solid #e2e8f0;
            border-radius: 20px;
            padding: 10px;
        }
        
        .student-item {
            padding: 12px 15px;
            margin-bottom: 5px;
            background: #f8fafc;
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }
        .student-item:hover { background: linear-gradient(135deg, #667eea, #764ba2); color: white; transform: translateX(-5px); }
        .student-item.selected { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border-color: #667eea; }
        
        .selected-student-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border-radius: 30px;
            padding: 25px;
            margin-bottom: 25px;
            position: relative;
            overflow: hidden;
        }
        .selected-student-header::before {
            content: '\f007';
            font-family: 'Font Awesome 6 Free';
            font-weight: 900;
            position: absolute;
            bottom: -20px;
            left: -20px;
            font-size: 150px;
            opacity: 0.1;
            color: white;
        }
        
        .semester-card {
            background: white;
            border-radius: 20px;
            margin-bottom: 20px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e2e8f0;
        }
        .semester-card-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .semester-card-header h6 { margin: 0; font-weight: 700; }
        
        .subjects-table { width: 100%; border-collapse: collapse; }
        .subjects-table th { background: #f8fafc; padding: 12px; font-weight: 700; color: #2d3748; border-bottom: 2px solid #e2e8f0; }
        .subjects-table td { padding: 12px; border-bottom: 1px solid #e2e8f0; vertical-align: middle; }
        .subjects-table tbody tr:hover { background: #f8fafc; }
        
        .type-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            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; }
        
        .btn-sm-gradient {
            background: linear-gradient(135deg, #4a90e2, #357abd);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 5px 12px;
            font-size: 0.75rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .btn-sm-danger {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 5px 12px;
            font-size: 0.75rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .btn-sm-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 5px 12px;
            font-size: 0.75rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .btn-sm-gradient:hover, .btn-sm-danger:hover, .btn-sm-success:hover { transform: translateY(-2px); color: white; }
        
        .stat-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 20px;
            padding: 15px;
            text-align: center;
            height: 100%;
        }
        .stat-number { font-size: 1.5rem; font-weight: 800; color: #2d3748; }
        .stat-label { color: #718096; font-weight: 600; font-size: 0.85rem; }
        
        .alert { border-radius: 20px; border: none; padding: 20px 30px; font-weight: 600; margin-bottom: 25px; }
        .alert-success { background: linear-gradient(135deg, #84fab0, #8fd3f4); color: #1e4620; }
        .alert-danger { background: linear-gradient(135deg, #fc6767, #ec008c); color: white; }
        
        .modal-content { border-radius: 20px; border: none; }
        .modal-header { border-radius: 20px 20px 0 0; padding: 20px 25px; }
        
        .max-load-warning { background: #fff3cd; border-right: 4px solid #ffc107; padding: 10px 15px; border-radius: 10px; margin-top: 10px; }
        .max-load-danger { background: #f8d7da; border-right: 4px solid #dc3545; padding: 10px 15px; border-radius: 10px; margin-top: 10px; }
        
        .select2-container--bootstrap-5 .select2-selection {
            border-radius: 15px !important;
            border: 2px solid #e2e8f0 !important;
            min-height: 45px !important;
        }
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
            text-align: right !important;
            padding-right: 15px !important;
        }
        .select2-dropdown {
            text-align: right !important;
        }
        
        .subject-context-info {
            background: linear-gradient(135deg, #e0f2fe, #bae6fd);
            border: none;
            border-radius: 16px;
            padding: 12px 15px;
            margin-bottom: 15px;
        }
        
        .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.3s ease;
        }
        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        
        @media (max-width: 768px) {
            .page-header { padding: 20px; }
            .page-header h1 { font-size: 1.5rem; }
            .subjects-table { font-size: 0.8rem; }
            .btn-sm-gradient, .btn-sm-danger, .btn-sm-success { padding: 3px 8px; font-size: 0.7rem; }
        }
    </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-weight-hanging ms-3"></i>
                    إدارة العبء الأكاديمي للطلاب
                </h1>
                <p class="mb-0">
                    <i class="fas fa-info-circle ms-2"></i>
                    عرض وإدارة المقررات الدراسية والعبء الأكاديمي للطلاب
                </p>
            </div>
            <div class="d-flex gap-3 mt-3 mt-md-0">
                <a href="admin_dashboard.php" class="btn-outline-gradient">
                    <i class="fas fa-arrow-right ms-2"></i>
                    العودة للوحة التحكم
                </a>
            </div>
        </div>

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

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

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

        <!-- Search and Filters Form -->
        <form method="get" action="" id="filterForm">
            <div class="filter-card">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label">بحث بـ</label>
                        <select class="form-select" name="search_type">
                            <option value="id" <?= $search_type === 'id' ? 'selected' : '' ?>>الرقم الجامعي</option>
                            <option value="name" <?= $search_type === 'name' ? 'selected' : '' ?>>الاسم</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">كلمة البحث</label>
                        <input type="text" class="form-control" name="search_term" value="<?= htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8') ?>" placeholder="أدخل الرقم الجامعي أو اسم الطالب...">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">الكلية</label>
                        <select class="form-select" name="college_id" id="college_id">
                            <option value="">جميع الكليات</option>
                            <?php foreach ($colleges as $college): ?>
                                <option value="<?= htmlspecialchars($college['id']) ?>" <?= ($college_filter == $college['id']) ? 'selected' : '' ?>><?= htmlspecialchars($college['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">القسم</label>
                        <select class="form-select" name="section_id" id="section_id">
                            <option value="">جميع الأقسام</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">البرنامج</label>
                        <select class="form-select" name="program_id" id="program_id">
                            <option value="">جميع البرامج</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">التخصص</label>
                        <select class="form-select" name="specialization_id" id="specialization_id">
                            <option value="">جميع التخصصات</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">الدفعة</label>
                        <select class="form-select" name="batch_id" id="batch_id">
                            <option value="">جميع الدفعات</option>
                            <?php foreach ($batches as $batch): ?>
                                <option value="<?= htmlspecialchars($batch['id']) ?>" <?= ($batch_filter == $batch['id']) ? 'selected' : '' ?>><?= htmlspecialchars($batch['value']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn-gradient w-100"><i class="fas fa-search ms-2"></i> بحث</button>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <a href="student_subject.php" class="btn-reset w-100 text-center"><i class="fas fa-redo-alt ms-2"></i> إعادة تعيين</a>
                    </div>
                </div>
            </div>
        </form>

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

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

            <!-- Summary Statistics -->
            <?php
            $total_hours_all = 0;
            $total_subjects_all = 0;
            foreach ($student_subjects as $semester) {
                $total_hours_all += $semester['total_hours'];
                $total_subjects_all += $semester['total_subjects'];
            }
            ?>
            <div class="row g-3 mb-4">
                <div class="col-md-3">
                    <div class="stat-card"><div class="stat-number"><?= $total_subjects_all ?></div><div class="stat-label">إجمالي المقررات</div></div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card"><div class="stat-number"><?= number_format($total_hours_all, 1) ?></div><div class="stat-label">إجمالي الساعات</div></div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card"><div class="stat-number"><?= count($student_subjects) ?></div><div class="stat-label">عدد الفصول الدراسية</div></div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card"><div class="stat-number"><?= round($total_hours_all / max(count($student_subjects), 1), 1) ?></div><div class="stat-label">متوسط الساعات لكل فصل</div></div>
                </div>
            </div>

            <!-- Academic Load per Semester -->
            <?php if (!empty($student_subjects)): ?>
                <div class="content-card">
                    <div class="content-card-header">
                        <h5><i class="fas fa-chalkboard-user ms-2"></i> المقررات الدراسية حسب الفصل الدراسي</h5>
                        <span class="badge bg-secondary rounded-pill">الحد الأقصى المسموح: 18 ساعة</span>
                    </div>
                    
                    <?php foreach ($student_subjects as $semester_id => $semester_data): ?>
                        <?php 
                        $max_allowed = 18;
                        $is_overload = $semester_data['total_hours'] > $max_allowed;
                        $load_percentage = ($semester_data['total_hours'] / $max_allowed) * 100;
                        ?>
                        <div class="semester-card">
                            <div class="semester-card-header">
                                <h6><i class="fas fa-calendar-alt ms-2"></i> الفصل <?= htmlspecialchars($semester_data['semester_name'], ENT_QUOTES, 'UTF-8') ?></h6>
                                <div class="d-flex gap-3 flex-wrap">
                                    <span class="badge bg-light text-dark rounded-pill"><i class="fas fa-book ms-1"></i> <?= $semester_data['total_subjects'] ?> مواد</span>
                                    <span class="badge bg-light text-dark rounded-pill"><i class="fas fa-clock ms-1"></i> <?= number_format($semester_data['total_hours'], 1) ?> / <?= $max_allowed ?> ساعة</span>
                                    <?php if ($is_overload): ?>
                                        <span class="badge bg-danger rounded-pill"><i class="fas fa-exclamation-triangle ms-1"></i> تجاوز العبء بمقدار <?= number_format($semester_data['total_hours'] - $max_allowed, 1) ?> ساعة</span>
                                    <?php elseif ($load_percentage > 80): ?>
                                        <span class="badge bg-warning rounded-pill"><i class="fas fa-hourglass-half ms-1"></i> قارب الحد الأقصى (<?= round($load_percentage) ?>%)</span>
                                    <?php else: ?>
                                        <span class="badge bg-success rounded-pill"><i class="fas fa-check-circle ms-1"></i> ضمن العبء المسموح</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <div class="p-3" style="background: #f8fafc;">
                                <div class="d-flex justify-content-between mb-1">
                                    <small>نسبة استهلاك العبء الأكاديمي</small>
                                    <small><?= round($load_percentage, 1) ?>%</small>
                                </div>
                                <div class="progress" style="height: 8px;">
                                    <div class="progress-bar <?= $is_overload ? 'bg-danger' : ($load_percentage > 80 ? 'bg-warning' : 'bg-success') ?>" 
                                         role="progressbar" style="width: <?= min($load_percentage, 100) ?>%;"></div>
                                </div>
                            </div>
                            
                            <div class="table-responsive">
                                <table class="subjects-table">
                                    <thead>
                                        <tr>
                                            <th>كود المادة</th>
                                            <th>اسم المادة</th>
                                            <th>الساعات</th>
                                            <th>نوع التسجيل</th>
                                            <th>التقدير</th>
                                            <th>الوزن</th>
                                            <th>الإجراءات</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($semester_data['subjects'] as $subject): ?>
                                            <tr>
                                                <td><code><?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?></code></div>
                                                <td><?= htmlspecialchars($subject['subjectnamea'], ENT_QUOTES, 'UTF-8') ?></div>
                                                <td><span class="badge bg-secondary rounded-pill"><?= number_format($subject['credit_hours'], 1) ?></span></div>
                                                <td>
                                                    <span class="type-badge type-<?= $subject['subjecttype_id'] ?>">
                                                        <?= htmlspecialchars($subject['subjecttype_name'], ENT_QUOTES, 'UTF-8') ?>
                                                    </span>
                                                 </div>
                                                <td>
                                                    <?php if ($subject['grade']): ?>
                                                        <span class="badge bg-success rounded-pill"><?= htmlspecialchars($subject['grade'], ENT_QUOTES, 'UTF-8') ?></span>
                                                    <?php else: ?>
                                                        <span class="text-muted">--</span>
                                                    <?php endif; ?>
                                                 </div>
                                                <td>
                                                    <?php if ($subject['weight'] && $subject['weight'] > 0.0): ?>
                                                        <span class="badge bg-info rounded-pill"><?= number_format($subject['weight'], 2) ?></span>
                                                    <?php else: ?>
                                                        <span class="text-muted">--</span>
                                                    <?php endif; ?>

                                                 </div>
                                                <td>
                                                    <div class="d-flex gap-2">
                                                        <button type="button" class="btn-sm-gradient" data-bs-toggle="modal" data-bs-target="#editTypeModal"
                                                                data-student-id="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>"
                                                                data-subject-code="<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>"
                                                                data-subject-name="<?= htmlspecialchars($subject['subjectnamea'], ENT_QUOTES, 'UTF-8') ?>"
                                                                data-semester-id="<?= $semester_id ?>"
                                                                data-current-type-id="<?= $subject['subjecttype_id'] ?>"
                                                                data-current-type-name="<?= htmlspecialchars($subject['subjecttype_name'], ENT_QUOTES, 'UTF-8') ?>">
                                                            <i class="fas fa-edit ms-1"></i> تعديل
                                                        </button>
                                                        <a href="?student_id=<?= urlencode($selected_student_id) ?>&delete_subject=1&subjectcode=<?= urlencode($subject['subjectcode']) ?>&semester_id=<?= $semester_id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" 
                                                           class="btn-sm-danger" onclick="return confirm('⚠️ هل أنت متأكد من حذف المقرر <?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>؟')">
                                                            <i class="fas fa-trash-alt ms-1"></i> حذف
                                                        </a>
                                                    </div>
                                                 </div>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot style="background: #f0fdf4;">
                                        <tr>
                                            <td colspan="2"><strong>إجمالي الفصل</strong></div>
                                            <td><strong><?= number_format($semester_data['total_hours'], 1) ?> ساعة</strong></div>
                                            <td colspan="4"></div>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                            
                            <?php if ($is_overload): ?>
                                <div class="max-load-danger p-3">
                                    <i class="fas fa-exclamation-triangle ms-2"></i>
                                    <strong>تحذير: تجاوز العبء الأكاديمي!</strong>
                                    <br>
                                    <small>الساعات المسجلة (<?= number_format($semester_data['total_hours'], 1) ?>) تتجاوز الحد الأقصى المسموح (<?= $max_allowed ?> ساعة) بمقدار <?= number_format($semester_data['total_hours'] - $max_allowed, 1) ?> ساعة. يرجى مراجعة تسجيل المقررات.</small>
                                </div>
                            <?php elseif ($load_percentage > 80): ?>
                                <div class="max-load-warning p-3">
                                    <i class="fas fa-hourglass-half ms-2"></i>
                                    <strong>تنبيه: قارب العبء الأكاديمي الحد الأقصى!</strong>
                                    <br>
                                    <small>تم استهلاك <?= round($load_percentage) ?>% من العبء الأكاديمي المسموح به (<?= number_format($semester_data['total_hours'], 1) ?> من <?= $max_allowed ?> ساعة).</small>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="content-card">
                    <div class="text-center py-5">
                        <i class="fas fa-book-open fa-3x text-muted mb-3"></i>
                        <h5>لا توجد مواد مسجلة</h5>
                        <p class="text-muted">لم يتم تسجيل أي مواد للطالب بعد</p>
                        <button type="button" class="btn-gradient" data-bs-toggle="modal" data-bs-target="#addSubjectModal">
                            <i class="fas fa-plus-circle ms-2"></i> إضافة مقرر جديد
                        </button>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Deleted Subjects Section -->
            <?php if (!empty($deleted_subjects)): ?>
                <div class="content-card mt-4" style="border-right-color: #dc3545;">
                    <div class="content-card-header">
                        <h5><i class="fas fa-trash-alt ms-2" style="color: #dc3545;"></i> المقررات المحذوفة</h5>
                        <div class="d-flex gap-2">
                            <span class="badge bg-danger rounded-pill px-3 py-2"><?= count($deleted_subjects) ?> مقرر محذوف</span>
                            <button type="button" class="btn btn-sm btn-outline-danger" id="selectAllDeleted" style="border-radius: 50px;">
                                <i class="fas fa-check-double ms-1"></i> تحديد الكل
                            </button>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="subjects-table" id="deletedSubjectsTable">
                            <thead>
                                <tr>
                                    <th width="50"><input type="checkbox" id="masterDeleteCheckbox" style="transform: scale(1.2);"></th>
                                    <th>كود المادة</th>
                                    <th>اسم المادة</th>
                                    <th>الساعات</th>
                                    <th>الفصل الدراسي</th>
                                    <th>نوع التسجيل</th>
                                    <th>تاريخ الحذف</th>
                                    <th>الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($deleted_subjects as $subject): ?>
                                    <tr style="background: #fff5f5;" id="deleted-row-<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>">
                                        <td>
                                            <input type="checkbox" class="deleted-checkbox" 
                                                   data-subjectcode="<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>" 
                                                   data-semester-id="<?= $subject['semester_id'] ?>"
                                                   data-subjecttype-id="<?= $subject['subjecttype_id'] ?>"
                                                   style="transform: scale(1.2);">
                                         </div>
                                        <td><code><?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?></code></div>
                                        <td><?= htmlspecialchars($subject['subjectnamea'], ENT_QUOTES, 'UTF-8') ?></div>
                                        <td><span class="badge bg-secondary rounded-pill"><?= number_format($subject['credit_hours'], 1) ?></span></div>
                                        <td>الفصل <?= htmlspecialchars($subject['semester_name'], ENT_QUOTES, 'UTF-8') ?></div>
                                        <td>
                                            <span class="type-badge type-<?= $subject['subjecttype_id'] ?>">
                                                <?= htmlspecialchars($subject['subjecttype_name'] ?? 'عادي', ENT_QUOTES, 'UTF-8') ?>
                                            </span>
                                         </div>
                                        <td>
                                            <span class="badge bg-secondary"><?= date('Y-m-d H:i', strtotime($subject['deleted_at'])) ?></span>
                                         </div>
                                        <td>
                                            <div class="d-flex gap-2">
                                                <form method="POST" action="" style="display: inline-block;" onsubmit="return confirm('⚠️ هل أنت متأكد من استعادة المقرر <?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>؟')">
                                                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                                    <input type="hidden" name="restore_subject" value="1">
                                                    <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="subjectcode" value="<?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="semester_id" value="<?= $subject['semester_id'] ?>">
                                                    <input type="hidden" name="subjecttype_id" value="<?= $subject['subjecttype_id'] ?>">
                                                    <input type="hidden" name="batch_id" value="<?= htmlspecialchars($selected_student['batch_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                                                    <button type="submit" class="btn-sm-success" title="استعادة المقرر"  id="bulkRestoreBtn">
                                                        <i class="fas fa-trash-restore ms-1"></i> استعادة
                                                    </button>
                                                </form>
                                                
                                                <a href="?student_id=<?= urlencode($selected_student_id) ?>&permanent_delete=1&subjectcode=<?= urlencode($subject['subjectcode']) ?>&semester_id=<?= $subject['semester_id'] ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" 
                                                   class="btn-sm-danger" 
                                                   onclick="return confirm('⚠️ تحذير: هذا الإجراء سيحذف المقرر نهائياً من قاعدة البيانات!\n\nالمقرر: <?= htmlspecialchars($subject['subjectcode'], ENT_QUOTES, 'UTF-8') ?>\n\nلا يمكن التراجع عن هذا الإطلاق. هل أنت متأكد؟')"
                                                   title="حذف نهائي - لا يمكن التراجع">
                                                    <i class="fas fa-trash-alt ms-1"></i> حذف نهائي
                                                </a>
                                            </div>
                                         </div>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Bulk Actions -->
                    <?php if (count($deleted_subjects) > 0): ?>
                        <div class="mt-3 p-3 bg-light rounded-3" id="bulkActions" style="display: none;">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                                <div>
                                    <i class="fas fa-check-circle text-primary ms-2"></i>
                                    <span id="selectedCount">0</span> مقرر محدد
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="button" class="btn btn-sm btn-success" id="bulkRestoreBtn">
                                        <i class="fas fa-trash-restore ms-1"></i> استعادة المحدد
                                    </button>
                                    <button type="button" class="btn btn-sm btn-danger" id="bulkDeleteBtn">
                                        <i class="fas fa-trash-alt ms-1"></i> حذف نهائي للمحدد
                                    </button>
                                    <button type="button" class="btn btn-sm btn-secondary" id="clearSelectionBtn">
                                        <i class="fas fa-times ms-1"></i> إلغاء التحديد
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

        <?php elseif (empty($students_list) && empty($selected_student) && empty($college_filter) && empty($section_filter) && empty($program_filter) && empty($specialization_filter) && empty($batch_filter) && empty($search_term)): ?>
            <div class="content-card"><div class="text-center py-5"><i class="fas fa-search fa-4x text-muted mb-3 opacity-50"></i><h4 class="fw-bold mb-3">ابحث عن طالب</h4><p class="text-muted">يمكنك البحث بالرقم الجامعي أو الاسم، أو استخدام الفلاتر لعرض قائمة الطلاب</p></div></div>
        <?php endif; ?>
    </div>
</div>

<!-- Add Subject Modal with Search -->
<div class="modal fade" id="addSubjectModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #00b09b, #96c93d); color: white;">
                <h5 class="modal-title"><i class="fas fa-plus-circle ms-2"></i> إضافة مقرر جديد</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="" id="addSubjectForm">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                <input type="hidden" name="add_subject" value="1">
                <input type="hidden" name="student_id" value="<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="batch_id" value="<?= htmlspecialchars($selected_student['batch_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                
                <div class="modal-body">
                    <div class="subject-context-info">
                        <i class="fas fa-info-circle ms-2"></i>
                        <strong>سياق البحث:</strong>
                        <span>
                            الكلية: <?= htmlspecialchars($selected_student['college_name'] ?? '', ENT_QUOTES, 'UTF-8') ?> |
                            البرنامج: <?= htmlspecialchars($selected_student['program_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                            <?php if (!empty($selected_student['specialization_name'])): ?>
                                | التخصص: <?= htmlspecialchars($selected_student['specialization_name'], ENT_QUOTES, 'UTF-8') ?>
                            <?php endif; ?>
                        </span>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label required-field"><i class="fas fa-search ms-1"></i> البحث عن مقرر</label>
                        <select class="form-select subject-search-select" name="subjectcode" id="subjectcode" required style="width: 100%;">
                            <option value="">ابحث عن مقرر بالكود أو الاسم...</option>
                        </select>
                        <small class="text-muted">البحث متاح بالكود أو اسم المقرر بالعربية أو الإنجليزية (يتم عرض مقررات الكلية والبرنامج فقط)</small>
                    </div>
                    
                    <div id="selectedSubjectInfo" class="alert alert-info mt-2" style="display: none;">
                        <i class="fas fa-info-circle ms-2"></i>
                        <span id="selectedSubjectDetails"></span>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label required-field"><i class="fas fa-calendar-alt ms-1"></i> الفصل الدراسي</label>
                        <select class="form-select" name="semester_id" required>
                            <option value="">اختر الفصل</option>
                            <?php foreach ($all_semesters as $sem): ?>
                                <option value="<?= $sem['id'] ?>">الفصل <?= htmlspecialchars($sem['name'], ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label required-field"><i class="fas fa-tag ms-1"></i> نوع التسجيل</label>
                        <select class="form-select" name="subjecttype_id" required>
                            <option value="">اختر نوع التسجيل</option>
                            <?php foreach ($subjectTypes as $type): ?>
                                <option value="<?= $type['id'] ?>"><?= htmlspecialchars($type['name'], ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="alert alert-warning mt-3">
                        <i class="fas fa-exclamation-triangle ms-2"></i>
                        <strong>ملاحظة مهمة:</strong>
                        <ul class="mt-2 mb-0">
                            <li>سيتم إضافة المقرر للطالب في الفصل الدراسي المحدد بنوع التسجيل المختار.</li>
                            <li>الحد الأقصى للعبء الأكاديمي هو 18 ساعة لكل فصل دراسي.</li>
                            <li>تأكد من عدم تجاوز الحد الأقصى للساعات المسموح بها.</li>
                            <li>يتم عرض فقط المقررات التي تنتمي لنفس كلية وبرنامج الطالب.</li>
                            <li>إذا كان المقرر محذوفاً مسبقاً، سيتم استعادته بدلاً من إضافته مرة أخرى.</li>
                        </ul>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn-gradient">إضافة المقرر</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Subject Type Modal -->
<div class="modal fade" id="editTypeModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background: linear-gradient(135deg, #4a90e2, #357abd); color: white;">
                <h5 class="modal-title"><i class="fas fa-edit ms-2"></i> تعديل نوع التسجيل</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                <input type="hidden" name="update_subject_type" value="1">
                <input type="hidden" name="student_id" id="edit_student_id">
                <input type="hidden" name="subjectcode" id="edit_subject_code">
                <input type="hidden" name="semester_id" id="edit_semester_id">
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-bold"><i class="fas fa-book ms-1"></i> المقرر</label>
                        <input type="text" id="edit_subject_name" class="form-control" readonly disabled>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold"><i class="fas fa-tag ms-1"></i> نوع التسجيل الحالي</label>
                        <div><span id="current_type_badge" class="type-badge"></span></div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label required-field"><i class="fas fa-exchange-alt ms-1"></i> تغيير نوع التسجيل إلى</label>
                        <select class="form-select" name="subjecttype_id" id="new_subjecttype_id" required>
                            <option value="">اختر نوع التسجيل الجديد</option>
                            <?php foreach ($subjectTypes as $type): ?>
                                <option value="<?= $type['id'] ?>"><?= htmlspecialchars($type['name'], ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn-gradient">حفظ التغييرات</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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // ============================================
    // TOAST NOTIFICATION FUNCTION
    // ============================================
    function showToast(type, message) {
        $('.toast-notification').remove();
        const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle';
        const bgClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const toastHtml = `
            <div class="alert ${bgClass} toast-notification" role="alert">
                <i class="fas ${icon} ms-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('body').append(toastHtml);
        setTimeout(function() { $('.toast-notification').fadeOut(500, function() { $(this).remove(); }); }, 3000);
    }
    
    // ============================================
    // LOADING OVERLAY
    // ============================================
    function showLoadingOverlay(show) {
        if (show) {
            $('#loadingOverlay').fadeIn(200);
        } else {
            $('#loadingOverlay').fadeOut(200);
        }
    }
    
    // ============================================
    // SELECT2 FOR SUBJECT SEARCH
    // ============================================
    $('#subjectcode').select2({
        dropdownParent: $('#addSubjectModal'),
        theme: 'bootstrap-5',
        placeholder: 'ابحث عن مقرر بالكود أو الاسم...',
        allowClear: true,
        ajax: {
            url: 'ajax/search_subjects.php',
            dataType: 'json',
            delay: 300,
            data: function(params) {
                return {
                    search: params.term,
                    page: params.page || 1,
                    student_id: '<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>'
                };
            },
            processResults: function(data, params) {
                params.page = params.page || 1;
                return {
                    results: data.results,
                    pagination: { more: data.more }
                };
            },
            cache: true
        },
        minimumInputLength: 2,
        templateResult: formatSubjectResult,
        templateSelection: formatSubjectSelection
    });
    
    function formatSubjectResult(subject) {
        if (subject.loading) return subject.text;
        return $(
            '<div class="d-flex justify-content-between align-items-center">' +
                '<div><strong>' + subject.subjectcode + '</strong><br><small>' + subject.subjectnamea + '</small></div>' +
                '<span class="badge bg-secondary">' + subject.credit_hours + ' ساعة</span>' +
            '</div>'
        );
    }
    
    function formatSubjectSelection(subject) {
        if (!subject.subjectcode) return subject.text;
        $('#selectedSubjectDetails').html(
            '<strong>' + subject.subjectcode + '</strong> - ' + subject.subjectnamea + 
            ' (' + subject.credit_hours + ' ساعة)'
        );
        $('#selectedSubjectInfo').show();
        return subject.subjectcode + ' - ' + subject.subjectnamea;
    }
    
    $('#subjectcode').on('change', function() {
        var selectedData = $(this).select2('data')[0];
        if (selectedData && selectedData.subjectcode) {
            $('#selectedSubjectDetails').html(
                '<strong>' + selectedData.subjectcode + '</strong> - ' + selectedData.subjectnamea + 
                ' (' + selectedData.credit_hours + ' ساعة)'
            );
            $('#selectedSubjectInfo').show();
        } else {
            $('#selectedSubjectInfo').hide();
        }
    });
    
    // ============================================
    // DELETED SUBJECTS - BULK ACTIONS
    // ============================================
    let selectedDeletedSubjects = [];
    
    function updateBulkActions() {
        selectedDeletedSubjects = [];
        $('.deleted-checkbox:checked').each(function() {
            selectedDeletedSubjects.push({
                subjectcode: $(this).data('subjectcode'),
                semester_id: $(this).data('semester-id'),
                subjecttype_id: $(this).data('subjecttype-id')
            });
        });
        
        const count = selectedDeletedSubjects.length;
        $('#selectedCount').text(count);
        
        if (count > 0) {
            $('#bulkActions').slideDown();
        } else {
            $('#bulkActions').slideUp();
        }
        
        const totalCheckboxes = $('.deleted-checkbox').length;
        const checkedCheckboxes = $('.deleted-checkbox:checked').length;
        $('#masterDeleteCheckbox').prop('checked', totalCheckboxes > 0 && checkedCheckboxes === totalCheckboxes);
    }
    
    $('#masterDeleteCheckbox').on('change', function() {
        $('.deleted-checkbox').prop('checked', $(this).prop('checked'));
        updateBulkActions();
    });
    
    $(document).on('change', '.deleted-checkbox', function() {
        updateBulkActions();
    });
    
    $('#selectAllDeleted').on('click', function() {
        $('.deleted-checkbox').prop('checked', true);
        updateBulkActions();
    });
    
    $('#clearSelectionBtn').on('click', function() {
        $('.deleted-checkbox').prop('checked', false);
        updateBulkActions();
    });
    
    // Bulk Restore
    $('#bulkRestoreBtn').on('click', function() {
        if (selectedDeletedSubjects.length === 0) {
            showToast('warning', 'الرجاء تحديد المقررات المراد استعادتها');
            return;
        }
        
        const confirmMsg = '═══════════════════════════════════════\n' +
                          '📋 تأكيد الاستعادة الجماعية\n' +
                          '═══════════════════════════════════════\n\n' +
                          `📚 عدد المقررات: ${selectedDeletedSubjects.length} مقرر\n\n` +
                          'سيتم استعادة المقررات المحددة.\n\n' +
                          '═══════════════════════════════════════\n🤔 هل أنت متأكد؟';
        
        if (!confirm(confirmMsg)) return;
        
        showLoadingOverlay(true);
        
        $.ajax({
            url: 'student_subject.php',
            method: 'POST',
            data: {
                csrf_token: '<?= $_SESSION['csrf_token'] ?>',
                bulk_restore: 1,
                student_id: '<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>',
                batch_id: '<?= htmlspecialchars($selected_student['batch_id'] ?? '', ENT_QUOTES, 'UTF-8') ?>',
                subjects: JSON.stringify(selectedDeletedSubjects)
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast('success', response.message);
                    setTimeout(function() { location.reload(); }, 1500);
                } else {
                    showToast('danger', response.message);
                }
            },
            error: function() {
                showToast('danger', 'حدث خطأ في الاتصال');
            },
            complete: function() {
                showLoadingOverlay(false);
            }
        });
    });
    
    // Bulk Permanent Delete
    $('#bulkDeleteBtn').on('click', function() {
        if (selectedDeletedSubjects.length === 0) {
            showToast('warning', 'الرجاء تحديد المقررات المراد حذفها نهائياً');
            return;
        }
        
        const confirmMsg = '═══════════════════════════════════════\n' +
                          '⚠️ تحذير: حذف نهائي جماعي ⚠️\n' +
                          '═══════════════════════════════════════\n\n' +
                          `📚 عدد المقررات: ${selectedDeletedSubjects.length} مقرر\n\n` +
                          'هذا الإجراء سيحذف المقررات نهائياً من قاعدة البيانات.\n' +
                          'لا يمكن التراجع عن هذا الإطلاق!\n\n' +
                          '═══════════════════════════════════════\n' +
                          '🤔 هل أنت متأكد تماماً؟';
        
        if (!confirm(confirmMsg)) return;
        
        showLoadingOverlay(true);
        
        $.ajax({
            url: 'student_subject.php',
            method: 'POST',
            data: {
                csrf_token: '<?= $_SESSION['csrf_token'] ?>',
                bulk_permanent_delete: 1,
                student_id: '<?= htmlspecialchars($selected_student_id, ENT_QUOTES, 'UTF-8') ?>',
                subjects: JSON.stringify(selectedDeletedSubjects)
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast('success', response.message);
                    // Remove deleted rows from table
                    selectedDeletedSubjects.forEach(function(subject) {
                        $('#deleted-row-' + subject.subjectcode).fadeOut(300, function() {
                            $(this).remove();
                        });
                    });
                    updateBulkActions();
                    // Reload after 1 second if all rows removed
                    if ($('.deleted-checkbox').length === 0) {
                        setTimeout(function() { location.reload(); }, 1000);
                    }
                } else {
                    showToast('danger', response.message);
                }
            },
            error: function() {
                showToast('danger', 'حدث خطأ في الاتصال');
            },
            complete: function() {
                showLoadingOverlay(false);
            }
        });
    });
    
    // ============================================
    // EDIT MODAL POPULATE
    // ============================================
    $('#editTypeModal').on('show.bs.modal', function(event) {
        const button = $(event.relatedTarget);
        $('#edit_student_id').val(button.data('student-id'));
        $('#edit_subject_code').val(button.data('subject-code'));
        $('#edit_subject_name').val(button.data('subject-name') + ' (' + button.data('subject-code') + ')');
        $('#edit_semester_id').val(button.data('semester-id'));
        
        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('');
    });
    
    // ============================================
    // DEPENDENT DROPDOWNS
    // ============================================
    $('#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}">${section.name}</option>`;
                    });
                    $('#section_id').html(options);
                }
            });
            $.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}">${program.name}</option>`;
                    });
                    $('#program_id').html(options);
                }
            });
        }
    });
    
    $('#section_id, #program_id').on('change', function() {
        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}">${spec.specialization_name_ar}</option>`;
                    });
                    $('#specialization_id').html(options);
                }
            });
        }
    });
    
    <?php if ($college_filter): ?>
        $('#college_id').trigger('change');
    <?php endif; ?>
    
    // ============================================
    // AUTO-HIDE ALERTS
    // ============================================
    setTimeout(function() { $('.alert').fadeOut(500, function() { $(this).remove(); }); }, 5000);
    
    // ============================================
    // RESET MODAL ON CLOSE
    // ============================================
    $('#addSubjectModal').on('hidden.bs.modal', function() {
        $('#subjectcode').val(null).trigger('change');
        $('#selectedSubjectInfo').hide();
        $('#selectedSubjectDetails').empty();
    });
});
</script>

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