<?php
// courses_management.php - نسخة تسمح بتكرار رمز المقرر في كليات وبرامج مختلفة
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

require 'db.php';
require 'helpers.php';
require_committee();

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

// =============================================
// تحسينات أمنية
// =============================================

// Rate limiting
if (!isset($_SESSION['request_count'])) {
    $_SESSION['request_count'] = 0;
    $_SESSION['request_time'] = time();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['request_count']++;
    
    if ($_SESSION['request_count'] > 10 && (time() - $_SESSION['request_time']) < 60) {
        $_SESSION['error_message'] = "طلبات كثيرة جداً، الرجاء الانتظار دقيقة";
        header("Location: courses_management.php");
        exit;
    }
    
    if (time() - $_SESSION['request_time'] > 60) {
        $_SESSION['request_count'] = 1;
        $_SESSION['request_time'] = time();
    }
}

// CSRF Token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// دوال التحقق
function validateInt($value, $default = 0) {
    if ($value === null || $value === '') return $default;
    return filter_var($value, FILTER_VALIDATE_INT) !== false ? (int)$value : $default;
}

function validateString($value, $default = '') {
    if ($value === null) return $default;
    $value = trim(strip_tags($value));
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

// دالة تسجيل الأحداث
function logAction($action, $details = '') {
    global $mysqli1, $committeeId;
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $timestamp = date('Y-m-d H:i:s');
    
    // تسجيل في ملف
    $log_entry = "[$timestamp] Committee: $committeeId | Action: $action | IP: $ip | UA: $user_agent | Details: $details" . PHP_EOL;
    $log_file = __DIR__ . '/logs/courses_management.log';
    $log_dir = dirname($log_file);
    
    if (!is_dir($log_dir)) {
        mkdir($log_dir, 0755, true);
    }
    
    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

// =============================================
// معالجة POST (إضافة، تعديل، حذف، إيقاف/تفعيل)
// =============================================

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // التحقق من CSRF
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        logAction('CSRF_ATTEMPT', 'محاولة اختراق CSRF');
        $_SESSION['error_message'] = 'خطأ في التحقق من الأمان';
        header("Location: courses_management.php");
        exit;
    }
    
    $action = $_POST['action'] ?? '';
    
    // =========================================
    // إضافة مقرر جديد - بدون التحقق من التكرار
    // =========================================
    if ($action === 'add') {
        // التحقق من الصلاحية
        $college_id = validateInt($_POST['college_id'] ?? 0);
        if (!$canAll && $scopeCollege !== null && $college_id != $scopeCollege) {
            logAction('UNAUTHORIZED_ADD', "محاولة إضافة مقرر لكلية غير مصرح بها: $college_id");
            $_SESSION['error_message'] = "ليس لديك صلاحية للإضافة لهذه الكلية";
            header("Location: courses_management.php");
            exit;
        }
        
        // التحقق من البيانات
        $subjectcode = $mysqli1->real_escape_string(trim($_POST['subjectcode'] ?? ''));
        $subjectnamea = $mysqli1->real_escape_string(trim($_POST['subjectnamea'] ?? ''));
        $subjectnamee = $mysqli1->real_escape_string(trim($_POST['subjectnamee'] ?? ''));
        $program_id = validateInt($_POST['program_id'] ?? 0);
        $section_id = isset($_POST['section_id']) && $_POST['section_id'] !== '' ? validateInt($_POST['section_id']) : 0;
        $specialization_id = isset($_POST['specialization_id']) && $_POST['specialization_id'] !== '' ? validateInt($_POST['specialization_id']) : 0;
        
        // نأخذ الساعات كنص صريح ونتأكد من عدم تحويلها
        $subjecthours = $mysqli1->real_escape_string(trim($_POST['subjecthours'] ?? '3'));
        
        $credit_hours = (float)($_POST['credit_hours'] ?? 3.00);
        $subjecttype_id = !empty($_POST['subjecttype_id']) ? validateInt($_POST['subjecttype_id']) : 'NULL';
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // تسجيل القيمة للتشخيص
        error_log("ADD - Hours value after escape: " . $subjecthours);
        
        // التحقق من الحقول المطلوبة
        $errors = [];
        if (empty($subjectcode)) $errors[] = 'رمز المقرر مطلوب';
        if (empty($subjectnamea)) $errors[] = 'اسم المقرر بالعربية مطلوب';
        if (empty($subjectnamee)) $errors[] = 'اسم المقرر بالإنجليزية مطلوب';
        if ($program_id <= 0) $errors[] = 'البرنامج مطلوب';
        if ($college_id <= 0) $errors[] = 'الكلية مطلوبة';
        if (empty($subjecthours)) $errors[] = 'عدد الساعات مطلوب';
        
        if (!empty($errors)) {
            logAction('ADD_VALIDATION_ERROR', 'أخطاء في التحقق: ' . implode(', ', $errors));
            $_SESSION['error_message'] = implode('<br>', $errors);
            header("Location: courses_management.php");
            exit;
        }
        
        // ملاحظة: تم إزالة التحقق من تكرار رمز المقرر بالكامل
        // يمكن إضافة نفس رمز المقرر لأي كلية أو برنامج
        
        // بناء جملة INSERT مع مراعاة الحقول الاختيارية
        $sql = "INSERT INTO subjects (subjectcode, program_id, college_id";
        
        // إضافة الحقول الاختيارية فقط إذا تم توفيرها
        if ($section_id > 0) $sql .= ", section_id";
        if ($specialization_id > 0) $sql .= ", specialization_id";
        
        $sql .= ", subjecthours, subjectnamea, subjectnamee, credit_hours, subjecttype_id, is_active) VALUES ('$subjectcode', $program_id, $college_id";
        
        if ($section_id > 0) $sql .= ", $section_id";
        if ($specialization_id > 0) $sql .= ", $specialization_id";
        
        $sql .= ", '$subjecthours', '$subjectnamea', '$subjectnamee', $credit_hours, $subjecttype_id, $is_active)";
        
        error_log("SQL Query: " . $sql);
        
        if ($mysqli1->query($sql)) {
            $new_id = $mysqli1->insert_id;
            logAction('ADD_COURSE', "تم إضافة مقرر جديد - ID: $new_id, Code: $subjectcode, Hours: $subjecthours");
            $_SESSION['success_message'] = "تم إضافة المقرر الدراسي بنجاح";
        } else {
            logAction('ADD_ERROR', "خطأ في إضافة المقرر: " . $mysqli1->error);
            $_SESSION['error_message'] = "حدث خطأ أثناء الإضافة: " . $mysqli1->error;
        }
        
        header("Location: courses_management.php");
        exit;
    }
    
    // =========================================
    // تعديل مقرر - بدون التحقق من التكرار
    // =========================================
    elseif ($action === 'edit') {
        $id = validateInt($_POST['id'] ?? 0);
        if ($id <= 0) {
            logAction('INVALID_EDIT_ID', 'محاولة تعديل بمعرف غير صالح');
            $_SESSION['error_message'] = 'معرف غير صالح';
            header("Location: courses_management.php");
            exit;
        }
        
        // التحقق من وجود المقرر وصلاحية الوصول
        $check_sql = "SELECT id, college_id, subjectcode FROM subjects  
                      WHERE id = $id AND deleted_at IS NULL";
        $check_result = $mysqli1->query($check_sql);
        $course = $check_result->fetch_assoc();
        
        if (!$course) {
            logAction('EDIT_NOT_FOUND', "محاولة تعديل مقرر غير موجود ID: $id");
            $_SESSION['error_message'] = "المقرر غير موجود";
            header("Location: courses_management.php");
            exit;
        }
        
        if (!$canAll && $scopeCollege !== null && $course['college_id'] != $scopeCollege) {
            logAction('UNAUTHORIZED_EDIT', "محاولة تعديل مقرر خارج الصلاحية ID: $id");
            $_SESSION['error_message'] = "ليس لديك صلاحية لتعديل هذا المقرر";
            header("Location: courses_management.php");
            exit;
        }
        
        // التحقق من البيانات
        $subjectcode = $mysqli1->real_escape_string(trim($_POST['subjectcode'] ?? ''));
        $subjectnamea = $mysqli1->real_escape_string(trim($_POST['subjectnamea'] ?? ''));
        $subjectnamee = $mysqli1->real_escape_string(trim($_POST['subjectnamee'] ?? ''));
        $program_id = validateInt($_POST['program_id'] ?? 0);
        $college_id = validateInt($_POST['college_id'] ?? 0);
        $section_id = isset($_POST['section_id']) && $_POST['section_id'] !== '' ? validateInt($_POST['section_id']) : 0;
        $specialization_id = isset($_POST['specialization_id']) && $_POST['specialization_id'] !== '' ? validateInt($_POST['specialization_id']) : 0;
        
        // نأخذ الساعات كنص صريح
        $subjecthours = $mysqli1->real_escape_string(trim($_POST['subjecthours'] ?? '3'));
        
        $credit_hours = (float)($_POST['credit_hours'] ?? 3.00);
        $subjecttype_id = !empty($_POST['subjecttype_id']) ? validateInt($_POST['subjecttype_id']) : 'NULL';
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // تسجيل القيمة للتشخيص
        error_log("EDIT - Hours value after escape: " . $subjecthours);
        
        // التحقق من الحقول المطلوبة
        $errors = [];
        if (empty($subjectcode)) $errors[] = 'رمز المقرر مطلوب';
        if (empty($subjectnamea)) $errors[] = 'اسم المقرر بالعربية مطلوب';
        if (empty($subjectnamee)) $errors[] = 'اسم المقرر بالإنجليزية مطلوب';
        if ($program_id <= 0) $errors[] = 'البرنامج مطلوب';
        if ($college_id <= 0) $errors[] = 'الكلية مطلوبة';
        if (empty($subjecthours)) $errors[] = 'عدد الساعات مطلوب';
        
        if (!empty($errors)) {
            logAction('EDIT_VALIDATION_ERROR', 'أخطاء في التحقق: ' . implode(', ', $errors));
            $_SESSION['error_message'] = implode('<br>', $errors);
            header("Location: courses_management.php");
            exit;
        }
        
        // ملاحظة: تم إزالة التحقق من تكرار رمز المقرر بالكامل
        // يمكن تعديل رمز المقرر لأي قيمة حتى لو كانت موجودة في مقرر آخر
        
        // بناء جملة UPDATE مع مراعاة الحقول الاختيارية
        $sql = "UPDATE subjects SET 
                subjectcode = '$subjectcode', 
                program_id = $program_id, 
                college_id = $college_id";
        
        // إضافة الحقول الاختيارية فقط إذا تم توفيرها أو إلغاؤها
        if ($section_id > 0) {
            $sql .= ", section_id = $section_id";
        } else {
            $sql .= ", section_id = NULL";
        }
        
        if ($specialization_id > 0) {
            $sql .= ", specialization_id = $specialization_id";
        } else {
            $sql .= ", specialization_id = NULL";
        }
        
        $sql .= ", subjecthours = '$subjecthours', 
                subjectnamea = '$subjectnamea', 
                subjectnamee = '$subjectnamee', 
                credit_hours = $credit_hours, 
                subjecttype_id = $subjecttype_id, 
                is_active = $is_active 
                WHERE id = $id";
        
        error_log("UPDATE SQL Query: " . $sql);
        
        if ($mysqli1->query($sql)) {
            logAction('EDIT_COURSE', "تم تعديل مقرر - ID: $id, Code: $subjectcode, Hours: $subjecthours");
            $_SESSION['success_message'] = "تم تحديث بيانات المقرر بنجاح";
        } else {
            logAction('EDIT_ERROR', "خطأ في تعديل المقرر ID: $id - " . $mysqli1->error);
            $_SESSION['error_message'] = "حدث خطأ أثناء التحديث: " . $mysqli1->error;
        }
        
        header("Location: courses_management.php");
        exit;
    }
    
    // =========================================
    // حذف مقرر (Soft Delete)
    // =========================================
    elseif ($action === 'delete') {
        $id = validateInt($_POST['id'] ?? 0);
        if ($id <= 0) {
            logAction('INVALID_DELETE_ID', 'محاولة حذف بمعرف غير صالح');
            $_SESSION['error_message'] = 'معرف غير صالح';
            header("Location: courses_management.php");
            exit;
        }
        
        // التحقق من وجود المقرر وصلاحية الوصول
        $checkStmt = $mysqli1->prepare("
            SELECT id, college_id, subjectcode, subjectnamea FROM subjects 
            WHERE id = ? AND deleted_at IS NULL
        ");
        $checkStmt->bind_param('i', $id);
        $checkStmt->execute();
        $course = $checkStmt->get_result()->fetch_assoc();
        $checkStmt->close();
        
        if (!$course) {
            logAction('DELETE_NOT_FOUND', "محاولة حذف مقرر غير موجود ID: $id");
            $_SESSION['error_message'] = "المقرر غير موجود";
            header("Location: courses_management.php");
            exit;
        }
        
        if (!$canAll && $scopeCollege !== null && $course['college_id'] != $scopeCollege) {
            logAction('UNAUTHORIZED_DELETE', "محاولة حذف مقرر خارج الصلاحية ID: $id");
            $_SESSION['error_message'] = "ليس لديك صلاحية لحذف هذا المقرر";
            header("Location: courses_management.php");
            exit;
        }
        
        // Soft delete
        $deleteStmt = $mysqli1->prepare("DELETE FROM subjects WHERE id = ?");
        
        if (!$deleteStmt) {
            logAction('DB_ERROR', 'خطأ في تحضير استعلام الحذف: ' . $mysqli1->error);
            $_SESSION['error_message'] = "خطأ في قاعدة البيانات: " . $mysqli1->error;
            header("Location: courses_management.php");
            exit;
        }
        
        $deleteStmt->bind_param('i', $id);
        
        if ($deleteStmt->execute()) {
            logAction('DELETE_COURSE', "تم حذف مقرر - ID: $id, Code: {$course['subjectcode']}");
            $_SESSION['success_message'] = "تم حذف المقرر بنجاح";
        } else {
            logAction('DELETE_ERROR', "خطأ في حذف المقرر ID: $id - " . $deleteStmt->error);
            $_SESSION['error_message'] = "حدث خطأ أثناء الحذف: " . $deleteStmt->error;
        }
        $deleteStmt->close();
        
        header("Location: courses_management.php");
        exit;
    }
    
    // =========================================
    // إيقاف/تفعيل مقرر
    // =========================================
    elseif ($action === 'toggle_status') {
        $id = validateInt($_POST['id'] ?? 0);
        if ($id <= 0) {
            logAction('INVALID_TOGGLE_ID', 'محاولة تغيير حالة بمعرف غير صالح');
            $_SESSION['error_message'] = 'معرف غير صالح';
            header("Location: courses_management.php");
            exit;
        }
        
        // التحقق من وجود المقرر وصلاحية الوصول
        $checkStmt = $mysqli1->prepare("
            SELECT id, college_id, is_active, subjectcode, subjectnamea FROM subjects 
            WHERE id = ? AND deleted_at IS NULL
        ");
        $checkStmt->bind_param('i', $id);
        $checkStmt->execute();
        $course = $checkStmt->get_result()->fetch_assoc();
        $checkStmt->close();
        
        if (!$course) {
            logAction('TOGGLE_NOT_FOUND', "محاولة تغيير حالة مقرر غير موجود ID: $id");
            $_SESSION['error_message'] = "المقرر غير موجود";
            header("Location: courses_management.php");
            exit;
        }
        
        if (!$canAll && $scopeCollege !== null && $course['college_id'] != $scopeCollege) {
            logAction('UNAUTHORIZED_TOGGLE', "محاولة تغيير حالة مقرر خارج الصلاحية ID: $id");
            $_SESSION['error_message'] = "ليس لديك صلاحية لتغيير حالة هذا المقرر";
            header("Location: courses_management.php");
            exit;
        }
        
        $newStatus = $course['is_active'] ? 0 : 1;
        $toggleStmt = $mysqli1->prepare("UPDATE subjects SET is_active = ? WHERE id = ?");
        
        if (!$toggleStmt) {
            logAction('DB_ERROR', 'خطأ في تحضير استعلام تغيير الحالة: ' . $mysqli1->error);
            $_SESSION['error_message'] = "خطأ في قاعدة البيانات";
            header("Location: courses_management.php");
            exit;
        }
        
        $toggleStmt->bind_param('ii', $newStatus, $id);
        
        if ($toggleStmt->execute()) {
            $statusText = $newStatus ? 'تفعيل' : 'إيقاف';
            logAction('TOGGLE_STATUS', "$statusText مقرر - ID: $id, Code: {$course['subjectcode']}");
            $_SESSION['success_message'] = $newStatus ? "تم تفعيل المقرر بنجاح" : "تم إيقاف المقرر بنجاح";
        } else {
            logAction('TOGGLE_ERROR', "خطأ في تغيير حالة المقرر ID: $id - " . $toggleStmt->error);
            $_SESSION['error_message'] = "حدث خطأ أثناء تغيير الحالة";
        }
        $toggleStmt->close();
        
        header("Location: courses_management.php");
        exit;
    }
}

// =============================================
// بناء الاستعلام مع الفلاتر
// =============================================

$search = validateString($_GET['search'] ?? '');
$program_id = isset($_GET['program_id']) && $_GET['program_id'] !== '' ? validateInt($_GET['program_id']) : null;
$college_id = isset($_GET['college_id']) && $_GET['college_id'] !== '' ? validateInt($_GET['college_id']) : null;
$section_id = isset($_GET['section_id']) && $_GET['section_id'] !== '' ? validateInt($_GET['section_id']) : null;
$specialization_id = isset($_GET['specialization_id']) && $_GET['specialization_id'] !== '' ? validateInt($_GET['specialization_id']) : null;
$is_active = isset($_GET['is_active']) && $_GET['is_active'] !== '' ? validateInt($_GET['is_active']) : null;
$subjecttype_id = isset($_GET['subjecttype_id']) && $_GET['subjecttype_id'] !== '' ? validateInt($_GET['subjecttype_id']) : null;
$show_deleted = isset($_GET['show_deleted']) && $_GET['show_deleted'] == 1 && isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';

// استعلام COUNT
$countSql = "SELECT COUNT(*) as total FROM subjects c WHERE 1=1";
$types = "";
$params = [];

if (!$show_deleted) {
    $countSql .= " AND c.deleted_at IS NULL";
}

if (!$canAll && $scopeCollege !== null) {
    $countSql .= " AND c.college_id = ?";
    $types .= "i";
    $params[] = $scopeCollege;
}

if (!empty($search)) {
    $countSql .= " AND (c.subjectcode LIKE ? OR c.subjectnamea LIKE ? OR c.subjectnamee LIKE ?)";
    $types .= "sss";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($program_id !== null) {
    $countSql .= " AND c.program_id = ?";
    $types .= "i";
    $params[] = $program_id;
}

if ($college_id !== null && ($canAll || $college_id == $scopeCollege)) {
    $countSql .= " AND c.college_id = ?";
    $types .= "i";
    $params[] = $college_id;
}

if ($section_id !== null) {
    $countSql .= " AND c.section_id = ?";
    $types .= "i";
    $params[] = $section_id;
}

if ($specialization_id !== null) {
    $countSql .= " AND c.specialization_id = ?";
    $types .= "i";
    $params[] = $specialization_id;
}

if ($is_active !== null) {
    $countSql .= " AND c.is_active = ?";
    $types .= "i";
    $params[] = $is_active;
}

if ($subjecttype_id !== null) {
    $countSql .= " AND c.subjecttype_id = ?";
    $types .= "i";
    $params[] = $subjecttype_id;
}

// تنفيذ استعلام COUNT
$countStmt = $mysqli1->prepare($countSql);
if (!$countStmt) {
    logAction('DB_ERROR', 'خطأ في تحضير استعلام COUNT: ' . $mysqli1->error);
    $totalCount = 0;
} else {
    if (!empty($params)) {
        $countStmt->bind_param($types, ...$params);
    }
    $countStmt->execute();
    $countResult = $countStmt->get_result()->fetch_assoc();
    $totalCount = (int)($countResult['total'] ?? 0);
    $countStmt->close();
}

// ترقيم الصفحات
$perPage = 20;
$page = isset($_GET['page']) ? validateInt($_GET['page'], 1) : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $perPage;
$totalPages = $totalCount > 0 ? ceil($totalCount / $perPage) : 1;

// استعلام جلب البيانات
$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 subjects 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 1=1
";

$queryTypes = "";
$queryParams = [];

if (!$show_deleted) {
    $query .= " AND c.deleted_at IS NULL";
}

if (!$canAll && $scopeCollege !== null) {
    $query .= " AND c.college_id = ?";
    $queryTypes .= "i";
    $queryParams[] = $scopeCollege;
}

if (!empty($search)) {
    $query .= " AND (c.subjectcode LIKE ? OR c.subjectnamea LIKE ? OR c.subjectnamee LIKE ?)";
    $queryTypes .= "sss";
    $searchTerm = "%$search%";
    $queryParams[] = $searchTerm;
    $queryParams[] = $searchTerm;
    $queryParams[] = $searchTerm;
}

if ($program_id !== null) {
    $query .= " AND c.program_id = ?";
    $queryTypes .= "i";
    $queryParams[] = $program_id;
}

if ($college_id !== null && ($canAll || $college_id == $scopeCollege)) {
    $query .= " AND c.college_id = ?";
    $queryTypes .= "i";
    $queryParams[] = $college_id;
}

if ($section_id !== null) {
    $query .= " AND c.section_id = ?";
    $queryTypes .= "i";
    $queryParams[] = $section_id;
}

if ($specialization_id !== null) {
    $query .= " AND c.specialization_id = ?";
    $queryTypes .= "i";
    $queryParams[] = $specialization_id;
}

if ($is_active !== null) {
    $query .= " AND c.is_active = ?";
    $queryTypes .= "i";
    $queryParams[] = $is_active;
}

if ($subjecttype_id !== null) {
    $query .= " AND c.subjecttype_id = ?";
    $queryTypes .= "i";
    $queryParams[] = $subjecttype_id;
}

$query .= " ORDER BY c.created_at DESC LIMIT ? OFFSET ?";
$queryTypes .= "ii";
$queryParams[] = $perPage;
$queryParams[] = $offset;

// تنفيذ الاستعلام الرئيسي
$courses = [];
$stmt = $mysqli1->prepare($query);
if ($stmt) {
    if (!empty($queryParams)) {
        $stmt->bind_param($queryTypes, ...$queryParams);
    }
    $stmt->execute();
    $courses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    logAction('DB_ERROR', 'خطأ في تحضير الاستعلام الرئيسي: ' . $mysqli1->error);
}

// إحصائيات
$statsSql = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active,
                SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive,
                SUM(credit_hours) as total_hours
             FROM subjects 
             WHERE 1=1";

$statsTypes = "";
$statsParams = [];

if (!$show_deleted) {
    $statsSql .= " AND deleted_at IS NULL";
}

if (!$canAll && $scopeCollege !== null) {
    $statsSql .= " AND college_id = ?";
    $statsTypes .= "i";
    $statsParams[] = $scopeCollege;
}

$statsStmt = $mysqli1->prepare($statsSql);
if ($statsStmt) {
    if (!empty($statsParams)) {
        $statsStmt->bind_param($statsTypes, ...$statsParams);
    }
    $statsStmt->execute();
    $statsResult = $statsStmt->get_result()->fetch_assoc();
    $statsStmt->close();
} else {
    $statsResult = [];
}

$totalStats = (int)($statsResult['total'] ?? 0);
$activeStats = (int)($statsResult['active'] ?? 0);
$inactiveStats = (int)($statsResult['inactive'] ?? 0);
$totalHours = (float)($statsResult['total_hours'] ?? 0);

// جلب بيانات الفلاتر
$colleges = $mysqli1->query("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$programs = $mysqli1->query("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$sections = $mysqli1->query("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name")->fetch_all(MYSQLI_ASSOC);
$specializations = $mysqli1->query("SELECT specialization_id as id, specialization_name_ar as name, section_id, program_id FROM specializations WHERE deleted_at IS NULL ORDER BY specialization_name_ar")->fetch_all(MYSQLI_ASSOC);

$subject_types = [
    ['id' => 1, 'name' => 'نظري'],
    ['id' => 2, 'name' => 'عملي'],
    ['id' => 3, 'name' => 'نظري وعملي'],
    ['id' => 4, 'name' => 'تدريب ميداني'],
    ['id' => 5, 'name' => 'مشروع تخرج']
];

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>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #1e40af, #3b82f6);
            --success-gradient: linear-gradient(135deg, #047857, #10b981);
            --warning-gradient: linear-gradient(135deg, #b45309, #f59e0b);
            --danger-gradient: linear-gradient(135deg, #b91c1c, #ef4444);
            --info-gradient: linear-gradient(135deg, #6d28d9, #8b5cf6);
            --theoretical-color: #2563eb;
            --practical-color: #16a34a;
            --plus-color: #6b7280;
        }
        
        body {
            font-family: 'Cairo', sans-serif;
            background-color: #f8fafc;
        }
        
        .page-header {
            background: linear-gradient(135deg, #1e40af, #3b82f6);
            color: white;
            padding: 25px 0;
            margin-bottom: 25px;
            border-radius: 0 0 25px 25px;
            box-shadow: 0 4px 20px rgba(59, 130, 246, 0.3);
        }
        
        .filter-card {
            background: white;
            border-radius: 20px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
            border: 1px solid #e5e7eb;
        }
        
        .stats-card {
            background: white;
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            border: 1px solid #e5e7eb;
            height: 100%;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .stats-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            color: white;
        }
        
        .stats-icon.primary { background: var(--primary-gradient); }
        .stats-icon.success { background: var(--success-gradient); }
        .stats-icon.warning { background: var(--warning-gradient); }
        .stats-icon.info { background: var(--info-gradient); }
        
        .badge-code {
            background: #e0e7ff;
            color: #1e40af;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            font-family: monospace;
            direction: ltr;
            display: inline-block;
        }
        
        .badge-active {
            background: linear-gradient(135deg, #d1fae5, #a7f3d0);
            color: #047857;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        
        .badge-inactive {
            background: linear-gradient(135deg, #fee2e2, #fecaca);
            color: #b91c1c;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        
        /* تنسيق عرض الساعات */
        .hours-display {
            display: inline-flex;
            align-items: center;
            gap: 2px;
            font-weight: 600;
        }
        
        .badge-hours-theoretical {
            background: linear-gradient(135deg, #dbeafe, #bfdbfe);
            color: #1e40af;
            padding: 4px 8px;
            border-radius: 12px 0 0 12px;
            font-size: 0.9rem;
            font-weight: 600;
            display: inline-block;
        }
        
        .badge-hours-practical {
            background: linear-gradient(135deg, #dcfce7, #bbf7d0);
            color: #166534;
            padding: 4px 8px;
            border-radius: 0 12px 12px 0;
            font-size: 0.9rem;
            font-weight: 600;
            display: inline-block;
        }
        
        .badge-hours-plus {
            background: #e5e7eb;
            color: #4b5563;
            padding: 4px 4px;
            font-size: 0.9rem;
            font-weight: 700;
            display: inline-block;
        }
        
        .badge-hours-single {
            background: linear-gradient(135deg, #e0e7ff, #c7d2fe);
            color: #1e40af;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
            display: inline-block;
        }
        
        .badge-type {
            background: #dbeafe;
            color: #1e40af;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
            justify-content: center;
        }
        
        .action-buttons .btn {
            width: 32px;
            height: 32px;
            padding: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        
        .action-buttons .btn:hover {
            transform: translateY(-2px);
        }
        
        .btn-view {
            background: linear-gradient(135deg, #6d28d9, #8b5cf6);
            color: white;
            border: none;
        }
        
        .btn-edit {
            background: linear-gradient(135deg, #b45309, #f59e0b);
            color: white;
            border: none;
        }
        
        .btn-toggle-active {
            background: linear-gradient(135deg, #047857, #10b981);
            color: white;
            border: none;
        }
        
        .btn-toggle-inactive {
            background: linear-gradient(135deg, #b91c1c, #ef4444);
            color: white;
            border: none;
        }
        
        .btn-delete {
            background: linear-gradient(135deg, #b91c1c, #ef4444);
            color: white;
            border: none;
        }
        
        .pagination .page-link {
            color: #1e40af;
            border-radius: 10px;
            margin: 0 3px;
        }
        
        .pagination .page-item.active .page-link {
            background: linear-gradient(135deg, #1e40af, #3b82f6);
            border-color: transparent;
            color: white;
        }
        
        .table thead th {
            background: #f8fafc;
            color: #1e293b;
            font-weight: 700;
            font-size: 0.9rem;
            border-bottom: 2px solid #e2e8f0;
            text-align:center !important;
        }
        
        .table td {
            vertical-align: middle;
            font-size: 0.95rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 20px;
            border: 2px dashed #e5e7eb;
        }
        
        .empty-state i {
            font-size: 5rem;
            color: #94a3b8;
            margin-bottom: 20px;
        }
        
        .form-section {
            background: #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 #3b82f6;
        }
        
        .required-field::after {
            content: " *";
            color: #dc3545;
        }
        
        .badge-filter {
            background: #e0e7ff;
            color: #1e40af;
            padding: 3px 8px;
            border-radius: 6px;
            font-size: 0.8rem;
            display: inline-block;
            margin-left: 5px;
        }
        
        .modal-content {
            border-radius: 20px;
        }
        
        .modal-header {
            border-radius: 20px 20px 0 0;
            padding: 20px;
        }
        
        .modal-header.bg-warning {
            background: linear-gradient(135deg, #b45309, #f59e0b) !important;
        }
        
        .modal-header.bg-info {
            background: linear-gradient(135deg, #1e40af, #3b82f6) !important;
        }
        
        .modal-header.bg-danger {
            background: linear-gradient(135deg, #b91c1c, #ef4444) !important;
        }
        
        .btn-close {
            filter: brightness(0) invert(1);
        }


    </style>
</head>
<body class="bg-light" dir="rtl">
    <!-- Header -->
    <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 ms-2"></i> إدارة المقررات الدراسية</h2>
                    <p class="mb-0 opacity-75">عرض وإدارة المقررات الدراسية - <?= e($committeeName) ?></p>
                    <span class="badge bg-light text-dark mt-2"><?= number_format($totalCount) ?> نتيجة</span>
                </div>
                <div>
                    <button type="button" class="btn btn-light rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#addCourseModal">
                        <i class="fas fa-plus-circle ms-2"></i> إضافة مقرر
                    </button>
                    <a href="admin_dashboard.php" class="btn btn-outline-light rounded-pill px-4 me-2">
                        <i class="fas fa-arrow-right ms-2"></i> العودة
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container mb-5">
        <!-- رسائل التنبيه -->
        <?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>
                <?= e($_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>
                <?= e($_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 g-4 mb-4">
            <div class="col-md-3">
                <div class="stats-card d-flex align-items-center">
                    <div class="stats-icon primary ms-3">
                        <i class="fas fa-book"></i>
                    </div>
                    <div>
                        <div class="text-muted small">إجمالي المقررات</div>
                        <div class="h4 mb-0 fw-bold"><?= number_format($totalStats) ?></div>
                        <small class="text-muted">مقرر دراسي</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card d-flex align-items-center">
                    <div class="stats-icon success ms-3">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div>
                        <div class="text-muted small">مقررات نشطة</div>
                        <div class="h4 mb-0 fw-bold"><?= number_format($activeStats) ?></div>
                        <small class="text-muted">قيد الاستخدام</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card d-flex align-items-center">
                    <div class="stats-icon warning ms-3">
                        <i class="fas fa-pause-circle"></i>
                    </div>
                    <div>
                        <div class="text-muted small">مقررات غير نشطة</div>
                        <div class="h4 mb-0 fw-bold"><?= number_format($inactiveStats) ?></div>
                        <small class="text-muted">متوقفة</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card d-flex align-items-center">
                    <div class="stats-icon info ms-3">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div>
                        <div class="text-muted small">إجمالي الساعات</div>
                        <div class="h4 mb-0 fw-bold"><?= number_format($totalHours, 2) ?></div>
                        <small class="text-muted">ساعة معتمدة</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- بطاقة التصفية -->
        <div class="filter-card">
            <form method="get" class="row g-3" id="filterForm">
                <div class="col-md-3">
                    <label class="form-label fw-semibold"><i class="fas fa-search ms-1"></i>بحث</label>
                    <input type="text" class="form-control" name="search" id="searchInput" 
                           placeholder="رمز أو اسم المقرر..." value="<?= e($search) ?>">
                </div>
                
                <div class="col-md-2">
                    <label class="form-label fw-semibold"><i class="fas fa-university ms-1"></i>الكلية</label>
                    <select class="form-select" name="college_id" id="college_id" onchange="this.form.submit()">
                        <option value="">جميع الكليات</option>
                        <?php foreach ($colleges as $college): ?>
                            <?php if ($canAll || $college['id'] == $scopeCollege): ?>
                                <option value="<?= e($college['id']) ?>" 
                                    <?= ($college_id == $college['id']) ? 'selected' : '' ?>>
                                    <?= e($college['name']) ?>
                                </option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label fw-semibold"><i class="fas fa-building ms-1"></i>القسم (اختياري)</label>
                    <select class="form-select" name="section_id" id="section_id" onchange="this.form.submit()">
                        <option value="">جميع الأقسام</option>
                        <?php
                        $filteredSections = $sections;
                        if ($college_id) {
                            $filteredSections = array_filter($sections, function($s) use ($college_id) {
                                return ($s['parent'] ?? 0) == $college_id;
                            });
                        }
                        
                        foreach ($filteredSections as $section): ?>
                            <option value="<?= e($section['id']) ?>" 
                                <?= ($section_id == $section['id']) ? 'selected' : '' ?>>
                                <?= e($section['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label fw-semibold"><i class="fas fa-graduation-cap ms-1"></i>البرنامج</label>
                    <select class="form-select" name="program_id" id="program_id" onchange="this.form.submit()">
                        <option value="">جميع البرامج</option>
                        <?php foreach ($programs as $program): ?>
                            <option value="<?= e($program['id']) ?>" 
                                <?= ($program_id == $program['id']) ? 'selected' : '' ?>>
                                <?= e($program['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label class="form-label fw-semibold"><i class="fas fa-tag ms-1"></i>التخصص (اختياري)</label>
                    <select class="form-select" name="specialization_id" id="specialization_id" onchange="this.form.submit()">
                        <option value="">جميع التخصصات</option>
                        <?php
                        if ($section_id && $program_id) {
                            $filteredSpecs = array_filter($specializations, function($s) use ($section_id, $program_id) {
                                return ($s['section_id'] ?? 0) == $section_id && ($s['program_id'] ?? 0) == $program_id;
                            });
                            
                            foreach ($filteredSpecs as $spec): ?>
                                <option value="<?= e($spec['id']) ?>" 
                                    <?= ($specialization_id == $spec['id']) ? 'selected' : '' ?>>
                                    <?= e($spec['name']) ?>
                                </option>
                            <?php endforeach;
                        } else {
                            echo '<option value="" disabled>اختر القسم والبرنامج أولاً</option>';
                        }
                        ?>
                    </select>
                </div>
                
                <div class="col-md-1">
                    <label class="form-label fw-semibold"><i class="fas fa-list-alt ms-1"></i>النوع</label>
                    <select class="form-select" name="subjecttype_id" onchange="this.form.submit()">
                        <option value="">الكل</option>
                        <?php foreach ($subject_types as $type): ?>
                            <option value="<?= $type['id'] ?>" 
                                <?= ($subjecttype_id == $type['id']) ? 'selected' : '' ?>>
                                <?= $type['name'] ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-1">
                    <label class="form-label fw-semibold"><i class="fas fa-toggle-on ms-1"></i>الحالة</label>
                    <select class="form-select" name="is_active" onchange="this.form.submit()">
                        <option value="">الكل</option>
                        <option value="1" <?= ($is_active === 1) ? 'selected' : '' ?>>نشط</option>
                        <option value="0" <?= ($is_active === 0) ? 'selected' : '' ?>>غير نشط</option>
                    </select>
                </div>
            </form>
            
            <!-- عرض الفلاتر النشطة -->
            <?php if ($search || $program_id || $college_id || $section_id || $specialization_id || $subjecttype_id || $is_active !== null): ?>
                <div class="mt-3">
                    <small class="text-muted ms-2">الفلاتر النشطة:</small>
                    <?php if ($search): ?>
                        <span class="badge-filter ms-2">
                            <i class="fas fa-search"></i> "<?= e($search) ?>"
                        </span>
                    <?php endif; ?>
                    <?php if ($college_id): ?>
                        <span class="badge-filter ms-2"><i class="fas fa-university"></i> كلية</span>
                    <?php endif; ?>
                    <?php if ($section_id): ?>
                        <span class="badge-filter ms-2"><i class="fas fa-building"></i> قسم</span>
                    <?php endif; ?>
                    <?php if ($program_id): ?>
                        <span class="badge-filter ms-2"><i class="fas fa-graduation-cap"></i> برنامج</span>
                    <?php endif; ?>
                    <?php if ($specialization_id): ?>
                        <span class="badge-filter ms-2"><i class="fas fa-tag"></i> تخصص</span>
                    <?php endif; ?>
                    <?php if ($subjecttype_id): ?>
                        <span class="badge-filter ms-2"><i class="fas fa-list-alt"></i> نوع</span>
                    <?php endif; ?>
                    <?php if ($is_active !== null): ?>
                        <span class="badge-filter ms-2">
                            <i class="fas fa-<?= $is_active ? 'check-circle' : 'pause-circle' ?>"></i>
                            <?= $is_active ? 'نشط' : 'غير نشط' ?>
                        </span>
                    <?php endif; ?>
                    <a href="courses_management.php" class="btn btn-sm btn-outline-danger ms-2">
                        <i class="fas fa-times"></i> إزالة الكل
                    </a>
                </div>
            <?php endif; ?>
        </div>

        <!-- جدول المقررات -->
        <div class="card shadow-sm">
            <div class="card-body">
                <?php if (empty($courses)): ?>
                    <div class="empty-state">
                        <i class="fas fa-book-open"></i>
                        <h5 class="mt-3">لا توجد مقررات دراسية</h5>
                        <p class="text-muted mb-4">لم يتم إضافة أي مقررات بعد أو لا توجد نتائج تطابق بحثك</p>
                        <?php if ($search || $program_id || $college_id || $section_id || $specialization_id || $subjecttype_id || $is_active !== null): ?>
                            <a href="courses_management.php" class="btn btn-primary">
                                <i class="fas fa-sync-alt ms-2"></i> عرض الكل
                            </a>
                        <?php else: ?>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCourseModal">
                                <i class="fas fa-plus-circle ms-2"></i> إضافة مقرر جديد
                            </button>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle" id="coursesTable">
   <thead>
    <tr>
        <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 + $offset ?></td>
        <td><span class="badge-code"><?= e($course['subjectcode'] ?? '') ?></span></td>
        <td><?= e($course['subjectnamea'] ?? '') ?></td>
        <td class="text-muted small"><?= e($course['subjectnamee'] ?? '') ?></td>
        <td><span class="badge bg-light text-dark"><?= e($course['program_name'] ?? '-') ?></span></td>
        <td><span class="badge bg-light text-dark"><?= e($course['college_name'] ?? '-') ?></span></td>
        <td><span class="badge bg-light text-dark"><?= e($course['section_name'] ?? '-') ?></span></td>
        <td><span class="badge bg-light text-dark"><?= e($course['specialization_name'] ?? '-') ?></span></td>
        <td> <!-- عمود الساعات -->
            <?php 
            $hours = $course['subjecthours'] ?? '0';
            if (empty($hours)) $hours = '0';
            
            if (preg_match('/\((\d+)\+(\d+)\)/', $hours, $matches)) {
                $theoretical = $matches[1];
                $practical = $matches[2];
                ?>
                <span class="hours-display" title="<?= e($hours) ?>">
                    <span class="badge-hours-theoretical" title="ساعات نظرية"><?= e($theoretical) ?></span>
                    <span class="badge-hours-plus">+</span>
                    <span class="badge-hours-practical" title="ساعات عملية"><?= e($practical) ?></span>
                </span>
            <?php
            } elseif (preg_match('/^(\d+)\+(\d+)$/', $hours, $matches)) {
                $theoretical = $matches[1];
                $practical = $matches[2];
                ?>
                <span class="hours-display" title="<?= e($hours) ?>">
                    <span class="badge-hours-theoretical" title="ساعات نظرية"><?= e($theoretical) ?></span>
                    <span class="badge-hours-plus">+</span>
                    <span class="badge-hours-practical" title="ساعات عملية"><?= e($practical) ?></span>
                </span>
            <?php
            } else {
                $cleanHours = preg_replace('/[\(\)]/', '', $hours);
                if (empty($cleanHours)) $cleanHours = '0';
                ?>
                <span class="badge-hours-single" title="<?= e($hours) ?>"><?= e($cleanHours) ?></span>
            <?php
            }
            ?>
        </td>
        <td> <!-- عمود الساعات المعتمدة (جديد) -->
            <span class="badge bg-primary text-white p-2" style="font-size: 1rem;">
                <i class="fas fa-star ms-1"></i>
                <?= number_format((float)($course['credit_hours'] ?? 0), 2) ?>
            </span>
        </td>
        <td> <!-- عمود الإجراءات -->
            <div class="action-buttons">
                <button class="btn btn-view" onclick="viewCourse(<?= htmlspecialchars(json_encode($course)) ?>)" 
                        title="عرض التفاصيل" data-bs-toggle="tooltip">
                    <i class="fas fa-eye"></i>
                </button>
                
                <button class="btn btn-edit" onclick="editCourse(<?= htmlspecialchars(json_encode($course)) ?>)" 
                        title="تعديل" data-bs-toggle="tooltip">
                    <i class="fas fa-edit"></i>
                </button>
                
                <form method="post" style="display: inline;" class="d-inline">
                    <input type="hidden" name="csrf_token" value="<?= e($csrf_token) ?>">
                    <input type="hidden" name="action" value="toggle_status">
                    <input type="hidden" name="id" value="<?= (int)$course['id'] ?>">
                    <button type="submit" class="btn <?= $course['is_active'] ? 'btn-toggle-inactive' : 'btn-toggle-active' ?>" 
                            title="<?= $course['is_active'] ? 'إيقاف' : 'تفعيل' ?>" data-bs-toggle="tooltip"
                            onclick="return confirm('هل أنت متأكد من <?= $course['is_active'] ? 'إيقاف' : 'تفعيل' ?> المقرر؟')">
                        <i class="fas fa-<?= $course['is_active'] ? 'pause' : 'play' ?>"></i>
                    </button>
                </form>
                
                <form method="post" style="display: inline;" class="d-inline" 
                      onsubmit="return confirm('⚠️ هل أنت متأكد من حذف هذا المقرر؟\nلا يمكن التراجع عن هذا الإجراء.')">
                    <input type="hidden" name="csrf_token" value="<?= e($csrf_token) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$course['id'] ?>">
                    <button type="submit" class="btn btn-delete" title="حذف" data-bs-toggle="tooltip">
                        <i class="fas fa-trash"></i>
                    </button>
                </form>
            </div>
        </td>
    </tr>
    <?php endforeach; ?>
</tbody>
</table>
                    </div>
                    
                    <?php if ($totalPages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                    <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>">
                                                <?= $i ?>
                                            </a>
                                        </li>
                                    <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            </ul>
                            <div class="text-center text-muted small mt-2">
                                عرض <?= count($courses) ?> من أصل <?= number_format($totalCount) ?> مقرر
                            </div>
                        </nav>
                    <?php endif; ?>
                <?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 bg-primary text-white">
                    <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">
                        <input type="hidden" name="csrf_token" value="<?= e($csrf_token) ?>">
                        
                        <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-field">
                                        <i class="fas fa-barcode ms-2"></i> رمز المقرر
                                    </label>
                                    <input type="text" name="subjectcode" class="form-control" required 
                                           placeholder="مثال: MATH101" dir="ltr" maxlength="20">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required-field">
                                        <i class="fas fa-clock ms-2"></i>ساعات الإتصال
                                    </label>
                                    <input type="text" name="subjecthours" class="form-control text-center" required 
                                           placeholder="مثال:   2+2 أو (2+2) " value="3+2"  dir="ltr">
                                    <small class="text-muted d-block mt-1">
                                        <i class="fas fa-info-circle"></i> 
                                       يمكنك إدخال أي صيغة تحتوي على عدد ساعات النظري + ساعات العملي مثل: 3+2 او (3+2)
                                    </small>
                                </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 text-center" 
                                           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-field">
                                        <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-field">
                                        <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-field">
                                        <i class="fas fa-university ms-2"></i> الكلية
                                    </label>
                                    <select class="form-select" name="college_id" id="add_college_id" required 
                                            onchange="loadAddPrograms(this.value); loadAddSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <?php if ($canAll || $college['id'] == $scopeCollege): ?>
                                                <option value="<?= e($college['id']) ?>">
                                                    <?= e($college['name']) ?>
                                                </option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required-field">
                                        <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">
                                        <i class="fas fa-building ms-2"></i> القسم (اختياري)
                                    </label>
                                    <select class="form-select" name="section_id" id="add_section_id" 
                                            onchange="loadAddSpecializations()">
                                        <option value="">اختر القسم (اختياري)</option>
                                    </select>
                                    <small class="text-muted">يمكنك تركه فارغاً</small>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-tag ms-2"></i> التخصص (اختياري)
                                    </label>
                                    <select class="form-select" name="specialization_id" id="add_specialization_id">
                                        <option value="">اختر التخصص (اختياري)</option>
                                    </select>
                                    <small class="text-muted">يمكنك تركه فارغاً</small>
                                </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">
                            <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 text-white">
                    <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">
                        <input type="hidden" name="csrf_token" value="<?= e($csrf_token) ?>">
                        
                        <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-field">
                                        <i class="fas fa-barcode ms-2"></i> رمز المقرر
                                    </label>
                                    <input type="text" name="subjectcode" id="edit_subjectcode" class="form-control" required 
                                           dir="ltr" maxlength="20">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required-field">
                                        <i class="fas fa-clock ms-2"></i>ساعات الإتصال
                                    </label>
                                    <input type="text" name="subjecthours" id="edit_subjecthours" class="form-control text-center" required 
                                           placeholder="مثال:   2+2 أو (2+2) " value="3+2"  dir="ltr">
                                   <small class="text-muted d-block mt-1">
                                        <i class="fas fa-info-circle"></i> 
                                       يمكنك إدخال أي صيغة تحتوي على عدد ساعات النظري + ساعات العملي مثل: 3+2 او (3+2)
                                    </small>
                                </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 text-center" 
                                           min="0" max="12" step="0.5">
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required-field">
                                        <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-field">
                                        <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-field">
                                        <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): ?>
                                            <?php if ($canAll || $college['id'] == $scopeCollege): ?>
                                                <option value="<?= e($college['id']) ?>">
                                                    <?= e($college['name']) ?>
                                                </option>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required-field">
                                        <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">
                                        <i class="fas fa-building ms-2"></i> القسم (اختياري)
                                    </label>
                                    <select class="form-select" name="section_id" id="edit_section_id" 
                                            onchange="loadEditSpecializations()">
                                        <option value="">اختر القسم (اختياري)</option>
                                    </select>
                                    <small class="text-muted">يمكنك تركه فارغاً</small>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-tag ms-2"></i> التخصص (اختياري)
                                    </label>
                                    <select class="form-select" name="specialization_id" id="edit_specialization_id">
                                        <option value="">اختر التخصص (اختياري)</option>
                                    </select>
                                    <small class="text-muted">يمكنك تركه فارغاً</small>
                                </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 text-white">
                    <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_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_display"></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>

    <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>
        const allSections = <?= json_encode($sections) ?>;
        const allSpecializations = <?= json_encode($specializations) ?>;
        const csrfToken = '<?= e($csrf_token) ?>';
        
        $(document).ready(function() {
          $('#coursesTable').DataTable({
    language: {
        url: '//cdn.datatables.net/plug-ins/1.13.4/i18n/ar.json'
    },
    paging: false,
    info: false,
    searching: false,
    ordering: true,
    responsive: true,
    columnDefs: [
        { orderable: false, targets: 10 } // العمود 11 (الإجراءات) غير قابل للترتيب
    ]
});
            
            setTimeout(function() {
                $('.alert').fadeOut(500, function() {
                    $(this).remove();
                });
            }, 5000);
            
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl, {
                    placement: 'top',
                    boundary: 'window'
                });
            });
            
            let searchTimer;
            $('#searchInput').on('input', function() {
                clearTimeout(searchTimer);
                searchTimer = setTimeout(() => {
                    $('#filterForm').submit();
                }, 1000);
            });
            
            $('#college_id').on('change', function() {
                const collegeId = $(this).val();
                if (collegeId) {
                    $.ajax({
                        url: 'ajax/get_sections.php',
                        method: 'GET',
                        data: { college_id: collegeId },
                        dataType: 'json',
                        beforeSend: function() {
                            $('#section_id').prop('disabled', true).html('<option value="">جاري التحميل...</option>');
                        },
                        success: function(sections) {
                            let options = '<option value="">جميع الأقسام</option>';
                            sections.forEach(section => {
                                options += `<option value="${section.id}">${section.name}</option>`;
                            });
                            $('#section_id').html(options).prop('disabled', false);
                        },
                        error: function() {
                            $('#section_id').html('<option value="">خطأ في التحميل</option>').prop('disabled', false);
                        }
                    });
                }
            });
            
            function loadSpecializations() {
                const programId = $('#program_id').val();
                const sectionId = $('#section_id').val();
                
                if (!programId || !sectionId) {
                    $('#specialization_id').html('<option value="" disabled selected>اختر القسم والبرنامج أولاً</option>');
                    return;
                }
                
                $.ajax({
                    url: 'ajax/get_specializations.php',
                    method: 'GET',
                    data: { 
                        section_id: sectionId,
                        program_id: programId 
                    },
                    dataType: 'json',
                    beforeSend: function() {
                        $('#specialization_id').prop('disabled', true).html('<option value="">جاري التحميل...</option>');
                    },
                    success: function(specializations) {
                        let options = '<option value="">جميع التخصصات</option>';
                        if (specializations && specializations.length > 0) {
                            specializations.forEach(spec => {
                                const specId = spec.specialization_id || spec.id;
                                const specName = spec.specialization_name_ar || spec.name;
                                options += `<option value="${specId}">${specName}</option>`;
                            });
                        } else {
                            options = '<option value="" disabled>لا توجد تخصصات</option>';
                        }
                        $('#specialization_id').html(options).prop('disabled', false);
                        
                        <?php if ($specialization_id): ?>
                        $('#specialization_id').val('<?= $specialization_id ?>');
                        <?php endif; ?>
                    },
                    error: function(xhr, status, error) {
                        console.error('Error loading specializations:', error);
                        $('#specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                    }
                });
            }
            
            $('#section_id, #program_id').on('change', function() {
                loadSpecializations();
            });
            
            <?php if ($program_id && $section_id): ?>
            loadSpecializations();
            <?php endif; ?>
        });
        
        // =============================================
        // دوال الإضافة
        // =============================================
        function loadAddPrograms(collegeId) {
            if (!collegeId) {
                $('#add_program_id').html('<option value="">اختر البرنامج</option>').prop('disabled', true);
                $('#add_specialization_id').html('<option value="">اختر التخصص</option>').prop('disabled', true);
                return;
            }
            
            $.ajax({
                url: 'ajax/get_programs.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                beforeSend: function() {
                    $('#add_program_id').prop('disabled', true).html('<option value="">جاري التحميل...</option>');
                    $('#add_specialization_id').prop('disabled', true).html('<option value="">اختر التخصص</option>');
                },
                success: function(programs) {
                    let options = '<option value="">اختر البرنامج</option>';
                    if (programs && programs.length > 0) {
                        programs.forEach(program => {
                            options += `<option value="${program.id}">${program.name}</option>`;
                        });
                        $('#add_program_id').html(options).prop('disabled', false);
                    } else {
                        $('#add_program_id').html('<option value="">لا توجد برامج</option>').prop('disabled', true);
                    }
                },
                error: function() {
                    $('#add_program_id').html('<option value="">خطأ في التحميل</option>').prop('disabled', false);
                }
            });
        }
        
        function loadAddSections(collegeId) {
            if (!collegeId) {
                $('#add_section_id').html('<option value="">اختر القسم</option>').prop('disabled', true);
                $('#add_specialization_id').html('<option value="">اختر التخصص</option>').prop('disabled', true);
                return;
            }
            
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                beforeSend: function() {
                    $('#add_section_id').prop('disabled', true).html('<option value="">جاري التحميل...</option>');
                    $('#add_specialization_id').prop('disabled', true).html('<option value="">اختر التخصص</option>');
                },
                success: function(sections) {
                    let options = '<option value="">اختر القسم (اختياري)</option>';
                    if (sections && sections.length > 0) {
                        sections.forEach(section => {
                            options += `<option value="${section.id}">${section.name}</option>`;
                        });
                    } else {
                        options = '<option value="">لا توجد أقسام</option>';
                    }
                    $('#add_section_id').html(options).prop('disabled', false);
                },
                error: function() {
                    $('#add_section_id').html('<option value="">خطأ في التحميل</option>').prop('disabled', false);
                }
            });
        }
        
        function loadAddSpecializations() {
            const programId = $('#add_program_id').val();
            const sectionId = $('#add_section_id').val();
            
            if (!programId) {
                $('#add_specialization_id').html('<option value="">اختر البرنامج أولاً</option>').prop('disabled', true);
                return;
            }
            
            // إذا لم يتم اختيار قسم، نعرض تخصصات بدون فلترة القسم
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { 
                    program_id: programId,
                    section_id: sectionId || 0
                },
                dataType: 'json',
                beforeSend: function() {
                    $('#add_specialization_id').prop('disabled', true).html('<option value="">جاري تحميل التخصصات...</option>');
                },
                success: function(specializations) {
                    let options = '<option value="">اختر التخصص (اختياري)</option>';
                    if (specializations && specializations.length > 0) {
                        specializations.forEach(spec => {
                            const specId = spec.specialization_id || spec.id;
                            const specName = spec.specialization_name_ar || spec.name;
                            options += `<option value="${specId}">${specName}</option>`;
                        });
                    } else {
                        options = '<option value="">لا توجد تخصصات</option>';
                    }
                    $('#add_specialization_id').html(options).prop('disabled', false);
                },
                error: function() {
                    $('#add_specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                }
            });
        }
        
        // =============================================
        // دوال التعديل
        // =============================================
        function loadEditPrograms(collegeId) {
            if (!collegeId) {
                $('#edit_program_id').html('<option value="">اختر البرنامج</option>').prop('disabled', true);
                $('#edit_specialization_id').html('<option value="">اختر التخصص</option>').prop('disabled', true);
                return;
            }
            
            $.ajax({
                url: 'ajax/get_programs.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                beforeSend: function() {
                    $('#edit_program_id').prop('disabled', true).html('<option value="">جاري التحميل...</option>');
                    $('#edit_specialization_id').prop('disabled', true).html('<option value="">اختر التخصص</option>');
                },
                success: function(programs) {
                    let options = '<option value="">اختر البرنامج</option>';
                    if (programs && programs.length > 0) {
                        programs.forEach(program => {
                            options += `<option value="${program.id}">${program.name}</option>`;
                        });
                        $('#edit_program_id').html(options).prop('disabled', false);
                    } else {
                        $('#edit_program_id').html('<option value="">لا توجد برامج</option>').prop('disabled', true);
                    }
                },
                error: function() {
                    $('#edit_program_id').html('<option value="">خطأ في التحميل</option>').prop('disabled', false);
                }
            });
        }
        
        function loadEditSections(collegeId) {
            if (!collegeId) {
                $('#edit_section_id').html('<option value="">اختر القسم</option>').prop('disabled', true);
                $('#edit_specialization_id').html('<option value="">اختر التخصص</option>').prop('disabled', true);
                return;
            }
            
            $.ajax({
                url: 'ajax/get_sections.php',
                method: 'GET',
                data: { college_id: collegeId },
                dataType: 'json',
                beforeSend: function() {
                    $('#edit_section_id').prop('disabled', true).html('<option value="">جاري التحميل...</option>');
                    $('#edit_specialization_id').prop('disabled', true).html('<option value="">اختر التخصص</option>');
                },
                success: function(sections) {
                    let options = '<option value="">اختر القسم (اختياري)</option>';
                    if (sections && sections.length > 0) {
                        sections.forEach(section => {
                            options += `<option value="${section.id}">${section.name}</option>`;
                        });
                    } else {
                        options = '<option value="">لا توجد أقسام</option>';
                    }
                    $('#edit_section_id').html(options).prop('disabled', false);
                },
                error: function() {
                    $('#edit_section_id').html('<option value="">خطأ في التحميل</option>').prop('disabled', false);
                }
            });
        }
        
        function loadEditSpecializations() {
            const programId = $('#edit_program_id').val();
            const sectionId = $('#edit_section_id').val();
            
            if (!programId) {
                $('#edit_specialization_id').html('<option value="">اختر البرنامج أولاً</option>').prop('disabled', true);
                return;
            }
            
            $.ajax({
                url: 'ajax/get_specializations.php',
                method: 'GET',
                data: { 
                    program_id: programId,
                    section_id: sectionId || 0
                },
                dataType: 'json',
                beforeSend: function() {
                    $('#edit_specialization_id').prop('disabled', true).html('<option value="">جاري تحميل التخصصات...</option>');
                },
                success: function(specializations) {
                    let options = '<option value="">اختر التخصص (اختياري)</option>';
                    if (specializations && specializations.length > 0) {
                        specializations.forEach(spec => {
                            const specId = spec.specialization_id || spec.id;
                            const specName = spec.specialization_name_ar || spec.name;
                            options += `<option value="${specId}">${specName}</option>`;
                        });
                    } else {
                        options = '<option value="">لا توجد تخصصات</option>';
                    }
                    $('#edit_specialization_id').html(options).prop('disabled', false);
                },
                error: function() {
                    $('#edit_specialization_id').html('<option value="">خطأ في تحميل التخصصات</option>').prop('disabled', false);
                }
            });
        }
        
        // =============================================
        // دوال الإجراءات
        // =============================================
        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);
            $('#edit_is_active').prop('checked', course.is_active == 1);
            
            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_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 || '-');
            
            // تنسيق عرض الساعات في نافذة التفاصيل
            let hoursDisplay = course.subjecthours || '-';
            if (hoursDisplay && hoursDisplay != '-') {
                if (hoursDisplay.includes('+')) {
                    let cleanHours = hoursDisplay.replace(/[\(\)]/g, '');
                    let parts = cleanHours.split('+');
                    let explanation = '';
                    parts.forEach((part, index) => {
                        if (part.trim() !== '') {
                            explanation += part.trim() + (index === 0 ? ' نظري' : ' عملي');
                            if (index < parts.length - 1) explanation += ' + ';
                        }
                    });
                    hoursDisplay = hoursDisplay + '  ←  ' + explanation;
                } else {
                    let cleanHours = hoursDisplay.replace(/[\(\)]/g, '');
                    hoursDisplay = cleanHours + ' ساعات' + (cleanHours !== '-' ? ' نظرية' : '');
                }
            }
            $('#view_subjecthours_display').text(hoursDisplay);
            
            $('#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();
        }
        
        // التحقق من صحة النماذج
        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>
<?php include 'footer.php'; ?>