<?php
// manage-specializations.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
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;

// Get dropdown data
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
$colleges_stmt->execute();
$colleges = $colleges_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$sections_stmt = $mysqli1->prepare("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
$sections_stmt->execute();
$sections = $sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
$programs_stmt->execute();
$programs = $programs_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get existing specializations
$specializations_stmt = $mysqli1->prepare("
    SELECT s.*, c.name as college_name, sec.name as section_name, p.name as program_name 
    FROM specializations s
    LEFT JOIN colleges c ON s.college_id = c.id
    LEFT JOIN sections sec ON s.section_id = sec.id
    LEFT JOIN programs p ON s.program_id = p.id
    WHERE s.deleted_at IS NULL 
    ORDER BY s.specialization_id DESC
");
$specializations_stmt->execute();
$specializations = $specializations_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

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

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة التخصصات - لوحة اللجنة</title>
    
    <!-- Bootstrap 5 RTL -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap RTL -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap5.min.css">
    <!-- Google Fonts: Cairo -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --bs-font-sans-serif: 'Cairo', system-ui, -apple-system, sans-serif;
        }
        
        body, h1, h2, h3, h4, h5, h6, p, a, button, label, input, select, textarea, .form-control, .form-select, .btn {
            font-family: 'Cairo', sans-serif !important;
            text-align: right !important;
        }
        
        .form-control, .form-select {
            text-align: right;
            direction: rtl;
        }
        
        .form-check {
            padding-right: 1.5em;
            padding-left: 0;
        }
        
        .form-check-input {
            float: right;
            margin-right: -1.5em;
            margin-left: 0;
        }
        
        .required::after {
            content: " *";
            color: #dc3545;
        }
        
        .rtl-heading {
            text-align: right;
            font-weight: 700;
            color: #1F3A2E;
            border-right: 4px solid #2ecc71;
            padding-right: 15px;
            margin: 20px 0;
        }
        
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        
        .form-section {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }
        
        .section-title {
            color: #2c3e50;
            font-weight: 600;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #2596be;
        }
        
        .badge-college {
            background-color: #e3f2fd;
            color: #0d47a1;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .badge-section {
            background-color: #e8f5e8;
            color: #1b5e20;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .badge-program {
            background-color: #fff3e0;
            color: #bf360c;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        
        .table-actions {
            white-space: nowrap;
        }
        
        .table-actions .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        
        .dataTables_wrapper .dataTables_length,
        .dataTables_wrapper .dataTables_filter,
        .dataTables_wrapper .dataTables_info,
        .dataTables_wrapper .dataTables_paginate {
            text-align: right !important;
        }
        
        .dataTables_wrapper .dataTables_filter input {
            margin-right: 0.5rem;
            margin-left: 0;
        }
        
        .modal-content {
            border-radius: 16px;
        }
        
        .modal-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            border-radius: 16px 16px 0 0;
        }
        
        .modal-footer {
            background-color: #f8f9fa;
            border-top: 1px solid #e9ecef;
            border-radius: 0 0 16px 16px;
        }
    </style>
</head>
<body class="bg-light" dir="rtl">
    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold text-dark">
                <i class="fas fa-tag ms-2"></i>إدارة التخصصات
            </h3>
            <div class="me-auto">
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addSpecializationModal">
                    <i class="fas fa-plus-circle ms-2"></i>إضافة تخصص جديد
                </button>
                <a href="admin_dashboard.php" class="btn btn-outline-secondary ms-2">
                    <i class="fas fa-arrow-right me-2"></i>العودة للوحة التحكم
                </a>
            </div>
        </div>

        <!-- Alert Messages -->
        <?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; ?>

        <!-- Specializations Table -->
        <div class="card card-arabic p-3">
            <div class="table-responsive">
                <table id="specializationsTable" class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>التخصص (عربي)</th>
                            <th>التخصص (إنجليزي)</th>
                            <th>الكلية</th>
                            <th>القسم</th>
                            <th>البرنامج</th>
                            <th>الدرجة الممنوحة (عربي)</th>
                            <th>الدرجة الممنوحة (إنجليزي)</th>
                            <th>تاريخ الإضافة</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($specializations as $spec): ?>
                        <tr>
                            <td><?= e($spec['specialization_id']) ?></td>
                            <td><?= e($spec['specialization_name_ar']) ?></td>
                            <td><?= e($spec['specialization_name_en']) ?></td>
                            <td>
                                <span class="badge-college">
                                    <i class="fas fa-university ms-1"></i>
                                    <?= e($spec['college_name'] ?? 'غير محدد') ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge-section">
                                    <i class="fas fa-building ms-1"></i>
                                    <?= e($spec['section_name'] ?? 'غير محدد') ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge-program">
                                    <i class="fas fa-graduation-cap ms-1"></i>
                                    <?= e($spec['program_name'] ?? 'غير محدد') ?>
                                </span>
                            </td>
                            <td><?= e($spec['degree_awarded_ar'] ?? '-') ?></td>
                            <td><?= e($spec['degree_awarded_en'] ?? '-') ?></td>
                            <td><?= date('Y-m-d', strtotime($spec['created_at'])) ?></td>
                            <td class="table-actions">
                                <button class="btn btn-sm btn-info" onclick="editSpecialization(<?= htmlspecialchars(json_encode($spec)) ?>)" 
                                        data-bs-toggle="tooltip" title="تعديل">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteSpecialization(<?= $spec['specialization_id'] ?>, '<?= e($spec['specialization_name_ar']) ?>')"
                                        data-bs-toggle="tooltip" title="حذف">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <button class="btn btn-sm btn-primary" onclick="viewSpecializationDetails(<?= htmlspecialchars(json_encode($spec)) ?>)"
                                        data-bs-toggle="tooltip" title="عرض التفاصيل">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Specialization Modal -->
    <div class="modal fade" id="addSpecializationModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-plus-circle ms-2"></i>إضافة تخصص جديد
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="save_specialization.php" method="POST" id="addSpecializationForm">
                    <div class="modal-body">
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-tag ms-3"></i>بيانات التخصص
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-building ms-2"></i>الكلية
                                        </label>
                                        <select class="form-select" name="college_id" id="modal_college_id" required
                                            onchange="loadModalSections()"
                                            <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                                            <option value="">اختر الكلية</option>
                                            <?php foreach ($colleges as $college): ?>
                                                <option value="<?= e($college['id'] ?? '') ?>">
                                                    <?= e($college['name'] ?? '') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if (!$canAll && $scopeCollege !== null): ?>
                                            <input type="hidden" name="college_id" value="<?= e($scopeCollege) ?>">
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-graduation-cap ms-2"></i>البرنامج
                                        </label>
                                        <select class="form-select" name="program_id" required>
                                            <option value="">اختر البرنامج</option>
                                            <?php foreach ($programs as $program): ?>
                                                <option value="<?= e($program['id'] ?? '') ?>">
                                                    <?= e($program['name'] ?? '') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-tag ms-2"></i>اسم التخصص (عربي)
                                        </label>
                                        <input type="text" class="form-control" name="specialization_name_ar" required
                                               placeholder="أدخل اسم التخصص بالعربية">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-tag ms-2"></i>اسم التخصص (إنجليزي)
                                        </label>
                                        <input type="text" class="form-control" name="specialization_name_en" required
                                               placeholder="Enter specialization name in English" dir="ltr">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-building ms-2"></i>القسم
                                        </label>
                                        <select class="form-select" name="section_id" id="modal_section_id" required>
                                            <option value="">اختر القسم</option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-certificate ms-2"></i>الدرجة الممنوحة (عربي)
                                        </label>
                                        <input type="text" class="form-control" name="degree_awarded_ar"
                                               placeholder="مثال: بكالوريوس العلوم">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-certificate ms-2"></i>الدرجة الممنوحة (إنجليزي)
                                        </label>
                                        <input type="text" class="form-control" name="degree_awarded_en"
                                               placeholder="e.g., Bachelor of Science" dir="ltr">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save ms-2"></i>حفظ التخصص
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Specialization Modal -->
    <div class="modal fade" id="editSpecializationModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <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="update_specialization.php" method="POST" id="editSpecializationForm">
                    <input type="hidden" name="specialization_id" id="edit_specialization_id">
                    <div class="modal-body">
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-tag ms-3"></i>بيانات التخصص
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-building ms-2"></i>الكلية
                                        </label>
                                        <select class="form-select" name="college_id" id="edit_college_id" required
                                            onchange="loadEditSections()">
                                            <option value="">اختر الكلية</option>
                                            <?php foreach ($colleges as $college): ?>
                                                <option value="<?= e($college['id'] ?? '') ?>">
                                                    <?= e($college['name'] ?? '') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-graduation-cap ms-2"></i>البرنامج
                                        </label>
                                        <select class="form-select" name="program_id" id="edit_program_id" required>
                                            <option value="">اختر البرنامج</option>
                                            <?php foreach ($programs as $program): ?>
                                                <option value="<?= e($program['id'] ?? '') ?>">
                                                    <?= e($program['name'] ?? '') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-tag ms-2"></i>اسم التخصص (عربي)
                                        </label>
                                        <input type="text" class="form-control" name="specialization_name_ar" 
                                               id="edit_name_ar" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-tag ms-2"></i>اسم التخصص (إنجليزي)
                                        </label>
                                        <input type="text" class="form-control" name="specialization_name_en" 
                                               id="edit_name_en" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label required">
                                            <i class="fas fa-building ms-2"></i>القسم
                                        </label>
                                        <select class="form-select" name="section_id" id="edit_section_id" required>
                                            <option value="">اختر القسم</option>
                                        </select>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-certificate ms-2"></i>الدرجة الممنوحة (عربي)
                                        </label>
                                        <input type="text" class="form-control" name="degree_awarded_ar" 
                                               id="edit_degree_ar">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-certificate ms-2"></i>الدرجة الممنوحة (إنجليزي)
                                        </label>
                                        <input type="text" class="form-control" name="degree_awarded_en" 
                                               id="edit_degree_en">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save ms-2"></i>تحديث التخصص
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- View Details Modal -->
    <div class="modal fade" id="viewDetailsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <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="40%">المعرف:</th>
                            <td id="detail_id"></td>
                        </tr>
                        <tr>
                            <th>التخصص (عربي):</th>
                            <td id="detail_name_ar"></td>
                        </tr>
                        <tr>
                            <th>التخصص (إنجليزي):</th>
                            <td id="detail_name_en"></td>
                        </tr>
                        <tr>
                            <th>الكلية:</th>
                            <td id="detail_college"></td>
                        </tr>
                        <tr>
                            <th>القسم:</th>
                            <td id="detail_section"></td>
                        </tr>
                        <tr>
                            <th>البرنامج:</th>
                            <td id="detail_program"></td>
                        </tr>
                        <tr>
                            <th>الدرجة الممنوحة (عربي):</th>
                            <td id="detail_degree_ar"></td>
                        </tr>
                        <tr>
                            <th>الدرجة الممنوحة (إنجليزي):</th>
                            <td id="detail_degree_en"></td>
                        </tr>
                        <tr>
                            <th>تاريخ الإضافة:</th>
                            <td id="detail_created"></td>
                        </tr>
                        <tr>
                            <th>آخر تحديث:</th>
                            <td id="detail_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>

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

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap5.min.js"></script>
    
    <script>
        // تخزين جميع الأقسام
        const allSections = <?= json_encode($sections) ?>;
        
        // تهيئة DataTable
        $(document).ready(function() {
            $('#specializationsTable').DataTable({
                language: {
                    url: '//cdn.datatables.net/plug-ins/1.13.4/i18n/ar.json'
                },
                order: [[0, 'desc']],
                responsive: true,
                pageLength: 25,
                columnDefs: [
                    { orderable: false, targets: 9 } // منع ترتيب عمود الإجراءات
                ]
            });
            
            // تهيئة التلميحات
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });

        // دالة تحميل الأقسام في النافذة المنبثقة للإضافة
        function loadModalSections() {
            const collegeId = document.getElementById('modal_college_id').value;
            const sectionSelect = document.getElementById('modal_section_id');
            
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            
            setTimeout(() => {
                const filteredSections = allSections.filter(section => section.parent == collegeId);
                
                if (filteredSections.length === 0) {
                    sectionSelect.innerHTML = '<option value="">لا توجد أقسام لهذه الكلية</option>';
                    return;
                }
                
                sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
                filteredSections.forEach(section => {
                    const option = document.createElement('option');
                    option.value = section.id;
                    option.textContent = section.name;
                    sectionSelect.appendChild(option);
                });
            }, 300);
        }

        // دالة تحميل الأقسام في نافذة التعديل
        function loadEditSections() {
            const collegeId = document.getElementById('edit_college_id').value;
            const sectionSelect = document.getElementById('edit_section_id');
            
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            
            setTimeout(() => {
                const filteredSections = allSections.filter(section => section.parent == collegeId);
                
                if (filteredSections.length === 0) {
                    sectionSelect.innerHTML = '<option value="">لا توجد أقسام لهذه الكلية</option>';
                    return;
                }
                
                sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
                filteredSections.forEach(section => {
                    const option = document.createElement('option');
                    option.value = section.id;
                    option.textContent = section.name;
                    sectionSelect.appendChild(option);
                });
            }, 300);
        }

        // دالة التعديل
        function editSpecialization(spec) {
            document.getElementById('edit_specialization_id').value = spec.specialization_id;
            document.getElementById('edit_college_id').value = spec.college_id;
            document.getElementById('edit_program_id').value = spec.program_id;
            document.getElementById('edit_name_ar').value = spec.specialization_name_ar;
            document.getElementById('edit_name_en').value = spec.specialization_name_en;
            document.getElementById('edit_degree_ar').value = spec.degree_awarded_ar || '';
            document.getElementById('edit_degree_en').value = spec.degree_awarded_en || '';
            
            // تحميل الأقسام ثم تحديد القسم
            loadEditSections();
            setTimeout(() => {
                document.getElementById('edit_section_id').value = spec.section_id;
            }, 500);
            
            // فتح النافذة المنبثقة
            new bootstrap.Modal(document.getElementById('editSpecializationModal')).show();
        }

        // دالة الحذف
        function deleteSpecialization(id, name) {
            document.getElementById('delete_id').value = id;
            document.getElementById('delete_item_name').textContent = name;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // دالة عرض التفاصيل
        function viewSpecializationDetails(spec) {
            document.getElementById('detail_id').textContent = spec.specialization_id;
            document.getElementById('detail_name_ar').textContent = spec.specialization_name_ar;
            document.getElementById('detail_name_en').textContent = spec.specialization_name_en;
            document.getElementById('detail_college').textContent = spec.college_name || 'غير محدد';
            document.getElementById('detail_section').textContent = spec.section_name || 'غير محدد';
            document.getElementById('detail_program').textContent = spec.program_name || 'غير محدد';
            document.getElementById('detail_degree_ar').textContent = spec.degree_awarded_ar || '-';
            document.getElementById('detail_degree_en').textContent = spec.degree_awarded_en || '-';
            document.getElementById('detail_created').textContent = spec.created_at ? new Date(spec.created_at).toLocaleString('ar-EG') : '-';
            document.getElementById('detail_updated').textContent = spec.updated_at ? new Date(spec.updated_at).toLocaleString('ar-EG') : '-';
            
            new bootstrap.Modal(document.getElementById('viewDetailsModal')).show();
        }

        // التحقق من صحة النموذج قبل الإرسال
        document.getElementById('addSpecializationForm')?.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('editSpecializationForm')?.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.addEventListener('DOMContentLoaded', function() {
            const collegeSelect = document.getElementById('modal_college_id');
            if (collegeSelect && collegeSelect.value && !collegeSelect.disabled) {
                loadModalSections();
            }
        });
    </script>
</body>
</html>
