<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/classes/Auth.php';

$auth = new Auth();
if (!$auth->isLoggedIn() || (!$auth->hasRole('admin') && !$auth->hasRole('college_admin'))) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();
$message = '';

// فحص وإصلاح AUTO_INCREMENT إذا لزم الأمر
try {
    $zero_record = $db->fetchOne("SELECT id FROM courses WHERE id = 0");
    if ($zero_record) {
        $db->query("DELETE FROM courses WHERE id = 0");
    }
    
    $columns = $db->fetchAll("SHOW COLUMNS FROM courses WHERE Field = 'id'");
    $has_auto_increment = false;
    if (!empty($columns)) {
        $has_auto_increment = (strpos($columns[0]['Extra'], 'auto_increment') !== false);
    }
    
    if (!$has_auto_increment) {
        $max_id_result = $db->fetchOne("SELECT MAX(id) as max_id FROM courses WHERE id > 0");
        $max_id = $max_id_result['max_id'] ?? 0;
        $new_auto_increment = max($max_id + 1, 1);
        $db->getConnection()->exec("ALTER TABLE courses MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
        $db->getConnection()->exec("ALTER TABLE courses AUTO_INCREMENT = " . (int)$new_auto_increment);
    }
} catch (PDOException $e) {
    error_log("Auto-increment check error: " . $e->getMessage());
}

// معالجة AJAX requests
if (isset($_GET['action']) && $_GET['action'] == 'get_majors' && isset($_GET['college_id'])) {
    header('Content-Type: application/json');
    $college_id = (int)$_GET['college_id'];
    $majors = $db->fetchAll(
        "SELECT id, name_ar FROM majors WHERE college_id = ? ORDER BY name_ar",
        [$college_id]
    );
    echo json_encode($majors);
    exit;
}

if (isset($_GET['action']) && $_GET['action'] == 'get_semesters' && isset($_GET['major_id'])) {
    header('Content-Type: application/json');
    $major_id = (int)$_GET['major_id'];
    $semesters = $db->fetchAll(
        "SELECT id, semester_number, academic_year FROM semesters WHERE major_id = ? ORDER BY academic_year DESC, semester_number DESC",
        [$major_id]
    );
    echo json_encode($semesters);
    exit;
}

// جلب المواد المدخلة مسبقاً للتخصص (للعرض قبل إضافة مواد جديدة)
if (isset($_GET['action']) && $_GET['action'] == 'get_courses' && isset($_GET['major_id'])) {
    header('Content-Type: application/json');
    $major_id = (int)$_GET['major_id'];
    $courses = $db->fetchAll(
        "SELECT c.id, c.code, c.name_ar, c.name_en, c.credit_hours, c.is_required, c.semester_id,
                s.semester_number, s.academic_year
         FROM courses c
         LEFT JOIN semesters s ON c.semester_id = s.id
         WHERE c.major_id = ?
         ORDER BY c.semester_id IS NULL DESC, s.academic_year DESC, s.semester_number, c.code",
        [$major_id]
    );
    echo json_encode($courses);
    exit;
}

// معالجة الإضافة
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_bulk') {
    $college_id = (int)($_POST['college_id'] ?? 0);
    $major_id = (int)($_POST['major_id'] ?? 0);
    
    // جلب بيانات المواد من النموذج
    $courses_data = [];
    if (isset($_POST['courses']) && is_array($_POST['courses'])) {
        foreach ($_POST['courses'] as $course) {
            if (!empty($course['name_ar']) && !empty($course['code'])) {
                $courses_data[] = [
                    'code' => trim($course['code']),
                    'name_ar' => trim($course['name_ar']),
                    'name_en' => trim($course['name_en'] ?? ''),
                    'credit_hours' => !empty($course['credit_hours']) ? (int)$course['credit_hours'] : 3,
                    'is_required' => isset($course['is_required']) ? 1 : 0,
                    'semester_id' => !empty($course['semester_id']) ? (int)$course['semester_id'] : null,
                ];
            }
        }
    }
    
    if ($college_id && $major_id && !empty($courses_data)) {
        // التحقق من الصلاحية
        if (!$auth->belongsToCollege($college_id) && !$auth->hasRole('admin')) {
            $message = '<div class="alert alert-error">ليس لديك صلاحية لإضافة مواد في هذه الكلية</div>';
        } else {
            try {
                $db->getConnection()->beginTransaction();
                
                $success_count = 0;
                $error_count = 0;
                $duplicate_count = 0;
                $errors = [];
                
                foreach ($courses_data as $index => $course_data) {
                    try {
                        // التحقق من عدم وجود مادة بنفس الرمز في نفس التخصص
                        $existing = $db->fetchOne(
                            "SELECT * FROM courses WHERE code = ? AND major_id = ?",
                            [$course_data['code'], $major_id]
                        );
                        
                        if ($existing) {
                            $duplicate_count++;
                            continue;
                        }
                        
                        // التأكد من عدم وجود سجل ب id=0
                        $zero_record = $db->fetchOne("SELECT id FROM courses WHERE id = 0");
                        if ($zero_record) {
                            $db->query("DELETE FROM courses WHERE id = 0");
                        }
                        
                        // إضافة المادة
                        $db->query(
                            "INSERT INTO courses (major_id, semester_id, code, name_ar, name_en, credit_hours, is_required) 
                             VALUES (?, ?, ?, ?, ?, ?, ?)",
                            [
                                $major_id, 
                                $course_data['semester_id'], 
                                $course_data['code'], 
                                $course_data['name_ar'], 
                                $course_data['name_en'], 
                                $course_data['credit_hours'], 
                                $course_data['is_required']
                            ]
                        );
                        
                        // الحصول على ID المولّد تلقائياً
                        $course_id = $db->getConnection()->lastInsertId();
                        
                        // إذا كان ID = 0، إصلاح المشكلة
                        if ($course_id == 0 || $course_id === false || $course_id === '0') {
                            $db->query("DELETE FROM courses WHERE id = 0");
                            $max_id_result = $db->fetchOne("SELECT MAX(id) as max_id FROM courses WHERE id > 0");
                            $max_id = $max_id_result['max_id'] ?? 0;
                            $new_auto_increment = max($max_id + 1, 1);
                            $db->getConnection()->exec("ALTER TABLE courses MODIFY id INT(11) NOT NULL AUTO_INCREMENT");
                            $db->getConnection()->exec("ALTER TABLE courses AUTO_INCREMENT = " . (int)$new_auto_increment);
                            
                            $db->query(
                                "INSERT INTO courses (major_id, semester_id, code, name_ar, name_en, credit_hours, is_required) 
                                 VALUES (?, ?, ?, ?, ?, ?, ?)",
                                [
                                    $major_id, 
                                    $course_data['semester_id'], 
                                    $course_data['code'], 
                                    $course_data['name_ar'], 
                                    $course_data['name_en'], 
                                    $course_data['credit_hours'], 
                                    $course_data['is_required']
                                ]
                            );
                            $course_id = $db->getConnection()->lastInsertId();
                        }
                        
                        $success_count++;
                    } catch (PDOException $e) {
                        $error_count++;
                        $error_msg = $e->getMessage();
                        if (strpos($error_msg, 'Duplicate entry') !== false || strpos($error_msg, '1062') !== false) {
                            $duplicate_count++;
                        } else {
                            $errors[] = "المادة " . $course_data['code'] . ": " . $error_msg;
                        }
                    }
                }
                
                $db->getConnection()->commit();
                
                // بناء رسالة النتيجة
                if ($success_count > 0) {
                    $message = '<div class="alert alert-success">✓ تم إضافة ' . $success_count . ' مادة بنجاح</div>';
                }
                if ($duplicate_count > 0) {
                    $message .= '<div class="alert alert-info">⚠ ' . $duplicate_count . ' مادة موجودة مسبقاً (تم تخطيها)</div>';
                }
                if ($error_count > 0) {
                    $message .= '<div class="alert alert-warning">⚠ ' . $error_count . ' خطأ في الإضافة</div>';
                    if (count($errors) > 0 && count($errors) <= 10) {
                        $message .= '<div class="alert alert-info" style="margin-top:10px;"><small>' . implode('<br>', array_map('htmlspecialchars', $errors)) . '</small></div>';
                    }
                }
            } catch (Exception $e) {
                $db->getConnection()->rollBack();
                $message = '<div class="alert alert-error">خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>';
            }
        }
    } else {
        $message = '<div class="alert alert-error">يرجى ملء جميع الحقول المطلوبة</div>';
    }
}

// جلب الكليات
$selected_college_id = isset($_GET['college_id']) ? (int)$_GET['college_id'] : 0;
$selected_major_id = isset($_GET['major_id']) ? (int)$_GET['major_id'] : 0;

if ($auth->hasRole('admin')) {
    $colleges = $db->fetchAll("SELECT * FROM colleges ORDER BY name_ar");
} else {
    $college_id = $_SESSION['college_id'] ?? 0;
    $colleges = $db->fetchAll("SELECT * FROM colleges WHERE id = ? ORDER BY name_ar", [$college_id]);
    $selected_college_id = $college_id;
}

// إذا كان major_id محدداً، جلب معلومات الكلية والتخصص
$major_info = null;
if ($selected_major_id) {
    $major_info = $db->fetchOne(
        "SELECT m.*, c.id as college_id, c.name_ar as college_name 
         FROM majors m 
         JOIN colleges c ON m.college_id = c.id 
         WHERE m.id = ?",
        [$selected_major_id]
    );
    if ($major_info) {
        $selected_college_id = $major_info['college_id'];
    }
}
?>
<!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>
    <?php include __DIR__ . '/includes/compatibility.php'; ?>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px 0;
        }
        
        .main-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .page-header h1 {
            color: #667eea;
            margin: 0 0 10px 0;
            font-size: 32px;
            font-weight: 700;
        }
        
        .page-header p {
            color: #666;
            margin: 0;
            font-size: 16px;
        }
        
        .form-card {
            background: white;
            border-radius: 15px;
            padding: 35px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .form-section {
            margin-bottom: 30px;
        }
        
        .form-section-title {
            color: #667eea;
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 0;
        }
        
        .form-group label {
            display: block;
            color: #333;
            font-weight: 600;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 15px;
            transition: all 0.3s ease;
            background: #fafafa;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .courses-table-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            overflow-x: auto;
        }
        
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .table-header h3 {
            color: #667eea;
            margin: 0;
            font-size: 22px;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(17, 153, 142, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn-add-row {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 10px 20px;
            font-size: 14px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        table thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        table th {
            padding: 15px;
            text-align: right;
            font-weight: 600;
            font-size: 14px;
        }
        
        table td {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        table tbody tr {
            transition: background 0.2s ease;
        }
        
        table tbody tr:hover {
            background: #f8f9ff;
        }
        
        table input, table select {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            background: white;
        }
        
        table input:focus, table select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }
        
        .btn-remove {
            background: #dc3545;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
        }
        
        .btn-remove:hover {
            background: #c82333;
        }
        
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-size: 15px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .info-box {
            background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
            border-right: 4px solid #667eea;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
        }
        
        .info-box p {
            margin: 5px 0;
            color: #555;
        }
        
        .info-box strong {
            color: #667eea;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>
    
    <div class="main-container">
        <div class="page-header">
            <h1>📖 إضافة مواد - دفعة واحدة</h1>
            <p>أضف عدة مواد دفعة واحدة بسهولة وسرعة</p>
        </div>
        
        <?php echo $message; ?>
        
        <form method="POST" id="addCoursesForm">
            <input type="hidden" name="action" value="add_bulk">
            
            <div class="form-card">
                <div class="form-section">
                    <h3 class="form-section-title">📋 معلومات الكلية والتخصص</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label>الكلية *</label>
                            <select name="college_id" id="college_id" required onchange="loadMajors()">
                                <option value="">-- اختر الكلية --</option>
                                <?php foreach ($colleges as $college): ?>
                                    <option value="<?php echo $college['id']; ?>" <?php echo ($selected_college_id && $college['id'] == $selected_college_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($college['name_ar']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>التخصص *</label>
                            <select name="major_id" id="major_id" required <?php echo $selected_college_id ? '' : 'disabled'; ?> onchange="loadSemesters()">
                                <option value="">-- <?php echo $selected_college_id ? 'اختر التخصص' : 'اختر الكلية أولاً'; ?> --</option>
                                <?php if ($selected_college_id && $major_info): ?>
                                    <option value="<?php echo $major_info['id']; ?>" selected><?php echo htmlspecialchars($major_info['name_ar']); ?></option>
                                <?php endif; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <div id="existingCoursesSection" class="courses-table-container" style="display: none; margin-bottom: 25px;">
                <div class="table-header">
                    <h3>📋 المواد المدخلة مسبقاً</h3>
                    <span id="existingCoursesCount" style="color: #667eea; font-weight: 600;"></span>
                </div>
                <div id="existingCoursesPlaceholder" style="padding: 15px; color: #666; text-align: center;">
                    اختر التخصص لعرض المواد المسجلة.
                </div>
                <table id="existingCoursesTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>الرمز</th>
                            <th>اسم المادة (عربي)</th>
                            <th>اسم المادة (إنجليزي)</th>
                            <th>الساعات</th>
                            <th>الفصل الدراسي</th>
                            <th>نوع المادة</th>
                            <th style="width: 100px;">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="existingCoursesTableBody"></tbody>
                </table>
            </div>
            
            <div class="courses-table-container">
                <div class="table-header">
                    <h3>📚 إضافة مواد جديدة</h3>
                    <div>
                        <a href="#" id="editCoursesLink" class="btn btn-secondary" style="margin-left: 10px; display: none;">تعديل المواد</a>
                        <button type="button" class="btn btn-add-row" onclick="addCourseRow()">
                            ➕ إضافة صف جديد
                        </button>
                    </div>
                </div>
                
                <div class="info-box">
                    <p><strong>💡 ملاحظات:</strong></p>
                    <p>• الحقول المطلوبة: اسم المادة (عربي) ورمز المادة</p>
                    <p>• يمكنك إضافة عدة صفوف وإزالة أي صف غير مطلوب</p>
                    <p>• المواد المكررة (بنفس الرمز في نفس التخصص) سيتم تخطيها تلقائياً</p>
                    <p>• الفصل الدراسي اختياري - إذا تركت فارغاً ستكون المادة عامة لجميع الفصول</p>
                </div>
                
                <table id="coursesTable">
                    <thead>
                        <tr>
                            <th style="width: 80px;">#</th>
                            <th>رمز المادة *</th>
                            <th>اسم المادة (عربي) *</th>
                            <th>اسم المادة (إنجليزي)</th>
                            <th>عدد الساعات</th>
                            <th>الفصل الدراسي</th>
                            <th>نوع المادة</th>
                            <th style="width: 100px;">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="coursesTableBody">
                        <tr>
                            <td>1</td>
                            <td><input type="text" name="courses[0][code]" required></td>
                            <td><input type="text" name="courses[0][name_ar]" required></td>
                            <td><input type="text" name="courses[0][name_en]"></td>
                            <td><input type="number" name="courses[0][credit_hours]" value="3" min="1" max="6"></td>
                            <td>
                                <select name="courses[0][semester_id]" id="course_semester_0">
                                    <option value="">جميع الفصول</option>
                                </select>
                            </td>
                            <td>
                                <select name="courses[0][is_required]">
                                    <option value="1">إجبارية</option>
                                    <option value="0">اختيارية</option>
                                </select>
                            </td>
                            <td>
                                <a href="#" onclick="var m=document.getElementById('major_id').value; if(m) location.href='courses.php?major_id='+m; return false;" class="btn btn-info" style="padding: 6px 12px; font-size: 13px; text-decoration: none; margin-left: 4px;">تعديل</a>
                                <button type="button" class="btn-remove" onclick="removeRow(this)" disabled>🗑️</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="form-card" style="text-align: center; margin-top: 30px;">
                <button type="submit" class="btn btn-success" style="padding: 15px 40px; font-size: 18px;">
                    ✅ حفظ جميع المواد
                </button>
                <a href="courses.php" class="btn btn-secondary" style="margin-right: 15px;">
                    🔙 العودة
                </a>
            </div>
        </form>
    </div>
    
    <script>
        let rowCount = 1;
        let semestersData = [];
        
        function addCourseRow() {
            const tbody = document.getElementById('coursesTableBody');
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${rowCount + 1}</td>
                <td><input type="text" name="courses[${rowCount}][code]" required></td>
                <td><input type="text" name="courses[${rowCount}][name_ar]" required></td>
                <td><input type="text" name="courses[${rowCount}][name_en]"></td>
                <td><input type="number" name="courses[${rowCount}][credit_hours]" value="3" min="1" max="6"></td>
                <td>
                    <select name="courses[${rowCount}][semester_id]" id="course_semester_${rowCount}">
                        <option value="">جميع الفصول</option>
                    </select>
                </td>
                <td>
                    <select name="courses[${rowCount}][is_required]">
                        <option value="1">إجبارية</option>
                        <option value="0">اختيارية</option>
                    </select>
                </td>
                <td>
                    <a href="#" onclick="var m=document.getElementById('major_id').value; if(m) location.href='courses.php?major_id='+m; return false;" class="btn btn-info" style="padding: 6px 12px; font-size: 13px; text-decoration: none; margin-left: 4px;">تعديل</a>
                    <button type="button" class="btn-remove" onclick="removeRow(this)">🗑️</button>
                </td>
            `;
            tbody.appendChild(row);
            
            // ملء قائمة الفصول الدراسية للصف الجديد
            const semesterSelect = row.querySelector(`#course_semester_${rowCount}`);
            semestersData.forEach(semester => {
                const option = document.createElement('option');
                option.value = semester.id;
                option.textContent = `فصل ${semester.semester_number} - ${semester.academic_year}`;
                semesterSelect.appendChild(option);
            });
            
            rowCount++;
            updateRowNumbers();
        }
        
        function removeRow(button) {
            const row = button.closest('tr');
            const tbody = document.getElementById('coursesTableBody');
            if (tbody.children.length > 1) {
                row.remove();
                updateRowNumbers();
            }
        }
        
        function updateRowNumbers() {
            const rows = document.querySelectorAll('#coursesTableBody tr');
            rows.forEach((row, index) => {
                row.querySelector('td:first-child').textContent = index + 1;
                if (rows.length === 1) {
                    row.querySelector('.btn-remove').disabled = true;
                } else {
                    row.querySelector('.btn-remove').disabled = false;
                }
            });
        }
        
        function loadMajors() {
            const collegeId = document.getElementById('college_id').value;
            const majorSelect = document.getElementById('major_id');
            const selectedMajorId = <?php echo $selected_major_id ? $selected_major_id : 'null'; ?>;
            
            if (!collegeId) {
                majorSelect.innerHTML = '<option value="">-- اختر الكلية أولاً --</option>';
                majorSelect.disabled = true;
                return;
            }
            
            majorSelect.innerHTML = '<option value="">-- اختر التخصص --</option>';
            majorSelect.disabled = false;
            
            fetch(`add_courses_bulk.php?action=get_majors&college_id=${collegeId}`)
                .then(response => response.json())
                .then(data => {
                    data.forEach(major => {
                        const option = document.createElement('option');
                        option.value = major.id;
                        option.textContent = major.name_ar;
                        if (selectedMajorId && major.id == selectedMajorId) {
                            option.selected = true;
                        }
                        majorSelect.appendChild(option);
                    });
                    majorSelect.disabled = false;
                    
                    // إذا كان التخصص محدداً مسبقاً، تحميل الفصول الدراسية
                    if (selectedMajorId && majorSelect.value == selectedMajorId) {
                        loadSemesters();
                    }
                })
                .catch(error => {
                    console.error('Error loading majors:', error);
                });
        }
        
        function loadSemesters() {
            const majorId = document.getElementById('major_id').value;
            const semesterSelects = document.querySelectorAll('select[id^="course_semester_"]');
            
            semestersData = [];
            semesterSelects.forEach(select => {
                select.innerHTML = '<option value="">جميع الفصول</option>';
            });
            
            if (!majorId) {
                document.getElementById('existingCoursesSection').style.display = 'none';
                return;
            }
            
            loadExistingCourses(majorId);
            updateEditCoursesLink();
            
            fetch(`add_courses_bulk.php?action=get_semesters&major_id=${majorId}`)
                .then(response => response.json())
                .then(data => {
                    semestersData = data;
                    data.forEach(semester => {
                        const option = document.createElement('option');
                        option.value = semester.id;
                        option.textContent = `فصل ${semester.semester_number} - ${semester.academic_year}`;
                        semesterSelects.forEach(select => {
                            const newOption = option.cloneNode(true);
                            select.appendChild(newOption);
                        });
                    });
                })
                .catch(error => {
                    console.error('Error loading semesters:', error);
                });
        }
        
        function loadExistingCourses(majorId) {
            const section = document.getElementById('existingCoursesSection');
            const placeholder = document.getElementById('existingCoursesPlaceholder');
            const table = document.getElementById('existingCoursesTable');
            const tbody = document.getElementById('existingCoursesTableBody');
            const countEl = document.getElementById('existingCoursesCount');
            
            section.style.display = 'block';
            placeholder.style.display = 'block';
            placeholder.textContent = 'جاري تحميل المواد...';
            table.style.display = 'none';
            tbody.innerHTML = '';
            
            if (!majorId) {
                placeholder.textContent = 'اختر التخصص لعرض المواد المسجلة.';
                return;
            }
            
            fetch(`add_courses_bulk.php?action=get_courses&major_id=${majorId}`)
                .then(response => response.json())
                .then(data => {
                    if (!data || data.length === 0) {
                        placeholder.textContent = 'لا توجد مواد مسجلة لهذا التخصص بعد.';
                        placeholder.style.display = 'block';
                        table.style.display = 'none';
                        countEl.textContent = '';
                        return;
                    }
                    placeholder.style.display = 'none';
                    table.style.display = 'table';
                    countEl.textContent = '(' + data.length + ' مادة)';
                    const majorId = document.getElementById('major_id').value;
                    data.forEach(c => {
                        const tr = document.createElement('tr');
                        const semesterLabel = c.semester_number != null 
                            ? 'فصل ' + c.semester_number + ' - ' + (c.academic_year || '')
                            : 'جميع الفصول';
                        const editUrl = 'courses.php?major_id=' + encodeURIComponent(majorId) + '&edit_course=' + encodeURIComponent(c.id);
                        tr.innerHTML = `
                            <td>${escapeHtml(c.code)}</td>
                            <td>${escapeHtml(c.name_ar)}</td>
                            <td>${escapeHtml(c.name_en || '-')}</td>
                            <td>${c.credit_hours || '-'}</td>
                            <td>${escapeHtml(semesterLabel)}</td>
                            <td>${c.is_required == 1 ? 'إجبارية' : 'اختيارية'}</td>
                            <td><a href="${editUrl}" class="btn btn-info" style="padding: 6px 12px; font-size: 13px; text-decoration: none;">تعديل</a></td>
                        `;
                        tbody.appendChild(tr);
                    });
                })
                .catch(error => {
                    console.error('Error loading courses:', error);
                    placeholder.textContent = 'حدث خطأ أثناء تحميل المواد.';
                    placeholder.style.display = 'block';
                });
        }
        
        function escapeHtml(text) {
            if (text == null) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function updateEditCoursesLink() {
            const majorId = document.getElementById('major_id').value;
            const link = document.getElementById('editCoursesLink');
            if (majorId) {
                link.href = 'courses.php?major_id=' + encodeURIComponent(majorId);
                link.style.display = 'inline-block';
            } else {
                link.style.display = 'none';
            }
        }
        
        // تحميل التخصصات والمواد المدخلة مسبقاً عند فتح الصفحة إذا كانت الكلية/التخصص محددة
        document.addEventListener('DOMContentLoaded', function() {
            const collegeSelect = document.getElementById('college_id');
            const majorSelect = document.getElementById('major_id');
            
            if (collegeSelect && collegeSelect.value) {
                loadMajors();
                // إذا كان التخصص محدداً مسبقاً، تحميل الفصول والمواد المدخلة مسبقاً
                if (majorSelect && majorSelect.value) {
                    loadSemesters();
                    updateEditCoursesLink();
                }
            }
        });
    </script>
    
    <?php include 'includes/footer.php'; ?>
</body>
</html>
