<?php
// academic_plan_subjects.php - نسخة محسنة مع تنسيقات صحيحة
error_reporting(E_ALL);
ini_set('display_errors', 0);
require 'db.php';
require 'helpers.php';
require_committee();

// التحقق من المدخلات بشكل آمن
$plan_id = isset($_GET['id']) && ctype_digit($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$plan_id) {
    $_SESSION['error_message'] = "معرّف الخطة غير صالح";
    header("Location: academic_plans_list.php");
    exit;
}

// Get plan details
$planStmt = $mysqli1->prepare("
    SELECT ap.*, c.name as college_name, sec.name as section_name, p.name as program_name, sp.specialization_name_ar as specialization_name
    FROM academic_plans ap
    LEFT JOIN colleges c ON c.id = ap.college_id
    LEFT JOIN sections sec ON sec.id = ap.section_id
    LEFT JOIN programs p ON p.id = ap.program_id
    LEFT JOIN specializations sp ON sp.specialization_id = ap.specialization_id
    WHERE ap.id = ? AND ap.deleted_at IS NULL
");

if (!$planStmt) {
    error_log("Error in plan query: " . $mysqli1->error);
    $_SESSION['error_message'] = "حدث خطأ في قاعدة البيانات";
    header("Location: academic_plans_list.php");
    exit;
}

$planStmt->bind_param('i', $plan_id);
$planStmt->execute();
$planResult = $planStmt->get_result();
$plan = $planResult->fetch_assoc();
$planStmt->close();

if (!$plan) {
    $_SESSION['error_message'] = "الخطة الدراسية غير موجودة";
    header("Location: academic_plans_list.php");
    exit;
}

// Handle AJAX requests for adding/removing subjects
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    $response = ['success' => false, 'message' => ''];
    
    if ($_POST['action'] === 'add_subject') {
        // التحقق من المدخلات
        if (!isset($_POST['semester']) || !ctype_digit($_POST['semester']) ||
            !isset($_POST['subject_id']) || !ctype_digit($_POST['subject_id'])) {
            $response['message'] = 'بيانات غير صالحة';
            echo json_encode($response);
            exit;
        }
        
        $semester_number = (int)$_POST['semester'];
        $subject_id = (int)$_POST['subject_id'];
        $is_core = isset($_POST['is_core']) ? (int)$_POST['is_core'] : 0;
        
        // Get subject details
        $subjectStmt = $mysqli1->prepare("
            SELECT subjectcode, credit_hours, subjectnamea FROM subjects WHERE id = ?
        ");
        
        if (!$subjectStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $subjectStmt->bind_param('i', $subject_id);
        $subjectStmt->execute();
        $subjectResult = $subjectStmt->get_result();
        $subject = $subjectResult->fetch_assoc();
        $subjectStmt->close();
        
        if (!$subject) {
            $response['message'] = 'المقرر غير موجودة';
            echo json_encode($response);
            exit;
        }
        
        // Check if subject already exists in plan
        $checkStmt = $mysqli1->prepare("
            SELECT id FROM academic_plan_subjects 
            WHERE plan_id = ? AND subject_id = ?
        ");
        
        if (!$checkStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $checkStmt->bind_param('ii', $plan_id, $subject_id);
        $checkStmt->execute();
        $checkStmt->store_result();
        
        if ($checkStmt->num_rows > 0) {
            $response['message'] = 'هذه المقرر موجودة بالفعل في الخطة';
            echo json_encode($response);
            exit;
        }
        $checkStmt->close();
        
        // Get or create semester
        $semesterStmt = $mysqli1->prepare("
            SELECT id FROM academic_plan_semesters 
            WHERE plan_id = ? AND semester_number = ?
        ");
        
        if (!$semesterStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $semesterStmt->bind_param('ii', $plan_id, $semester_number);
        $semesterStmt->execute();
        $semesterResult = $semesterStmt->get_result();
        
        if ($semesterRow = $semesterResult->fetch_assoc()) {
            $semester_db_id = $semesterRow['id'];
        } else {
            // Create new semester
            $insertSemesterStmt = $mysqli1->prepare("
                INSERT INTO academic_plan_semesters (plan_id, semester_number, semester_name)
                VALUES (?, ?, ?)
            ");
            
            if (!$insertSemesterStmt) {
                $response['message'] = 'خطأ في قاعدة البيانات';
                echo json_encode($response);
                exit;
            }
            
            $semester_name = "الفصل " . $semester_number;
            $insertSemesterStmt->bind_param('iis', $plan_id, $semester_number, $semester_name);
            
            if (!$insertSemesterStmt->execute()) {
                $response['message'] = 'خطأ في إنشاء الفصل';
                echo json_encode($response);
                exit;
            }
            
            $semester_db_id = $insertSemesterStmt->insert_id;
            $insertSemesterStmt->close();
        }
        $semesterStmt->close();
        
        // Add subject to plan
        $insertStmt = $mysqli1->prepare("
            INSERT INTO academic_plan_subjects 
            (plan_id, semester_id, subject_id, subject_code, is_core, credit_hours)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        if (!$insertStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $insertStmt->bind_param(
            'iiisii',
            $plan_id,
            $semester_db_id,
            $subject_id,
            $subject['subjectcode'],
            $is_core,
            $subject['credit_hours']
        );
        
        if ($insertStmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'تم إضافة المقرر بنجاح';
            $response['subject'] = [
                'name' => $subject['subjectnamea'],
                'code' => $subject['subjectcode'],
                'hours' => $subject['credit_hours'],
                'is_core' => $is_core
            ];
        } else {
            $response['message'] = 'حدث خطأ أثناء إضافة المقرر';
        }
        $insertStmt->close();
        
    } elseif ($_POST['action'] === 'remove_subject') {
        // التحقق من المدخلات
        if (!isset($_POST['plan_subject_id']) || !ctype_digit($_POST['plan_subject_id'])) {
            $response['message'] = 'بيانات غير صالحة';
            echo json_encode($response);
            exit;
        }
        
        $plan_subject_id = (int)$_POST['plan_subject_id'];
        
        $deleteStmt = $mysqli1->prepare("
            DELETE FROM academic_plan_subjects WHERE id = ?
        ");
        
        if (!$deleteStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $deleteStmt->bind_param('i', $plan_subject_id);
        
        if ($deleteStmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'تم حذف المقرر بنجاح';
        } else {
            $response['message'] = 'حدث خطأ أثناء الحذف';
        }
        $deleteStmt->close();
        
    } elseif ($_POST['action'] === 'update_subject') {
        // التحقق من المدخلات
        if (!isset($_POST['plan_subject_id']) || !ctype_digit($_POST['plan_subject_id']) ||
            !isset($_POST['semester']) || !ctype_digit($_POST['semester'])) {
            $response['message'] = 'بيانات غير صالحة';
            echo json_encode($response);
            exit;
        }
        
        $plan_subject_id = (int)$_POST['plan_subject_id'];
        $semester_number = (int)$_POST['semester'];
        $is_core = isset($_POST['is_core']) ? (int)$_POST['is_core'] : 0;
        
        // Get semester id
        $semesterStmt = $mysqli1->prepare("
            SELECT id FROM academic_plan_semesters 
            WHERE plan_id = ? AND semester_number = ?
        ");
        
        if (!$semesterStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $semesterStmt->bind_param('ii', $plan_id, $semester_number);
        $semesterStmt->execute();
        $semesterResult = $semesterStmt->get_result();
        
        if ($semesterRow = $semesterResult->fetch_assoc()) {
            $semester_db_id = $semesterRow['id'];
        } else {
            // Create new semester
            $insertSemesterStmt = $mysqli1->prepare("
                INSERT INTO academic_plan_semesters (plan_id, semester_number, semester_name)
                VALUES (?, ?, ?)
            ");
            
            if (!$insertSemesterStmt) {
                $response['message'] = 'خطأ في قاعدة البيانات';
                echo json_encode($response);
                exit;
            }
            
            $semester_name = "الفصل " . $semester_number;
            $insertSemesterStmt->bind_param('iis', $plan_id, $semester_number, $semester_name);
            
            if (!$insertSemesterStmt->execute()) {
                $response['message'] = 'خطأ في إنشاء الفصل';
                echo json_encode($response);
                exit;
            }
            
            $semester_db_id = $insertSemesterStmt->insert_id;
            $insertSemesterStmt->close();
        }
        $semesterStmt->close();
        
        $updateStmt = $mysqli1->prepare("
            UPDATE academic_plan_subjects 
            SET semester_id = ?, is_core = ?
            WHERE id = ?
        ");
        
        if (!$updateStmt) {
            $response['message'] = 'خطأ في قاعدة البيانات';
            echo json_encode($response);
            exit;
        }
        
        $updateStmt->bind_param('iii', $semester_db_id, $is_core, $plan_subject_id);
        
        if ($updateStmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'تم تحديث المقرر بنجاح';
        } else {
            $response['message'] = 'حدث خطأ أثناء التحديث';
        }
        $updateStmt->close();
    }
    
    echo json_encode($response);
    exit;
}

// ================ تحسين عرض المقررات حسب التسلسل الهرمي ================
// التحقق من وجود عمود is_shared في جدول subjects
$checkColumnStmt = $mysqli1->query("SHOW COLUMNS FROM subjects LIKE 'is_shared'");
$has_is_shared = $checkColumnStmt && $checkColumnStmt->num_rows > 0;

// تحضير المتغيرات مع التحقق من القيم NULL
$college_id = (int)($plan['college_id'] ?? 0);
$program_id = (int)($plan['program_id'] ?? 0);
$section_id = (int)($plan['section_id'] ?? 0);
$specialization_id = (int)($plan['specialization_id'] ?? 0);

// بناء الاستعلام بناءً على وجود العمود is_shared
if ($has_is_shared) {
    $subjectsQuery = "
        SELECT s.*,
               CASE 
                   WHEN (s.program_id = 0 OR s.program_id IS NULL) AND 
                        (s.section_id = 0 OR s.section_id IS NULL) AND 
                        (s.specialization_id = 0 OR s.specialization_id IS NULL) THEN 'college'
                   WHEN (s.section_id = 0 OR s.section_id IS NULL) AND 
                        (s.specialization_id = 0 OR s.specialization_id IS NULL) THEN 'program'
                   WHEN (s.specialization_id = 0 OR s.specialization_id IS NULL) THEN 'section'
                   ELSE 'specialization'
               END as subject_level
        FROM subjects s
        WHERE s.is_active = 1
        AND s.deleted_at IS NULL
        AND (
            (s.college_id = ? AND (s.program_id = 0 OR s.program_id IS NULL) AND (s.section_id = 0 OR s.section_id IS NULL) AND (s.specialization_id = 0 OR s.specialization_id IS NULL))
            OR (s.college_id = ? AND s.program_id = ? AND (s.section_id = 0 OR s.section_id IS NULL) AND (s.specialization_id = 0 OR s.specialization_id IS NULL))
            OR (s.college_id = ? AND s.program_id = ? AND s.section_id = ? AND (s.specialization_id = 0 OR s.specialization_id IS NULL))
            OR (s.college_id = ? AND s.program_id = ? AND s.section_id = ? AND s.specialization_id = ?)
            OR (s.college_id = ? AND s.program_id = ? AND (s.section_id = 0 OR s.section_id IS NULL) AND s.is_shared = 1)
        )
        ORDER BY 
            CASE subject_level
                WHEN 'college' THEN 1
                WHEN 'program' THEN 2
                WHEN 'section' THEN 3
                WHEN 'specialization' THEN 4
            END,
            s.subjectcode
    ";
    
    $subjectsStmt = $mysqli1->prepare($subjectsQuery);
    
    if (!$subjectsStmt) {
        error_log("Error in subjects query: " . $mysqli1->error);
        $all_subjects = [];
    } else {
        $subjectsStmt->bind_param('iiiiiiiiiii', 
            $college_id,                   
            $college_id, $program_id,       
            $college_id, $program_id, $section_id,
            $college_id, $program_id, $section_id, $specialization_id,
            $college_id, $program_id        
        );
        $subjectsStmt->execute();
        $subjectsResult = $subjectsStmt->get_result();
        $all_subjects = $subjectsResult->fetch_all(MYSQLI_ASSOC);
        $subjectsStmt->close();
    }
} else {
    $subjectsQuery = "
        SELECT s.*,
               CASE 
                   WHEN (s.program_id = 0 OR s.program_id IS NULL) AND 
                        (s.section_id = 0 OR s.section_id IS NULL) AND 
                        (s.specialization_id = 0 OR s.specialization_id IS NULL) THEN 'college'
                   WHEN (s.section_id = 0 OR s.section_id IS NULL) AND 
                        (s.specialization_id = 0 OR s.specialization_id IS NULL) THEN 'program'
                   WHEN (s.specialization_id = 0 OR s.specialization_id IS NULL) THEN 'section'
                   ELSE 'specialization'
               END as subject_level
        FROM subjects s
        WHERE s.is_active = 1
        AND s.deleted_at IS NULL
        AND (
            (s.college_id = ? AND (s.program_id = 0 OR s.program_id IS NULL) AND (s.section_id = 0 OR s.section_id IS NULL) AND (s.specialization_id = 0 OR s.specialization_id IS NULL))
            OR (s.college_id = ? AND s.program_id = ? AND (s.section_id = 0 OR s.section_id IS NULL) AND (s.specialization_id = 0 OR s.specialization_id IS NULL))
            OR (s.college_id = ? AND s.program_id = ? AND s.section_id = ? AND (s.specialization_id = 0 OR s.specialization_id IS NULL))
            OR (s.college_id = ? AND s.program_id = ? AND s.section_id = ? AND s.specialization_id = ?)
        )
        ORDER BY 
            CASE subject_level
                WHEN 'college' THEN 1
                WHEN 'program' THEN 2
                WHEN 'section' THEN 3
                WHEN 'specialization' THEN 4
            END,
            s.subjectcode
    ";
    
    $subjectsStmt = $mysqli1->prepare($subjectsQuery);
    
    if (!$subjectsStmt) {
        error_log("Error in subjects query: " . $mysqli1->error);
        $all_subjects = [];
    } else {
        $subjectsStmt->bind_param('iiiiiiiiii', 
            $college_id,                   
            $college_id, $program_id,       
            $college_id, $program_id, $section_id,
            $college_id, $program_id, $section_id, $specialization_id
        );
        $subjectsStmt->execute();
        $subjectsResult = $subjectsStmt->get_result();
        $all_subjects = $subjectsResult->fetch_all(MYSQLI_ASSOC);
        $subjectsStmt->close();
    }
}

// تجميع المقررات حسب المستوى
$subjects_by_level = [
    'college' => [],
    'program' => [],
    'section' => [],
    'specialization' => []
];

foreach ($all_subjects as $subject) {
    $level = $subject['subject_level'];
    if (isset($subjects_by_level[$level])) {
        $subjects_by_level[$level][] = $subject;
    }
}

// Get plan subjects organized by semester
$planSubjectsStmt = $mysqli1->prepare("
    SELECT 
        aps.id as plan_subject_id,
        aps.subject_id,
        aps.subject_code,
        aps.is_core,
        aps.credit_hours,
        aps.semester_id,
        aps_sem.semester_number,
        s.subjectnamea,
        s.subjectnamee
    FROM academic_plan_subjects aps
    JOIN academic_plan_semesters aps_sem ON aps.semester_id = aps_sem.id
    JOIN subjects s ON aps.subject_id = s.id
    WHERE aps.plan_id = ?
    ORDER BY aps_sem.semester_number, aps.subject_code
");

if (!$planSubjectsStmt) {
    error_log("Error in plan subjects query: " . $mysqli1->error);
    $plan_subjects = [];
    $subjects_by_semester = [];
    $subject_ids_in_plan = [];
    $total_hours_by_semester = [];
} else {
    $planSubjectsStmt->bind_param('i', $plan_id);
    $planSubjectsStmt->execute();
    $planSubjectsResult = $planSubjectsStmt->get_result();
    $plan_subjects = $planSubjectsResult->fetch_all(MYSQLI_ASSOC);
    $planSubjectsStmt->close();
    
    $subjects_by_semester = [];
    $subject_ids_in_plan = [];
    $total_hours_by_semester = [];
    
    foreach ($plan_subjects as $ps) {
        $semester = $ps['semester_number'];
        if (!isset($subjects_by_semester[$semester])) {
            $subjects_by_semester[$semester] = [];
            $total_hours_by_semester[$semester] = 0;
        }
        $subjects_by_semester[$semester][] = $ps;
        $subject_ids_in_plan[$ps['subject_id']] = true;
        $total_hours_by_semester[$semester] += $ps['credit_hours'];
    }
}

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة مقررات الخطة - <?= htmlspecialchars($plan['plan_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></title>
    <link rel="stylesheet" href="css/style4.css">
    <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;500;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" />
    <style>
        /* Reset and Base Styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Cairo', sans-serif;
            /*background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
              background-color: #f8fafc;
            min-height: 100vh;
        }
        
        .main-wrapper {
            padding: 30px 20px;
        }
        
        /* Glassmorphism Cards */
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .glass-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 80px rgba(0, 0, 0, 0.4);
        }
        
        /* Header Styles */
        .page-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            border-radius: 30px;
            padding: 40px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            position: relative;
            overflow: hidden;
        }
        
        .page-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            animation: rotate 20s linear infinite;
        }
        
        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        .page-header h1 {
            color: white;
            font-size: 2.5rem;
            font-weight: 800;
            margin: 0;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
            position: relative;
            z-index: 2;
        }
        
        .page-header p {
            color: rgba(255,255,255,0.9);
            font-size: 1.1rem;
            margin-top: 10px;
            position: relative;
            z-index: 2;
        }
        
        /* Header Buttons */
        .header-buttons {
            display: flex;
            gap: 15px;
            position: relative;
            z-index: 2;
        }
        
        .btn-back {
            background: rgba(255, 255, 255, 0.15);
            border: 2px solid rgba(255, 255, 255, 0.5);
            color: white;
            padding: 12px 30px;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            backdrop-filter: blur(5px);
        }
        
        .btn-back:hover {
            background: white;
            color: #1e3c72;
            border-color: white;
            transform: translateY(-2px);
            text-decoration: none;
        }
        
        .btn-edit {
            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-edit:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 176, 155, 0.6);
            color: white;
            text-decoration: none;
        }
        
        /* Plan Info Card */
        .plan-info {
            background: white;
            border-radius: 30px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            border-right: 5px solid #667eea;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 20px;
            border: 1px solid rgba(102, 126, 234, 0.1);
            transition: all 0.3s ease;
        }
        
        .info-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.2);
        }
        
        .info-icon {
            width: 45px;
            height: 45px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.3rem;
        }
        
        /* Statistics Cards */
        .stat-card {
            background: white;
            border-radius: 25px;
            padding: 30px 20px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            border: 1px solid rgba(102, 126, 234, 0.1);
            height: 100%;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
        }
        
        .stat-icon {
            font-size: 2.8rem;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 15px;
        }
        
        .stat-number {
            font-size: 2.2rem;
            font-weight: 800;
            color: #2d3748;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #718096;
            font-weight: 600;
            font-size: 1rem;
        }
        
        /* Add Subject Section */
        .add-section {
            background: white;
            border-radius: 30px;
            padding: 35px;
            margin-top: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            border: 2px dashed #667eea;
        }
        
        .add-section h5 {
            color: #2d3748;
            font-weight: 700;
            margin-bottom: 25px;
            font-size: 1.3rem;
        }
        
        .add-section h5 i {
            color: #667eea;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
            font-size: 1rem;
        }
        
        .form-control, .form-select {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 12px 15px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: white;
            height: 50px;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }
        
        /* Subject Type Selector */
        .type-selector {
            display: flex;
            gap: 10px;
            margin-top: 5px;
        }
        
        .type-option {
            flex: 1;
            text-align: center;
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
            background: white;
        }
        
        .type-option.core.active {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            border-color: #84fab0;
            color: #1e4620;
        }
        
        .type-option.elective.active {
            background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
            border-color: #fda085;
            color: #7f4f24;
        }
        
        .type-option:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        /* Semester Cards */
        .semester-card {
            background: white;
            border-radius: 25px;
            border: 1px solid #e5e7eb;
            margin-bottom: 25px;
            overflow: hidden;
            transition: all 0.3s ease;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            height: calc(100% - 25px);
        }
        
        .semester-card:hover {
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.2);
            transform: translateY(-5px);
        }
        
        .semester-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            padding: 20px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: white;
        }
        
        .semester-header h4 {
            margin: 0;
            font-weight: 700;
            font-size: 1.3rem;
        }
        
        .semester-header h4 i {
            margin-left: 10px;
        }
        
        .semester-total {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 8px 20px;
            border-radius: 50px;
            font-size: 1rem;
            font-weight: 600;
            backdrop-filter: blur(5px);
        }
        
        .semester-body {
            padding: 20px;
        }
        
        /* Subject Items */
        .subject-item {
            padding: 20px;
            border-bottom: 1px solid #eef2f6;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
            background: white;
        }
        
        .subject-item:last-child {
            border-bottom: none;
        }
        
        .subject-item:hover {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        }
        
        .subject-code {
            background: #667eea;
            color: white;
            padding: 5px 15px;
            border-radius: 50px;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        .core-badge {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e4620;
            padding: 5px 15px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        .elective-badge {
            background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
            color: #7f4f24;
            padding: 5px 15px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        .hours-badge {
            background: #e9ecef;
            padding: 5px 15px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        /* Action Buttons */
        .subject-actions {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1rem;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
        }
        
        .action-btn:hover {
            transform: translateY(-3px) scale(1.1);
        }
        
        .btn-edit-subject {
            background: linear-gradient(135deg, #f6d365, #fda085);
        }
        
        .btn-remove-subject {
            background: linear-gradient(135deg, #fc6767, #ec008c);
        }
        
        /* Level Badges */
        .level-badge {
            display: inline-block;
            padding: 6px 15px;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 600;
            margin-left: 10px;
        }
        
        .level-college {
            background: #cff4fc;
            color: #055160;
            border: 1px solid #9eeaf9;
        }
        
        .level-program {
            background: #d1e7dd;
            color: #0f5132;
            border: 1px solid #a3cfbb;
        }
        
        .level-section {
            background: #fff3cd;
            color: #664d03;
            border: 1px solid #ffe69c;
        }
        
        .level-specialization {
            background: #f8d7da;
            color: #842029;
            border: 1px solid #f1aeb5;
        }
        
        /* Select2 Customization */
        .select2-container--default .select2-selection--single {
            height: 50px;
            border: 2px solid #e2e8f0;
            border-radius: 15px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 46px;
            padding: 0 15px;
            font-size: 1rem;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px;
        }
        
        .select2-dropdown {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
        }
        
        /* Empty State */
        .empty-semester {
            padding: 50px 20px;
            text-align: center;
            color: #718096;
        }
        
        .empty-semester i {
            font-size: 4rem;
            color: #cbd5e0;
            margin-bottom: 20px;
        }
        
        .empty-semester p {
            font-size: 1.1rem;
            margin-bottom: 10px;
        }
        
        /* Loading Spinner */
        .loading-spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 4px solid rgba(102, 126, 234, 0.3);
            border-radius: 50%;
            border-top-color: #667eea;
            animation: spin 1s ease-in-out infinite;
        }
        
        /* Modal Styles */
        .modal-content {
            border-radius: 30px;
            border: none;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
            border-radius: 30px 30px 0 0;
            padding: 20px 30px;
        }
        
        .modal-header h5 {
            font-size: 1.3rem;
            font-weight: 700;
        }
        
        .modal-body {
            padding: 30px;
        }
        
        .modal-footer {
            padding: 20px 30px;
            border-top: 1px solid #e2e8f0;
        }
        
        /* Alerts */
        .alert {
            border-radius: 20px;
            border: none;
            padding: 20px 30px;
            font-weight: 600;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.5s ease;
            margin-bottom: 30px;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-20px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        .alert-success {
            background: linear-gradient(135deg, #84fab0, #8fd3f4);
            color: #1e4620;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #fc6767, #ec008c);
            color: white;
        }
        
        /* RTL Specific */
        .me-1 { margin-left: 0.25rem !important; margin-right: 0 !important; }
        .me-2 { margin-left: 0.5rem !important; margin-right: 0 !important; }
        .me-3 { margin-left: 1rem !important; margin-right: 0 !important; }
        .ms-1 { margin-right: 0.25rem !important; margin-left: 0 !important; }
        .ms-2 { margin-right: 0.5rem !important; margin-left: 0 !important; }
        .ms-3 { margin-right: 1rem !important; margin-left: 0 !important; }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-header {
                padding: 30px 20px;
            }
            
            .page-header h1 {
                font-size: 1.8rem;
            }
            
            .header-buttons {
                flex-direction: column;
                gap: 10px;
                margin-top: 20px;
            }
            
            .header-buttons a {
                width: 100%;
                justify-content: center;
            }
            
            .semester-header {
                flex-direction: column;
                gap: 10px;
                text-align: center;
            }
            
            .subject-item {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
            
            .subject-item > div:first-child {
                width: 100%;
            }
            
            .subject-actions {
                justify-content: center;
            }
            
            .type-selector {
                flex-direction: column;
            }
        }
        
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 12px;
        }
        
        ::-webkit-scrollbar-track {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9edf5 100%);
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 6px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: linear-gradient(135deg, #764ba2, #667eea);
        }
    </style>
</head>
<body dir="rtl">
    <div class="main-wrapper">
        <div class="container-fluid px-4">
            <!-- Header -->
            <div class="page-header d-flex flex-wrap align-items-center justify-content-between">
                <div>
                    <h1 class="mb-2">
                        <i class="fas fa-book ms-3"></i>
                        إدارة مقررات الخطة
                    </h1>
                    <p class="mb-0">
                        <i class="fas fa-layer-group ms-2"></i>
                        إضافة وتعديل مقررات الخطة: <?= htmlspecialchars($plan['plan_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                    </p>
                </div>
                <div class="header-buttons">
                    <a href="academic_plans_list.php" class="btn-back">
                        <i class="fas fa-arrow-right ms-2"></i> 
                        العودة للقائمة
                    </a>
                    
                    <a href="academic_plan_view.php?id=<?= (int)$plan_id ?>" class="btn-edit" style="background: transparent; border: 2px solid rgba(255,255,255,0.5);">
                        <i class="fas fa-eye ms-2"></i>
                        عرض الخطة
                    </a>
                    
                    <a href="academic_plan_edit.php?id=<?= (int)$plan_id ?>" class="btn-edit">
                        <i class="fas fa-edit ms-2"></i>
                        تعديل الخطة
                    </a>
                </div>
            </div>

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

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

            <!-- Plan Information -->
            <div class="plan-info">
                <h5 class="fw-bold mb-4">
                    <i class="fas fa-info-circle ms-2" style="color: #667eea;"></i>
                    معلومات الخطة
                </h5>
                
                <div class="row g-4">
                    <div class="col-md-3">
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-tag"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block">رمز الخطة</small>
                                <span class="fw-bold fs-5"><?= htmlspecialchars($plan['plan_code'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-university"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block">الكلية</small>
                                <span class="fw-bold fs-5"><?= htmlspecialchars($plan['college_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-building"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block">القسم</small>
                                <span class="fw-bold fs-5"><?= htmlspecialchars($plan['section_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-graduation-cap"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block">البرنامج</small>
                                <span class="fw-bold fs-5"><?= htmlspecialchars($plan['program_name'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <?php if (!empty($plan['specialization_name'])): ?>
                    <div class="col-md-3">
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-tag"></i>
                            </div>
                            <div>
                                <small class="text-muted d-block">التخصص</small>
                                <span class="fw-bold fs-5"><?= htmlspecialchars($plan['specialization_name'], ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Statistics -->
            <div class="row g-4 mb-4">
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-book"></i>
                        </div>
                        <div class="stat-number"><?= (int)count($plan_subjects) ?></div>
                        <div class="stat-label">إجمالي المقررات</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-star"></i>
                        </div>
                        <div class="stat-number"><?= (int)count(array_filter($plan_subjects, function($ps) { return $ps['is_core']; })) ?></div>
                        <div class="stat-label">المقررات الأساسية</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="stat-number"><?= (int)array_sum(array_column($plan_subjects, 'credit_hours')) ?></div>
                        <div class="stat-label">إجمالي الساعات</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-layer-group"></i>
                        </div>
                        <div class="stat-number"><?= (int)count($subjects_by_semester) ?></div>
                        <div class="stat-label">فصول تحتوي مقررات</div>
                    </div>
                </div>
            </div>

            <!-- Add Subject Section -->
            <div class="add-section">
                <h5>
                    <i class="fas fa-plus-circle ms-2"></i>
                    إضافة مقرر جديدة إلى الخطة
                </h5>
                
                <div class="alert alert-info mb-4">
                    <i class="fas fa-info-circle ms-2"></i>
                    يتم عرض المقررات حسب التسلسل الهرمي:
                    <span class="level-badge level-college ms-2">مقررات الكلية</span>
                    <span class="level-badge level-program">مقررات البرنامج</span>
                    <span class="level-badge level-section">مقررات القسم</span>
                    <span class="level-badge level-specialization">مقررات التخصص</span>
                </div>
                
                <div class="row g-4">
                    <div class="col-md-3">
                        <label class="form-label">الفصل الدراسي</label>
                        <select class="form-select" id="add_semester">
                            <?php 
                            $total_semesters = (int)($plan['total_semesters'] ?? 8);
                            for ($i = 1; $i <= $total_semesters; $i++): 
                            ?>
                                <option value="<?= $i ?>">الفصل <?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">اختر المقرر</label>
                        <select class="form-select" id="add_subject" style="width: 100%">
                            <option value="">اختر المقرر...</option>
                            
                            <?php if (!empty($subjects_by_level['college'])): ?>
                            <optgroup label="📚 مقررات الكلية">
                                <?php foreach ($subjects_by_level['college'] as $subject): ?>
                                    <?php if (!isset($subject_ids_in_plan[$subject['id']])): ?>
                                        <option value="<?= (int)$subject['id'] ?>" 
                                                data-code="<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                data-hours="<?= (int)($subject['credit_hours'] ?? 0) ?>">
                                            [<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>] <?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?> 
                                            (<?= (int)($subject['credit_hours'] ?? 0) ?> ساعة)
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endif; ?>
                            
                            <?php if (!empty($subjects_by_level['program'])): ?>
                            <optgroup label="🎓 مقررات البرنامج">
                                <?php foreach ($subjects_by_level['program'] as $subject): ?>
                                    <?php if (!isset($subject_ids_in_plan[$subject['id']])): ?>
                                        <option value="<?= (int)$subject['id'] ?>" 
                                                data-code="<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                data-hours="<?= (int)($subject['credit_hours'] ?? 0) ?>">
                                            [<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>] <?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?> 
                                            (<?= (int)($subject['credit_hours'] ?? 0) ?> ساعة)
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endif; ?>
                            
                            <?php if (!empty($subjects_by_level['section'])): ?>
                            <optgroup label="🏢 مقررات القسم">
                                <?php foreach ($subjects_by_level['section'] as $subject): ?>
                                    <?php if (!isset($subject_ids_in_plan[$subject['id']])): ?>
                                        <option value="<?= (int)$subject['id'] ?>" 
                                                data-code="<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                data-hours="<?= (int)($subject['credit_hours'] ?? 0) ?>">
                                            [<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>] <?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?> 
                                            (<?= (int)($subject['credit_hours'] ?? 0) ?> ساعة)
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endif; ?>
                            
                            <?php if (!empty($subjects_by_level['specialization'])): ?>
                            <optgroup label="🔬 مقررات التخصص">
                                <?php foreach ($subjects_by_level['specialization'] as $subject): ?>
                                    <?php if (!isset($subject_ids_in_plan[$subject['id']])): ?>
                                        <option value="<?= (int)$subject['id'] ?>" 
                                                data-code="<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                data-hours="<?= (int)($subject['credit_hours'] ?? 0) ?>">
                                            [<?= htmlspecialchars($subject['subjectcode'] ?? '', ENT_QUOTES, 'UTF-8') ?>] <?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?> 
                                            (<?= (int)($subject['credit_hours'] ?? 0) ?> ساعة)
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endif; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">نوع المقرر</label>
                        <div class="type-selector">
                            <div class="type-option core active" id="option_core" onclick="setSubjectType('core')">
                                <i class="fas fa-star ms-1"></i>
                                أساسي
                            </div>
                            <div class="type-option elective" id="option_elective" onclick="setSubjectType('elective')">
                                <i class="fas fa-circle ms-1"></i>
                                اختياري
                            </div>
                        </div>
                        <input type="hidden" id="add_is_core" value="1">
                    </div>
                </div>
                
                <div class="row mt-4">
                    <div class="col-12">
                        <button type="button" class="btn-edit" id="btnAddSubject" style="width: 200px;">
                            <i class="fas fa-plus ms-2"></i>إضافة المقرر
                        </button>
                    </div>
                </div>
                
                <div class="mt-4 text-muted small">
                    <i class="fas fa-info-circle ms-1"></i>
                    إجمالي المقررات المتاحة: <?= (int)count($all_subjects) ?> مقرر
                    (الكلية: <?= (int)count($subjects_by_level['college']) ?> | 
                     البرنامج: <?= (int)count($subjects_by_level['program']) ?> | 
                     القسم: <?= (int)count($subjects_by_level['section']) ?> | 
                     التخصص: <?= (int)count($subjects_by_level['specialization']) ?>)
                </div>
            </div>
            
            <!-- Subjects by Semester -->
            <div class="row g-4">
                <?php 
                $total_semesters = (int)($plan['total_semesters'] ?? 8);
                for ($sem = 1; $sem <= $total_semesters; $sem++): 
                ?>
                    <div class="col-lg-6">
                        <div class="semester-card" id="semester-<?= $sem ?>">
                            <div class="semester-header">
                                <h4>
                                    <i class="fas fa-calendar-alt"></i>
                                    الفصل <?= $sem ?>
                                </h4>
                                <div>
                                    <span class="semester-total">
                                        <i class="fas fa-clock ms-1"></i>
                                        <?= (int)($total_hours_by_semester[$sem] ?? 0) ?> ساعة
                                    </span>
                                </div>
                            </div>
                            <div class="semester-body">
                                <?php if (isset($subjects_by_semester[$sem]) && !empty($subjects_by_semester[$sem])): ?>
                                    <?php foreach ($subjects_by_semester[$sem] as $subject): ?>
                                        <div class="subject-item" id="subject-<?= (int)$subject['plan_subject_id'] ?>">
                                            <div>
                                                <div class="d-flex align-items-center gap-2 mb-3 flex-wrap">
                                                    <span class="subject-code"><?= htmlspecialchars($subject['subject_code'] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                                                    <?php if ($subject['is_core']): ?>
                                                        <span class="core-badge">أساسي</span>
                                                    <?php else: ?>
                                                        <span class="elective-badge">اختياري</span>
                                                    <?php endif; ?>
                                                    <span class="hours-badge">
                                                        <?= (int)($subject['credit_hours'] ?? 0) ?> س
                                                    </span>
                                                </div>
                                                <div class="fw-bold fs-5"><?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                                                <?php if (!empty($subject['subjectnamee'])): ?>
                                                    <small class="text-muted"><?= htmlspecialchars($subject['subjectnamee'], ENT_QUOTES, 'UTF-8') ?></small>
                                                <?php endif; ?>
                                            </div>
                                            <div class="subject-actions">
                                                <button type="button" 
                                                        class="action-btn btn-edit-subject edit-subject"
                                                        data-id="<?= (int)$subject['plan_subject_id'] ?>"
                                                        data-subject="<?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                        data-code="<?= htmlspecialchars($subject['subject_code'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                        data-semester="<?= $sem ?>"
                                                        data-core="<?= (int)($subject['is_core'] ?? 0) ?>"
                                                        title="تعديل">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" 
                                                        class="action-btn btn-remove-subject remove-subject"
                                                        data-id="<?= (int)$subject['plan_subject_id'] ?>"
                                                        data-subject="<?= htmlspecialchars($subject['subjectnamea'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                                        title="حذف">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="empty-semester">
                                        <i class="fas fa-folder-open"></i>
                                        <p class="mb-2">لا توجد مقررات في هذا الفصل</p>
                                        <small class="text-muted">يمكنك إضافة مقررات من النموذج أعلاه</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endfor; ?>
            </div>
        </div>
    </div>

    <!-- Edit Subject Modal -->
    <div class="modal fade" id="editSubjectModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold">
                        <i class="fas fa-edit ms-2" style="color: #667eea;"></i>
                        تعديل المقرر في الخطة
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="edit_plan_subject_id">
                    
                    <div class="mb-4">
                        <label class="form-label">المقرر</label>
                        <div class="info-item">
                            <div class="info-icon">
                                <i class="fas fa-book"></i>
                            </div>
                            <input type="text" class="form-control" id="edit_subject_name" readonly style="background: #f8fafc;">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label">الفصل الدراسي</label>
                        <select class="form-select" id="edit_semester">
                            <?php 
                            $total_semesters = (int)($plan['total_semesters'] ?? 8);
                            for ($i = 1; $i <= $total_semesters; $i++): 
                            ?>
                                <option value="<?= $i ?>">الفصل <?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">نوع المقرر</label>
                        <div class="type-selector">
                            <div class="type-option core" id="edit_option_core" onclick="setEditSubjectType('core')">
                                <i class="fas fa-star ms-1"></i>
                                أساسي
                            </div>
                            <div class="type-option elective" id="edit_option_elective" onclick="setEditSubjectType('elective')">
                                <i class="fas fa-circle ms-1"></i>
                                اختياري
                            </div>
                        </div>
                        <input type="hidden" id="edit_is_core" value="1">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-back" data-bs-dismiss="modal" style="background: transparent; border: 2px solid #6b7280; color: #6b7280;">
                        إلغاء
                    </button>
                    <button type="button" class="btn-edit" id="btnUpdateSubject">
                        <i class="fas fa-save ms-2"></i>تحديث
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Loading Overlay -->
    <div id="loadingOverlay" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.9); z-index: 9999; justify-content: center; align-items: center;">
        <div class="text-center">
            <div class="loading-spinner" style="width: 60px; height: 60px;"></div>
            <p class="mt-4 fw-bold fs-5" style="color: #667eea;">جاري التحميل...</p>
        </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>
    // دالة لتحديد نوع المقرر في الإضافة
    function setSubjectType(type) {
        if (type === 'core') {
            $('#option_core').addClass('active');
            $('#option_elective').removeClass('active');
            $('#add_is_core').val('1');
        } else {
            $('#option_core').removeClass('active');
            $('#option_elective').addClass('active');
            $('#add_is_core').val('0');
        }
    }
    
    // دالة لتحديد نوع المقرر في التعديل
    function setEditSubjectType(type) {
        if (type === 'core') {
            $('#edit_option_core').addClass('active');
            $('#edit_option_elective').removeClass('active');
            $('#edit_is_core').val('1');
        } else {
            $('#edit_option_core').removeClass('active');
            $('#edit_option_elective').addClass('active');
            $('#edit_is_core').val('0');
        }
    }
    
    $(document).ready(function() {
        // Initialize Select2
        $('#add_subject').select2({
            placeholder: 'اختر المقرر...',
            width: '100%',
            language: {
                noResults: function() {
                    return "لا توجد نتائج";
                },
                searching: function() {
                    return "جاري البحث...";
                }
            }
        });
        
        // Show loading overlay
        function showLoading() {
            $('#loadingOverlay').fadeIn(200).css('display', 'flex');
        }
        
        function hideLoading() {
            $('#loadingOverlay').fadeOut(200);
        }
        
        // Add subject
        $('#btnAddSubject').on('click', function() {
            const semester = $('#add_semester').val();
            const subjectId = $('#add_subject').val();
            const isCore = $('#add_is_core').val();
            
            if (!subjectId) {
                alert('⚠️ الرجاء اختيار مقرر');
                return;
            }
            
            showLoading();
            
            $.ajax({
                url: 'academic_plan_subjects.php?id=<?= (int)$plan_id ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'add_subject',
                    semester: semester,
                    subject_id: subjectId,
                    is_core: isCore
                },
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        alert('✅ ' + response.message);
                        location.reload();
                    } else {
                        alert('❌ ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    hideLoading();
                    console.error('Error:', error);
                    alert('❌ حدث خطأ أثناء إضافة المقرر');
                }
            });
        });
        
        // Remove subject
        $('.remove-subject').on('click', function() {
            const id = $(this).data('id');
            const subjectName = $(this).data('subject');
            
            if (!confirm('⚠️ هل أنت متأكد من حذف المقرر "' + subjectName + '" من الخطة؟')) {
                return;
            }
            
            showLoading();
            
            $.ajax({
                url: 'academic_plan_subjects.php?id=<?= (int)$plan_id ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'remove_subject',
                    plan_subject_id: id
                },
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        alert('✅ ' + response.message);
                        location.reload();
                    } else {
                        alert('❌ ' + response.message);
                    }
                },
                error: function() {
                    hideLoading();
                    alert('❌ حدث خطأ أثناء حذف المقرر');
                }
            });
        });
        
        // Edit subject
        $('.edit-subject').on('click', function() {
            const id = $(this).data('id');
            const subjectName = $(this).data('subject');
            const semester = $(this).data('semester');
            const isCore = $(this).data('core');
            
            $('#edit_plan_subject_id').val(id);
            $('#edit_subject_name').val(subjectName);
            $('#edit_semester').val(semester);
            $('#edit_is_core').val(isCore);
            
            if (isCore == 1) {
                $('#edit_option_core').addClass('active');
                $('#edit_option_elective').removeClass('active');
            } else {
                $('#edit_option_core').removeClass('active');
                $('#edit_option_elective').addClass('active');
            }
            
            $('#editSubjectModal').modal('show');
        });
        
        // Update subject
        $('#btnUpdateSubject').on('click', function() {
            const id = $('#edit_plan_subject_id').val();
            const semester = $('#edit_semester').val();
            const isCore = $('#edit_is_core').val();
            
            showLoading();
            
            $.ajax({
                url: 'academic_plan_subjects.php?id=<?= (int)$plan_id ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'update_subject',
                    plan_subject_id: id,
                    semester: semester,
                    is_core: isCore
                },
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        alert('✅ ' + response.message);
                        location.reload();
                    } else {
                        alert('❌ ' + response.message);
                    }
                },
                error: function() {
                    hideLoading();
                    alert('❌ حدث خطأ أثناء تحديث المقرر');
                }
            });
        });
        
        // Auto-hide alerts
        setTimeout(function() {
            $('.alert').fadeOut(500, function() {
                $(this).remove();
            });
        }, 5000);
    });
    </script>
</body>
</html>
<?php include 'footer.php'; ?>