<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'db.php';
require_once 'helpers.php';

// التحقق من اتصال قاعدة البيانات
if (!$mysqli1) {
    die("خطأ في اتصال قاعدة البيانات: " . mysqli_connect_error());
}

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

// معالجة الطلبات (إضافة، تعديل، حذف)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add') {
        $subjectcode = trim($_POST['subjectcode']);
        $program_id = (int)$_POST['program_id'];
        $college_id = (int)$_POST['college_id'];
        $section_id = (int)$_POST['section_id'];
        $specialization_id = (int)$_POST['specialization_id'];
        $subjecthours = (int)$_POST['subjecthours'];
        $subjectnamea = trim($_POST['subjectnamea']);
        $subjectnamee = trim($_POST['subjectnamee']);
        $credit_hours = !empty($_POST['credit_hours']) ? (float)$_POST['credit_hours'] : 3.00;
        $subjecttype_id = !empty($_POST['subjecttype_id']) ? (int)$_POST['subjecttype_id'] : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // التحقق من صحة البيانات
        if (empty($subjectcode) || empty($subjectnamea) || empty($subjectnamee) || 
            $program_id <= 0 || $college_id <= 0 || $section_id <= 0 || $specialization_id <= 0 || $subjecthours <= 0) {
            $_SESSION['error_message'] = "الرجاء ملء جميع الحقول المطلوبة";
            header("Location: courses_management.php");
            exit;
        }
        
        // التحقق من وجود جدول courses
        $check_table = $mysqli1->query("SHOW TABLES LIKE 'courses'");
        if ($check_table->num_rows == 0) {
            // إنشاء جدول courses إذا لم يكن موجوداً (حسب هيكل subjects)
            $create_table = "CREATE TABLE IF NOT EXISTS `courses` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `subjectcode` varchar(20) NOT NULL,
                `program_id` int(11) NOT NULL,
                `college_id` int(11) NOT NULL,
                `section_id` int(11) NOT NULL,
                `specialization_id` int(11) NOT NULL,
                `subjecthours` int(11) NOT NULL,
                `subjectnamea` varchar(255) NOT NULL,
                `subjectnamee` varchar(255) NOT NULL,
                `credit_hours` decimal(4,2) DEFAULT 3.00,
                `subjecttype_id` int(11) DEFAULT NULL,
                `is_active` tinyint(1) DEFAULT 1,
                `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
                `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
                `deleted_at` timestamp NULL DEFAULT NULL,
                PRIMARY KEY (`id`),
                KEY `subjectcode` (`subjectcode`),
                KEY `program_id` (`program_id`),
                KEY `college_id` (`college_id`),
                KEY `section_id` (`section_id`),
                KEY `specialization_id` (`specialization_id`),
                KEY `subjecttype_id` (`subjecttype_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            
            if (!$mysqli1->query($create_table)) {
                $_SESSION['error_message'] = "خطأ في إنشاء الجدول: " . $mysqli1->error;
                header("Location: courses_management.php");
                exit;
            }
        }
        
        $sql = "INSERT INTO courses (subjectcode, program_id, college_id, section_id, specialization_id, subjecthours, subjectnamea, subjectnamee, credit_hours, subjecttype_id, is_active) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $mysqli1->prepare($sql);
        
        if (!$stmt) {
            $_SESSION['error_message'] = "خطأ في تحضير الاستعلام: " . $mysqli1->error;
            header("Location: courses_management.php");
            exit;
        }
        
        $stmt->bind_param('siiiiisssdi', $subjectcode, $program_id, $college_id, $section_id, $specialization_id, 
                         $subjecthours, $subjectnamea, $subjectnamee, $credit_hours, $subjecttype_id, $is_active);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "تم إضافة المقرر الدراسي بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء الإضافة: " . $stmt->error;
        }
        $stmt->close();
        
        header("Location: courses_management.php");
        exit;
    }
    
    elseif ($action == 'edit') {
        $id = (int)$_POST['id'];
        $subjectcode = trim($_POST['subjectcode']);
        $program_id = (int)$_POST['program_id'];
        $college_id = (int)$_POST['college_id'];
        $section_id = (int)$_POST['section_id'];
        $specialization_id = (int)$_POST['specialization_id'];
        $subjecthours = (int)$_POST['subjecthours'];
        $subjectnamea = trim($_POST['subjectnamea']);
        $subjectnamee = trim($_POST['subjectnamee']);
        $credit_hours = !empty($_POST['credit_hours']) ? (float)$_POST['credit_hours'] : 3.00;
        $subjecttype_id = !empty($_POST['subjecttype_id']) ? (int)$_POST['subjecttype_id'] : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if ($id <= 0 || empty($subjectcode) || empty($subjectnamea) || empty($subjectnamee) || 
            $program_id <= 0 || $college_id <= 0 || $section_id <= 0 || $specialization_id <= 0 || $subjecthours <= 0) {
            $_SESSION['error_message'] = "بيانات غير صالحة";
            header("Location: courses_management.php");
            exit;
        }
        
        $sql = "UPDATE courses SET subjectcode=?, program_id=?, college_id=?, section_id=?, specialization_id=?, 
                subjecthours=?, subjectnamea=?, subjectnamee=?, credit_hours=?, subjecttype_id=?, is_active=? 
                WHERE id=?";
        $stmt = $mysqli1->prepare($sql);
        
        if (!$stmt) {
            $_SESSION['error_message'] = "خطأ في تحضير الاستعلام: " . $mysqli1->error;
            header("Location: courses_management.php");
            exit;
        }
        
        $stmt->bind_param('siiiiisssdii', $subjectcode, $program_id, $college_id, $section_id, $specialization_id, 
                         $subjecthours, $subjectnamea, $subjectnamee, $credit_hours, $subjecttype_id, $is_active, $id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "تم تحديث بيانات المقرر بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء التحديث: " . $stmt->error;
        }
        $stmt->close();
        
        header("Location: courses_management.php");
        exit;
    }
    
    elseif ($action == 'delete') {
        $id = (int)$_POST['id'];
        
        if ($id <= 0) {
            $_SESSION['error_message'] = "معرف غير صالح";
            header("Location: courses_management.php");
            exit;
        }
        
        // Soft delete
        $sql = "UPDATE courses SET deleted_at = NOW() WHERE id=?";
        $stmt = $mysqli1->prepare($sql);
        
        if (!$stmt) {
            $_SESSION['error_message'] = "خطأ في تحضير الاستعلام: " . $mysqli1->error;
            header("Location: courses_management.php");
            exit;
        }
        
        $stmt->bind_param('i', $id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "تم حذف المقرر بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء الحذف: " . $stmt->error;
        }
        $stmt->close();
        
        header("Location: courses_management.php");
        exit;
    }
}

// جلب بيانات الكليات
$colleges = [];
$colleges_query = "SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name";
$colleges_result = $mysqli1->query($colleges_query);
if ($colleges_result) {
    $colleges = $colleges_result->fetch_all(MYSQLI_ASSOC);
} else {
    // إذا كان جدول colleges لا يحتوي على حقل name، جرب حقول أخرى
    $colleges_query = "SELECT id, FacultyNameAC as name FROM colleges WHERE deleted_at IS NULL ORDER BY FacultyNameAC";
    $colleges_result = $mysqli1->query($colleges_query);
    if ($colleges_result) {
        $colleges = $colleges_result->fetch_all(MYSQLI_ASSOC);
    } else {
        $colleges = [];
    }
}

// جلب بيانات البرامج
$programs = [];
$programs_query = "SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name";
$programs_result = $mysqli1->query($programs_query);
if ($programs_result) {
    $programs = $programs_result->fetch_all(MYSQLI_ASSOC);
}

// جلب بيانات الأقسام
$sections = [];
$sections_query = "SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name";
$sections_result = $mysqli1->query($sections_query);
if ($sections_result) {
    $sections = $sections_result->fetch_all(MYSQLI_ASSOC);
}

// جلب بيانات التخصصات
$specializations = [];
$specializations_query = "SELECT specialization_id, specialization_name_ar, section_id, program_id FROM specializations WHERE deleted_at IS NULL";
$specializations_result = $mysqli1->query($specializations_query);
if ($specializations_result) {
    $specializations = $specializations_result->fetch_all(MYSQLI_ASSOC);
}

// جلب بيانات أنواع المقررات (افتراضي، يمكن إنشاء جدول منفصل)
$subject_types = [
    ['id' => 1, 'name' => 'نظري'],
    ['id' => 2, 'name' => 'عملي'],
    ['id' => 3, 'name' => 'نظري وعملي'],
    ['id' => 4, 'name' => 'تدريب ميداني'],
    ['id' => 5, 'name' => 'مشروع تخرج']
];

// جلب بيانات المقررات مع معلومات الكلية والقسم والتخصص والبرنامج
$courses = [];
$courses_query = "
    SELECT c.*, 
           COALESCE(col.name, col.FacultyNameAC) as college_name,
           s.name as section_name,
           spec.specialization_name_ar as specialization_name,
           p.name as program_name,
           CASE 
               WHEN c.subjecttype_id = 1 THEN 'نظري'
               WHEN c.subjecttype_id = 2 THEN 'عملي'
               WHEN c.subjecttype_id = 3 THEN 'نظري وعملي'
               WHEN c.subjecttype_id = 4 THEN 'تدريب ميداني'
               WHEN c.subjecttype_id = 5 THEN 'مشروع تخرج'
               ELSE '-'
           END as subject_type_name
    FROM courses c
    LEFT JOIN colleges col ON c.college_id = col.id
    LEFT JOIN sections s ON c.section_id = s.id
    LEFT JOIN specializations spec ON c.specialization_id = spec.specialization_id
    LEFT JOIN programs p ON c.program_id = p.id
    WHERE c.deleted_at IS NULL
    ORDER BY c.created_at DESC
";
$courses_result = $mysqli1->query($courses_query);
if ($courses_result) {
    $courses = $courses_result->fetch_all(MYSQLI_ASSOC);
}

// تقييد الكليات حسب صلاحيات اللجنة إذا لزم الأمر
if (!$canAll && $scopeCollege !== null) {
    $filtered_colleges = array_filter($colleges, function($college) use ($scopeCollege) {
        return $college['id'] == $scopeCollege;
    });
    $colleges = $filtered_colleges ?: [];
}

// تضمين الهيدر إذا كان موجوداً
if (file_exists('header.php')) {
    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>إدارة المقررات الدراسية - نظام القبول والتسجيل</title>
    
    <!-- Bootstrap 5 RTL -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap5.min.css">
    <!-- Select2 -->
    <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.rtl.min.css" rel="stylesheet" />
    <!-- Google Fonts: Cairo -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --bs-font-sans-serif: 'Cairo', system-ui, -apple-system, sans-serif;
            --primary-gradient: linear-gradient(135deg, #059669, #047857);
            --primary-color: #059669;
        }
        
        body, h1, h2, h3, h4, h5, h6, p, a, button, label, input, select, textarea, .form-control, .form-select, .btn {
            font-family: 'Cairo', sans-serif !important;
        }
        
        .page-header {
            background: var(--primary-gradient);
            color: white;
            padding: 30px 0;
            margin-bottom: 30px;
            border-radius: 0 0 30px 30px;
            box-shadow: 0 10px 30px rgba(5, 150, 105, 0.3);
        }
        
        .card-custom {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        
        .stats-card {
            background: var(--primary-gradient);
            color: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(5, 150, 105, 0.3);
            transition: transform 0.3s;
            height: 100%;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
        }
        
        .stats-card .icon {
            font-size: 3rem;
            opacity: 0.5;
        }
        
        .stats-card.blue {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
        }
        
        .stats-card.purple {
            background: linear-gradient(135deg, #8b5cf6, #6d28d9);
        }
        
        .badge-course {
            background: linear-gradient(135deg, #059669, #047857);
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-code {
            background-color: #e3f2fd;
            color: #0d47a1;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
            font-family: monospace;
            direction: ltr;
        }
        
        .badge-hours {
            background-color: #f3e5f5;
            color: #4a148c;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-credit {
            background-color: #fff3e0;
            color: #bf360c;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-type {
            background-color: #e8eaf6;
            color: #1a237e;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-active {
            background-color: #c8e6c9;
            color: #1b5e20;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-inactive {
            background-color: #ffcdd2;
            color: #b71c1c;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .btn-actions {
            white-space: nowrap;
        }
        
        .btn-actions .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            margin: 0 2px;
            border-radius: 8px;
        }
        
        .modal-content {
            border-radius: 20px;
            border: none;
        }
        
        .modal-header {
            background: var(--primary-gradient);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 20px;
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-header.bg-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706) !important;
        }
        
        .modal-header.bg-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626) !important;
        }
        
        .modal-header.bg-info {
            background: linear-gradient(135deg, #3b82f6, #2563eb) !important;
        }
        
        .form-section {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }
        
        .section-title {
            color: #2c3e50;
            font-weight: 700;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #059669;
        }
        
        .required::after {
            content: " *";
            color: #dc3545;
        }
        
        .btn-primary-custom {
            background: var(--primary-gradient);
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-weight: 600;
            color: white;
        }
        
        .btn-primary-custom:hover {
            background: linear-gradient(135deg, #047857, #065f46);
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #a0aec0;
        }
        
        .empty-state i {
            font-size: 5rem;
            margin-bottom: 20px;
        }
        
        /* تحسينات Select2 */
        .select2-container--bootstrap-5 .select2-selection {
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            min-height: 46px;
        }
        
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
            line-height: 42px;
            padding-right: 15px;
        }
        
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__arrow {
            height: 42px;
            left: 10px;
            right: auto;
        }
        
        .form-check-input:checked {
            background-color: #059669;
            border-color: #059669;
        }
    </style>
</head>
<body class="bg-light" dir="rtl">
    <!-- رأس الصفحة -->
    <div class="page-header">
        <div class="container">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h2 class="mb-2"><i class="fas fa-book-open me-2"></i> إدارة المقررات الدراسية</h2>
                    <p class="mb-0 opacity-75">عرض وإدارة المقررات الدراسية لكافة البرامج والتخصصات</p>
                </div>
                <a href="javascript:history.back()" class="btn btn-light rounded-pill px-4">
                    <i class="fas fa-arrow-right me-2"></i> العودة
                </a>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- رسائل التنبيه -->
        <?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']) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></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']) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- بطاقات الإحصائيات -->
        <div class="row mb-4 g-4">
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-2">إجمالي المقررات</h6>
                            <h2 class="mb-0"><?= count($courses) ?></h2>
                            <small class="opacity-75">مقرر دراسي</small>
                        </div>
                        <i class="fas fa-book icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card blue">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-2">الكليات</h6>
                            <h2 class="mb-0"><?= count($colleges) ?></h2>
                            <small class="opacity-75">كلية</small>
                        </div>
                        <i class="fas fa-university icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card purple">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-2">البرامج</h6>
                            <h2 class="mb-0"><?= count($programs) ?></h2>
                            <small class="opacity-75">برنامج</small>
                        </div>
                        <i class="fas fa-graduation-cap icon"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- بطاقة الجدول الرئيسي -->
        <div class="card card-custom p-3">
            <div class="card-header bg-transparent border-0 d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-list-ul ms-2 text-success"></i>
                    قائمة المقررات الدراسية
                </h5>
                <button type="button" class="btn btn-primary-custom rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#addCourseModal">
                    <i class="fas fa-plus-circle ms-2"></i> إضافة مقرر جديد
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($courses)): ?>
                    <div class="empty-state">
                        <i class="fas fa-book-open text-muted"></i>
                        <h5>لا يوجد مقررات دراسية مضافة</h5>
                        <p class="text-muted">قم بإضافة أول مقرر من خلال الضغط على زر الإضافة</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table id="coursesTable" class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>#</th>
                                    <th>رمز المقرر</th>
                                    <th>اسم المقرر (عربي)</th>
                                    <th>اسم المقرر (إنجليزي)</th>
                                    <th>البرنامج</th>
                                    <th>الكلية</th>
                                    <th>القسم</th>
                                    <th>التخصص</th>
                                    <th>الساعات</th>
                                    <th>الساعات المعتمدة</th>
                                    <th>النوع</th>
                                    <th>الحالة</th>
                                    <th>الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($courses as $index => $course): ?>
                                <tr>
                                    <td class="fw-bold"><?= $index + 1 ?></td>
                                    <td>
                                        <span class="badge-code">
                                            <?= htmlspecialchars($course['subjectcode'] ?? '') ?>
                                        </span>
                                    </td>
                                    <td><?= htmlspecialchars($course['subjectnamea'] ?? '') ?></td>
                                    <td><?= htmlspecialchars($course['subjectnamee'] ?? '') ?></td>
                                    <td>
                                        <span class="badge" style="background: linear-gradient(135deg, #8b5cf6, #6d28d9); color: white;">
                                            <?= htmlspecialchars($course['program_name'] ?? '-') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge" style="background: linear-gradient(135deg, #3b82f6, #2563eb); color: white;">
                                            <?= htmlspecialchars($course['college_name'] ?? '-') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge" style="background: linear-gradient(135deg, #10b981, #047857); color: white;">
                                            <?= htmlspecialchars($course['section_name'] ?? '-') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge" style="background: linear-gradient(135deg, #f59e0b, #b45309); color: white;">
                                            <?= htmlspecialchars($course['specialization_name'] ?? '-') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge-hours">
                                            <i class="fas fa-clock ms-1"></i>
                                            <?= (int)($course['subjecthours'] ?? 0) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge-credit">
                                            <i class="fas fa-star ms-1"></i>
                                            <?= number_format($course['credit_hours'] ?? 3, 2) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge-type">
                                            <?= htmlspecialchars($course['subject_type_name'] ?? '-') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($course['is_active'] ?? 1): ?>
                                            <span class="badge-active">
                                                <i class="fas fa-check-circle ms-1"></i> نشط
                                            </span>
                                        <?php else: ?>
                                            <span class="badge-inactive">
                                                <i class="fas fa-times-circle ms-1"></i> غير نشط
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="btn-actions">
                                        <button class="btn btn-sm btn-info text-white" onclick="viewCourse(<?= htmlspecialchars(json_encode($course)) ?>)" 
                                                data-bs-toggle="tooltip" title="عرض التفاصيل">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button class="btn btn-sm btn-warning" onclick="editCourse(<?= htmlspecialchars(json_encode($course)) ?>)" 
                                                data-bs-toggle="tooltip" title="تعديل">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger" onclick="deleteCourse(<?= $course['id'] ?? 0 ?>, '<?= htmlspecialchars($course['subjectnamea'] ?? '') ?>')"
                                                data-bs-toggle="tooltip" title="حذف">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Modal إضافة مقرر جديد -->
    <div class="modal fade" id="addCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-plus-circle ms-2"></i> إضافة مقرر دراسي جديد
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="courses_management.php" method="POST" id="addCourseForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add">
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-tag ms-2"></i> المعلومات الأساسية
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-barcode ms-2"></i> رمز المقرر
                                    </label>
                                    <input type="text" name="subjectcode" class="form-control" required 
                                           placeholder="مثال: MATH101" dir="ltr">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-clock ms-2"></i> عدد الساعات
                                    </label>
                                    <input type="number" name="subjecthours" class="form-control" required 
                                           min="1" max="12" value="3">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-star ms-2"></i> الساعات المعتمدة
                                    </label>
                                    <input type="number" name="credit_hours" class="form-control" 
                                           min="0" max="12" step="0.5" value="3.00">
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-language ms-2"></i> اسم المقرر (عربي)
                                    </label>
                                    <input type="text" name="subjectnamea" class="form-control" required 
                                           placeholder="أدخل اسم المقرر بالعربية">
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-language ms-2"></i> اسم المقرر (إنجليزي)
                                    </label>
                                    <input type="text" name="subjectnamee" class="form-control" required 
                                           placeholder="Enter course name in English" dir="ltr">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-sitemap ms-2"></i> التصنيف الأكاديمي
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-university ms-2"></i> الكلية
                                    </label>
                                    <select class="form-select" name="college_id" required 
                                            onchange="loadAddPrograms(this.value); loadAddSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <option value="<?= $college['id'] ?? '' ?>">
                                                <?= htmlspecialchars($college['name'] ?? '') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-graduation-cap ms-2"></i> البرنامج
                                    </label>
                                    <select class="form-select" name="program_id" id="add_program_id" required 
                                            onchange="loadAddSpecializations()">
                                        <option value="">اختر البرنامج</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-building ms-2"></i> القسم
                                    </label>
                                    <select class="form-select" name="section_id" id="add_section_id" required 
                                            onchange="loadAddSpecializations()">
                                        <option value="">اختر القسم</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-tag ms-2"></i> التخصص
                                    </label>
                                    <select class="form-select" name="specialization_id" id="add_specialization_id" required>
                                        <option value="">اختر التخصص</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-list-alt ms-2"></i> نوع المقرر
                                    </label>
                                    <select class="form-select" name="subjecttype_id">
                                        <option value="">اختر النوع</option>
                                        <?php foreach ($subject_types as $type): ?>
                                            <option value="<?= $type['id'] ?>"><?= $type['name'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="is_active" id="add_is_active" checked>
                                        <label class="form-check-label" for="add_is_active">
                                            <i class="fas fa-check-circle text-success ms-1"></i>
                                            المقرر نشط
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times ms-2"></i> إلغاء
                        </button>
                        <button type="submit" class="btn btn-primary-custom">
                            <i class="fas fa-save ms-2"></i> حفظ المقرر
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal تعديل مقرر -->
    <div class="modal fade" id="editCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title">
                        <i class="fas fa-edit ms-2"></i> تعديل بيانات المقرر
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="courses_management.php" method="POST" id="editCourseForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="edit_id">
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-tag ms-2"></i> المعلومات الأساسية
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-barcode ms-2"></i> رمز المقرر
                                    </label>
                                    <input type="text" name="subjectcode" id="edit_subjectcode" class="form-control" required 
                                           dir="ltr">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-clock ms-2"></i> عدد الساعات
                                    </label>
                                    <input type="number" name="subjecthours" id="edit_subjecthours" class="form-control" required 
                                           min="1" max="12">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-star ms-2"></i> الساعات المعتمدة
                                    </label>
                                    <input type="number" name="credit_hours" id="edit_credit_hours" class="form-control" 
                                           min="0" max="12" step="0.5">
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-language ms-2"></i> اسم المقرر (عربي)
                                    </label>
                                    <input type="text" name="subjectnamea" id="edit_subjectnamea" class="form-control" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-language ms-2"></i> اسم المقرر (إنجليزي)
                                    </label>
                                    <input type="text" name="subjectnamee" id="edit_subjectnamee" class="form-control" required 
                                           dir="ltr">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-sitemap ms-2"></i> التصنيف الأكاديمي
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-university ms-2"></i> الكلية
                                    </label>
                                    <select class="form-select" name="college_id" id="edit_college_id" required 
                                            onchange="loadEditPrograms(this.value); loadEditSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <option value="<?= $college['id'] ?? '' ?>">
                                                <?= htmlspecialchars($college['name'] ?? '') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-graduation-cap ms-2"></i> البرنامج
                                    </label>
                                    <select class="form-select" name="program_id" id="edit_program_id" required 
                                            onchange="loadEditSpecializations()">
                                        <option value="">اختر البرنامج</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-building ms-2"></i> القسم
                                    </label>
                                    <select class="form-select" name="section_id" id="edit_section_id" required 
                                            onchange="loadEditSpecializations()">
                                        <option value="">اختر القسم</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-tag ms-2"></i> التخصص
                                    </label>
                                    <select class="form-select" name="specialization_id" id="edit_specialization_id" required>
                                        <option value="">اختر التخصص</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-list-alt ms-2"></i> نوع المقرر
                                    </label>
                                    <select class="form-select" name="subjecttype_id" id="edit_subjecttype_id">
                                        <option value="">اختر النوع</option>
                                        <?php foreach ($subject_types as $type): ?>
                                            <option value="<?= $type['id'] ?>"><?= $type['name'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active" checked>
                                        <label class="form-check-label" for="edit_is_active">
                                            <i class="fas fa-check-circle text-success ms-1"></i>
                                            المقرر نشط
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times ms-2"></i> إلغاء
                        </button>
                        <button type="submit" class="btn btn-warning">
                            <i class="fas fa-save ms-2"></i> تحديث البيانات
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal عرض التفاصيل -->
    <div class="modal fade" id="viewCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info">
                    <h5 class="modal-title">
                        <i class="fas fa-info-circle ms-2"></i> تفاصيل المقرر الدراسي
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <table class="table table-bordered">
                        <tr>
                            <th width="35%">المعرف:</th>
                            <td id="view_id"></td>
                        </tr>
                        <tr>
                            <th>رمز المقرر:</th>
                            <td id="view_subjectcode"></td>
                        </tr>
                        <tr>
                            <th>اسم المقرر (عربي):</th>
                            <td id="view_subjectnamea"></td>
                        </tr>
                        <tr>
                            <th>اسم المقرر (إنجليزي):</th>
                            <td id="view_subjectnamee"></td>
                        </tr>
                        <tr>
                            <th>البرنامج:</th>
                            <td id="view_program"></td>
                        </tr>
                        <tr>
                            <th>الكلية:</th>
                            <td id="view_college"></td>
                        </tr>
                        <tr>
                            <th>القسم:</th>
                            <td id="view_section"></td>
                        </tr>
                        <tr>
                            <th>التخصص:</th>
                            <td id="view_specialization"></td>
                        </tr>
                        <tr>
                            <th>عدد الساعات:</th>
                            <td id="view_subjecthours"></td>
                        </tr>
                        <tr>
                            <th>الساعات المعتمدة:</th>
                            <td id="view_credit_hours"></td>
                        </tr>
                        <tr>
                            <th>نوع المقرر:</th>
                            <td id="view_type"></td>
                        </tr>
                        <tr>
                            <th>الحالة:</th>
                            <td id="view_status"></td>
                        </tr>
                        <tr>
                            <th>تاريخ الإضافة:</th>
                            <td id="view_created"></td>
                        </tr>
                        <tr>
                            <th>آخر تحديث:</th>
                            <td id="view_updated"></td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times ms-2"></i> إغلاق
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal تأكيد الحذف -->
    <div class="modal fade" id="deleteCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-triangle ms-2"></i> تأكيد الحذف
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>هل أنت متأكد من حذف المقرر: <strong id="delete_item_name"></strong>؟</p>
                    <p class="text-danger mb-0">
                        <i class="fas fa-info-circle ms-2"></i>
                        هذا الإجراء لا يمكن التراجع عنه.
                    </p>
                </div>
                <div class="modal-footer">
                    <form action="courses_management.php" method="POST" id="deleteForm">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" id="delete_id">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times ms-2"></i> إلغاء
                        </button>
                        <button type="submit" class="btn btn-danger">
                            <i class="fas fa-trash ms-2"></i> تأكيد الحذف
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <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.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        // تخزين البيانات
        const allSections = <?= json_encode($sections) ?>;
        const allSpecializations = <?= json_encode($specializations) ?>;
        
        // تهيئة DataTable
        $(document).ready(function() {
            $('#coursesTable').DataTable({
                language: {
                    url: '//cdn.datatables.net/plug-ins/1.13.4/i18n/ar.json'
                },
                order: [[0, 'desc']],
                responsive: true,
                pageLength: 25,
                columnDefs: [
                    { orderable: false, targets: 12 } // منع ترتيب عمود الإجراءات
                ]
            });
            
            // تهيئة التلميحات
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            
            // تهيئة Select2
            $('.select2').select2({
                theme: 'bootstrap-5',
                dir: 'rtl',
                placeholder: 'اختر...',
                allowClear: true
            });
        });

        // دوال تحميل البيانات للإضافة
        function loadAddPrograms(collegeId) {
            if (!collegeId) {
                $('#add_program_id').html('<option value="">اختر البرنامج</option>');
                return;
            }
            
            $.ajax({
                url: 'ajax/get_programs.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(programs) {
                    let options = '<option value="">اختر البرنامج</option>';
                    programs.forEach(program => {
                        options += `<option value="${program.id}">${program.name}</option>`;
                    });
                    $('#add_program_id').html(options);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading programs:', error);
                    $('#add_program_id').html('<option value="">خطأ في تحميل البرامج</option>');
                }
            });
        }

        function loadAddSections(collegeId) {
            if (!collegeId) {
                $('#add_section_id').html('<option value="">اختر القسم</option>');
                return;
            }
            
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(sections) {
                    let options = '<option value="">اختر القسم</option>';
                    sections.forEach(section => {
                        options += `<option value="${section.id}">${section.name}</option>`;
                    });
                    $('#add_section_id').html(options);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sections:', error);
                    $('#add_section_id').html('<option value="">خطأ في تحميل الأقسام</option>');
                }
            });
        }

        function loadAddSpecializations() {
            const programId = $('#add_program_id').val();
            const sectionId = $('#add_section_id').val();
            
            if (!programId || !sectionId) {
                $('#add_specialization_id').html('<option value="">اختر التخصص</option>');
                return;
            }
            
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { 
                    section_id: sectionId,
                    program_id: programId 
                },
                dataType: 'json',
                success: function(specializations) {
                    let options = '<option value="">اختر التخصص</option>';
                    specializations.forEach(spec => {
                        options += `<option value="${spec.specialization_id}">${spec.specialization_name_ar}</option>`;
                    });
                    $('#add_specialization_id').html(options);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading specializations:', error);
                    $('#add_specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>');
                }
            });
        }

        // دوال تحميل البيانات للتعديل
        function loadEditPrograms(collegeId) {
            if (!collegeId) {
                $('#edit_program_id').html('<option value="">اختر البرنامج</option>');
                return;
            }
            
            $.ajax({
                url: 'ajax/get_programs.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(programs) {
                    let options = '<option value="">اختر البرنامج</option>';
                    programs.forEach(program => {
                        options += `<option value="${program.id}">${program.name}</option>`;
                    });
                    $('#edit_program_id').html(options);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading programs:', error);
                    $('#edit_program_id').html('<option value="">خطأ في تحميل البرامج</option>');
                }
            });
        }

        function loadEditSections(collegeId) {
            if (!collegeId) {
                $('#edit_section_id').html('<option value="">اختر القسم</option>');
                return;
            }
            
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                success: function(sections) {
                    let options = '<option value="">اختر القسم</option>';
                    sections.forEach(section => {
                        options += `<option value="${section.id}">${section.name}</option>`;
                    });
                    $('#edit_section_id').html(options);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sections:', error);
                    $('#edit_section_id').html('<option value="">خطأ في تحميل الأقسام</option>');
                }
            });
        }

        function loadEditSpecializations() {
            const programId = $('#edit_program_id').val();
            const sectionId = $('#edit_section_id').val();
            
            if (!programId || !sectionId) {
                $('#edit_specialization_id').html('<option value="">اختر التخصص</option>');
                return;
            }
            
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { 
                    section_id: sectionId,
                    program_id: programId 
                },
                dataType: 'json',
                success: function(specializations) {
                    let options = '<option value="">اختر التخصص</option>';
                    specializations.forEach(spec => {
                        options += `<option value="${spec.specialization_id}">${spec.specialization_name_ar}</option>`;
                    });
                    $('#edit_specialization_id').html(options);
                },
                error: function(xhr, status, error) {
                    console.error('Error loading specializations:', error);
                    $('#edit_specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>');
                }
            });
        }

        // دالة التعديل
        function editCourse(course) {
            $('#edit_id').val(course.id);
            $('#edit_subjectcode').val(course.subjectcode);
            $('#edit_subjecthours').val(course.subjecthours);
            $('#edit_credit_hours').val(course.credit_hours);
            $('#edit_subjectnamea').val(course.subjectnamea);
            $('#edit_subjectnamee').val(course.subjectnamee);
            $('#edit_college_id').val(course.college_id);
            $('#edit_subjecttype_id').val(course.subjecttype_id);
            
            if (course.is_active == 1) {
                $('#edit_is_active').prop('checked', true);
            } else {
                $('#edit_is_active').prop('checked', false);
            }
            
            // تحميل البرامج
            loadEditPrograms(course.college_id);
            
            // تحميل الأقسام
            loadEditSections(course.college_id);
            
            // بعد تحميل البرامج والأقسام، تحميل التخصصات وتحديد القيم
            setTimeout(() => {
                $('#edit_program_id').val(course.program_id);
                $('#edit_section_id').val(course.section_id);
                
                loadEditSpecializations();
                
                setTimeout(() => {
                    $('#edit_specialization_id').val(course.specialization_id);
                }, 500);
            }, 500);
            
            new bootstrap.Modal(document.getElementById('editCourseModal')).show();
        }

        // دالة عرض التفاصيل
        function viewCourse(course) {
            $('#view_id').text(course.id || '-');
            $('#view_subjectcode').text(course.subjectcode || '-');
            $('#view_subjectnamea').text(course.subjectnamea || '-');
            $('#view_subjectnamee').text(course.subjectnamee || '-');
            $('#view_program').text(course.program_name || '-');
            $('#view_college').text(course.college_name || '-');
            $('#view_section').text(course.section_name || '-');
            $('#view_specialization').text(course.specialization_name || '-');
            $('#view_subjecthours').text(course.subjecthours || '-');
            $('#view_credit_hours').text(course.credit_hours || '-');
            $('#view_type').text(course.subject_type_name || '-');
            
            let status = course.is_active ? 'نشط' : 'غير نشط';
            let statusClass = course.is_active ? 'badge-active' : 'badge-inactive';
            $('#view_status').html(`<span class="${statusClass}">${status}</span>`);
            
            const createdDate = course.created_at ? new Date(course.created_at).toLocaleString('ar-EG') : '-';
            const updatedDate = course.updated_at ? new Date(course.updated_at).toLocaleString('ar-EG') : '-';
            
            $('#view_created').text(createdDate);
            $('#view_updated').text(updatedDate);
            
            new bootstrap.Modal(document.getElementById('viewCourseModal')).show();
        }

        // دالة الحذف
        function deleteCourse(id, name) {
            $('#delete_id').val(id);
            $('#delete_item_name').text(name);
            new bootstrap.Modal(document.getElementById('deleteCourseModal')).show();
        }

        // التحقق من صحة النموذج قبل الإرسال
        document.getElementById('addCourseForm')?.addEventListener('submit', function(e) {
            const requiredFields = this.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                alert('❌ الرجاء ملء جميع الحقول المطلوبة');
            }
        });

        document.getElementById('editCourseForm')?.addEventListener('submit', function(e) {
            const requiredFields = this.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                alert('❌ الرجاء ملء جميع الحقول المطلوبة');
            }
        });
    </script>
</body>
</html>
