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

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

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

// التحقق من صلاحيات اللجنة إذا لزم الأمر
// 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;

// معالجة الطلبات (إضافة، تعديل، حذف)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add') {
        $name = $_POST['name'];
        $email = $_POST['email'] ?: null;
        $phone = $_POST['phone'] ?: null;
        $college_id = $_POST['college_id'];
        $section_id = $_POST['section_id'];
        
        $stmt = $mysqli1->prepare("INSERT INTO instructors (name, email, phone, college_id, section_id) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param('sssii', $name, $email, $phone, $college_id, $section_id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "تم إضافة الأستاذ بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء الإضافة: " . $stmt->error;
        }
        $stmt->close();
        
        header("Location: instructors.php");
        exit;
    }
    
    elseif ($action == 'edit') {
        $id = $_POST['id'];
        $name = $_POST['name'];
        $email = $_POST['email'] ?: null;
        $phone = $_POST['phone'] ?: null;
        $college_id = $_POST['college_id'];
        $section_id = $_POST['section_id'];
        
        $stmt = $mysqli1->prepare("UPDATE instructors SET name=?, email=?, phone=?, college_id=?, section_id=? WHERE id=?");
        $stmt->bind_param('sssiii', $name, $email, $phone, $college_id, $section_id, $id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "تم تحديث بيانات الأستاذ بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء التحديث: " . $stmt->error;
        }
        $stmt->close();
        
        header("Location: instructors.php");
        exit;
    }
    
    elseif ($action == 'delete') {
        $id = $_POST['id'];
        
        // Soft delete
        $stmt = $mysqli1->prepare("UPDATE instructors SET deleted_at = NOW() WHERE id=?");
        $stmt->bind_param('i', $id);
        
        if ($stmt->execute()) {
            $_SESSION['success_message'] = "تم حذف الأستاذ بنجاح";
        } else {
            $_SESSION['error_message'] = "حدث خطأ أثناء الحذف: " . $stmt->error;
        }
        $stmt->close();
        
        header("Location: instructors.php");
        exit;
    }
}

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

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

// جلب بيانات الأساتذة مع معلومات الكلية والقسم
$teachers = [];
$teachers_query = "
    SELECT i.*, 
           c.name as college_name,
           s.name as department_name
    FROM instructors i
    LEFT JOIN colleges c ON i.college_id = c.id
    LEFT JOIN sections s ON i.section_id = s.id
    WHERE i.deleted_at IS NULL
    ORDER BY i.created_at DESC
";
$teachers_result = $mysqli1->query($teachers_query);
if ($teachers_result) {
    $teachers = $teachers_result->fetch_all(MYSQLI_ASSOC);
}

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

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الأساتذة - نظام القبول والتسجيل</title>
    
    <!-- Bootstrap 5 RTL -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.bootstrap5.min.css">
    <!-- 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;
        }
        
        .required::after {
            content: " *";
            color: #dc3545;
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 30px 0;
            margin-bottom: 30px;
            border-radius: 0 0 30px 30px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }
        
        .card-custom {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
            transition: transform 0.2s;
        }
        
        .card-custom:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,.1);
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
            transition: transform 0.3s;
        }
        
        .stats-card:hover {
            transform: translateY(-5px);
        }
        
        .stats-card .icon {
            font-size: 3rem;
            opacity: 0.5;
        }
        
        .stats-card.green {
            background: linear-gradient(135deg, #10b981, #047857);
        }
        
        .stats-card.orange {
            background: linear-gradient(135deg, #f59e0b, #b45309);
        }
        
        .badge-college {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-department {
            background: linear-gradient(135deg, #10b981, #047857);
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-email {
            background-color: #e3f2fd;
            color: #0d47a1;
            padding: 3px 10px;
            border-radius: 15px;
            font-size: 0.85rem;
            display: inline-block;
            direction: ltr;
        }
        
        .badge-phone {
            background-color: #e8f5e8;
            color: #1b5e20;
            padding: 3px 10px;
            border-radius: 15px;
            font-size: 0.85rem;
            display: inline-block;
            direction: ltr;
        }
        
        .btn-actions {
            white-space: nowrap;
        }
        
        .btn-actions .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            margin: 0 2px;
            border-radius: 8px;
            transition: all 0.2s;
        }
        
        .btn-actions .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 10px rgba(0,0,0,0.1);
        }
        
        .btn-actions .btn-edit {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
            border: none;
        }
        
        .btn-actions .btn-delete {
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: white;
            border: none;
        }
        
        .btn-actions .btn-view {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
            border: none;
        }
        
        .modal-content {
            border-radius: 20px;
            border: none;
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border-radius: 20px 20px 0 0;
            padding: 20px;
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-header.bg-warning {
            background: linear-gradient(135deg, #f59e0b, #d97706) !important;
        }
        
        .modal-header.bg-danger {
            background: linear-gradient(135deg, #ef4444, #dc2626) !important;
        }
        
        .modal-header.bg-info {
            background: linear-gradient(135deg, #3b82f6, #2563eb) !important;
        }
        
        .form-section {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }
        
        .section-title {
            color: #2c3e50;
            font-weight: 700;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }
        
        .form-label {
            font-weight: 600;
            color: #4a5568;
            margin-bottom: 8px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 10px 15px;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-primary-custom {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-weight: 600;
            color: white;
        }
        
        .btn-primary-custom:hover {
            background: linear-gradient(135deg, #5a67d8, #6b46a0);
            color: white;
        }
        
        .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;
        }
        
        .table > :not(caption) > * > * {
            padding: 1rem 0.75rem;
            vertical-align: middle;
        }
        
        .table-hover tbody tr:hover {
            background-color: rgba(102, 126, 234, 0.05);
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #a0aec0;
        }
        
        .empty-state i {
            font-size: 5rem;
            margin-bottom: 20px;
        }
    </style>
</head>
<body class="bg-light" dir="rtl">
    <!-- رأس الصفحة -->
    <div class="page-header">
        <div class="container">
            <div class="d-flex align-items-center justify-content-between">
                <div>
                    <h2 class="mb-2"><i class="fas fa-chalkboard-teacher me-2"></i> إدارة الأساتذة</h2>
                    <p class="mb-0 opacity-75"><i class="fas fa-chevron-left me-2"></i> عرض وإدارة بيانات أعضاء هيئة التدريس والمحاضرين</p>
                </div>
                <a href="admin_dashboard.php" class="btn btn-light rounded-pill px-4">
                    <i class="fas fa-arrow-right me-2"></i> العودة
                </a>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- رسائل التنبيه -->
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle ms-2"></i>
                <?= 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 mb-4">
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-2">إجمالي الأساتذة</h6>
                            <h2 class="mb-0"><?= count($teachers) ?></h2>
                            <small class="opacity-75">أستاذ/محاضر</small>
                        </div>
                        <i class="fas fa-chalkboard-teacher icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card green">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-2">الكليات</h6>
                            <h2 class="mb-0"><?= count($colleges) ?></h2>
                            <small class="opacity-75">كلية</small>
                        </div>
                        <i class="fas fa-university icon"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card orange">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="mb-2">الأقسام</h6>
                            <h2 class="mb-0"><?= count($sections) ?></h2>
                            <small class="opacity-75">قسم</small>
                        </div>
                        <i class="fas fa-layer-group icon"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- بطاقة الجدول الرئيسي -->
        <div class="card card-custom p-3">
            <div class="card-header bg-transparent border-0 d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-list-ul ms-2 text-primary"></i>
                    قائمة الأساتذة
                </h5>
                <button type="button" class="btn btn-primary-custom rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#addInstructorModal">
                    <i class="fas fa-plus-circle ms-2"></i> إضافة أستاذ جديد
                </button>
            </div>
            <div class="card-body">
                <?php if (empty($teachers)): ?>
                    <div class="empty-state">
                        <i class="fas fa-chalkboard-teacher text-muted"></i>
                        <h5>لا يوجد أساتذة مضافة</h5>
                        <p class="text-muted">قم بإضافة أول أستاذ من خلال الضغط على زر الإضافة</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table id="instructorsTable" 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>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($teachers as $index => $teacher): ?>
                                <tr>
                                    <td class="fw-bold"><?= $index + 1 ?></td>
                                    <td>
                                        <div class="fw-bold"><?= e($teacher['name']) ?></div>
                                    </td>
                                    <td>
                                        <?php if ($teacher['email']): ?>
                                            <span class="badge-email">
                                                <i class="fas fa-envelope ms-1"></i>
                                                <?= e($teacher['email']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($teacher['phone']): ?>
                                            <span class="badge-phone">
                                                <i class="fas fa-phone ms-1"></i>
                                                <?= e($teacher['phone']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($teacher['college_name']): ?>
                                            <span class="badge-college">
                                                <i class="fas fa-university ms-1"></i>
                                                <?= e($teacher['college_name']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($teacher['department_name']): ?>
                                            <span class="badge-department">
                                                <i class="fas fa-building ms-1"></i>
                                                <?= e($teacher['department_name']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-calendar-alt text-primary ms-2"></i>
                                            <?= date('Y-m-d', strtotime($teacher['created_at'])) ?>
                                        </div>
                                    </td>
                                    <td class="btn-actions">
                                        <button class="btn btn-view" onclick="viewInstructor(<?= htmlspecialchars(json_encode($teacher)) ?>)" 
                                                data-bs-toggle="tooltip" title="عرض التفاصيل">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button class="btn btn-edit" onclick="editInstructor(<?= htmlspecialchars(json_encode($teacher)) ?>)" 
                                                data-bs-toggle="tooltip" title="تعديل">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-delete" onclick="deleteInstructor(<?= $teacher['id'] ?>, '<?= e($teacher['name']) ?>')"
                                                data-bs-toggle="tooltip" title="حذف">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Modal إضافة أستاذ جديد -->
    <div class="modal fade" id="addInstructorModal" 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="instructors.php" method="POST" id="addInstructorForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="add">
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-user ms-2"></i> البيانات الشخصية
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-user ms-2"></i> الاسم الكامل
                                    </label>
                                    <input type="text" name="name" class="form-control" required 
                                           placeholder="أدخل الاسم الرباعي">
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-envelope ms-2"></i> البريد الإلكتروني
                                    </label>
                                    <input type="email" name="email" class="form-control" dir="ltr"
                                           placeholder="example@domain.com">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-phone ms-2"></i> رقم الهاتف
                                    </label>
                                    <input type="tel" name="phone" class="form-control" dir="ltr"
                                           placeholder="05xxxxxxxx">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-building ms-2"></i> المعلومات الأكاديمية
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-university ms-2"></i> الكلية
                                    </label>
                                    <select class="form-select" name="college_id" required 
                                            onchange="loadAddSections(this.value)"
                                            <?= (!$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="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-building ms-2"></i> القسم
                                    </label>
                                    <select class="form-select" name="section_id" id="add_section_id" required>
                                        <option value="">اختر القسم</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                            <i class="fas fa-times ms-2"></i> إلغاء
                        </button>
                        <button type="submit" class="btn btn-primary-custom">
                            <i class="fas fa-save ms-2"></i> حفظ البيانات
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal تعديل أستاذ -->
    <div class="modal fade" id="editInstructorModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title">
                        <i class="fas fa-edit ms-2"></i> تعديل بيانات الأستاذ
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="instructors.php" method="POST" id="editInstructorForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="edit">
                        <input type="hidden" name="id" id="edit_id">
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-user ms-2"></i> البيانات الشخصية
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-user ms-2"></i> الاسم الكامل
                                    </label>
                                    <input type="text" name="name" id="edit_name" class="form-control" required>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-envelope ms-2"></i> البريد الإلكتروني
                                    </label>
                                    <input type="email" name="email" id="edit_email" class="form-control" dir="ltr">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-phone ms-2"></i> رقم الهاتف
                                    </label>
                                    <input type="tel" name="phone" id="edit_phone" class="form-control" dir="ltr">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-building ms-2"></i> المعلومات الأكاديمية
                            </h5>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">
                                        <i class="fas fa-university ms-2"></i> الكلية
                                    </label>
                                    <select class="form-select" name="college_id" id="edit_college_id" required 
                                            onchange="loadEditSections(this.value)">
                                        <option value="">اختر الكلية</option>
                                        <?php foreach ($colleges as $college): ?>
                                            <option value="<?= e($college['id'] ?? '') ?>">
                                                <?= e($college['name'] ?? '') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-6 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>
                        </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="viewInstructorModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-info">
                    <h5 class="modal-title">
                        <i class="fas fa-info-circle ms-2"></i> تفاصيل الأستاذ
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <table class="table table-bordered">
                        <tr>
                            <th width="35%">المعرف:</th>
                            <td id="view_id"></td>
                        </tr>
                        <tr>
                            <th>الاسم الكامل:</th>
                            <td id="view_name"></td>
                        </tr>
                        <tr>
                            <th>البريد الإلكتروني:</th>
                            <td id="view_email"></td>
                        </tr>
                        <tr>
                            <th>رقم الهاتف:</th>
                            <td id="view_phone"></td>
                        </tr>
                        <tr>
                            <th>الكلية:</th>
                            <td id="view_college"></td>
                        </tr>
                        <tr>
                            <th>القسم:</th>
                            <td id="view_department"></td>
                        </tr>
                        <tr>
                            <th>تاريخ الإضافة:</th>
                            <td id="view_created"></td>
                        </tr>
                        <tr>
                            <th>آخر تحديث:</th>
                            <td id="view_updated"></td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times ms-2"></i> إغلاق
                    </button>
                </div>
            </div>
        </div>
    </div>

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

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap5.min.js"></script>

    <script>
        // تخزين جميع الأقسام
        const allSections = <?= json_encode($sections) ?>;
        
        // تهيئة DataTable
        $(document).ready(function() {
            $('#instructorsTable').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: 7 } // منع ترتيب عمود الإجراءات
                ]
            });
            
            // تهيئة التلميحات
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });

        // دالة تحميل الأقسام في نافذة الإضافة
        function loadAddSections(collegeId) {
            const sectionSelect = document.getElementById('add_section_id');
            
            if (!collegeId) {
                sectionSelect.innerHTML = '<option value="">اختر القسم أولاً</option>';
                sectionSelect.disabled = true;
                return;
            }
            
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            sectionSelect.disabled = true;
            
            // محاكاة تأخير بسيط (يمكن إزالة setTimeout إذا كان الأداء جيداً)
            setTimeout(() => {
                const filteredSections = allSections.filter(section => section.parent == collegeId);
                
                if (filteredSections.length === 0) {
                    sectionSelect.innerHTML = '<option value="">لا توجد أقسام لهذه الكلية</option>';
                    sectionSelect.disabled = true;
                    return;
                }
                
                let options = '<option value="">اختر القسم</option>';
                filteredSections.forEach(section => {
                    options += `<option value="${section.id}">${section.name}</option>`;
                });
                
                sectionSelect.innerHTML = options;
                sectionSelect.disabled = false;
            }, 300);
        }

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

        // دالة التعديل
        function editInstructor(instructor) {
            document.getElementById('edit_id').value = instructor.id;
            document.getElementById('edit_name').value = instructor.name;
            document.getElementById('edit_email').value = instructor.email || '';
            document.getElementById('edit_phone').value = instructor.phone || '';
            document.getElementById('edit_college_id').value = instructor.college_id;
            
            // تحميل الأقسام ثم تحديد القسم
            loadEditSections(instructor.college_id);
            
            // تأخير بسيط لضمان تحميل الأقسام ثم تحديد القسم
            setTimeout(() => {
                document.getElementById('edit_section_id').value = instructor.section_id;
            }, 500);
            
            // فتح النافذة المنبثقة
            new bootstrap.Modal(document.getElementById('editInstructorModal')).show();
        }

        // دالة عرض التفاصيل
        function viewInstructor(instructor) {
            document.getElementById('view_id').textContent = instructor.id;
            document.getElementById('view_name').textContent = instructor.name;
            document.getElementById('view_email').textContent = instructor.email || '-';
            document.getElementById('view_phone').textContent = instructor.phone || '-';
            document.getElementById('view_college').textContent = instructor.college_name || 'غير محدد';
            document.getElementById('view_department').textContent = instructor.department_name || 'غير محدد';
            
            // تنسيق التاريخ
            const createdDate = instructor.created_at ? new Date(instructor.created_at).toLocaleString('ar-EG') : '-';
            const updatedDate = instructor.updated_at ? new Date(instructor.updated_at).toLocaleString('ar-EG') : '-';
            
            document.getElementById('view_created').textContent = createdDate;
            document.getElementById('view_updated').textContent = updatedDate;
            
            new bootstrap.Modal(document.getElementById('viewInstructorModal')).show();
        }

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

        // التحقق من صحة النموذج قبل الإرسال
        document.getElementById('addInstructorForm')?.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('editInstructorForm')?.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) {
                loadAddSections(collegeSelect.value);
            }
        });
    </script>
</body>
</html>
