<?php
// sections.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

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

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Regenerate CSRF token periodically (every 30 minutes)
if (!isset($_SESSION['csrf_token_time']) || time() - $_SESSION['csrf_token_time'] > 1800) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    $_SESSION['csrf_token_time'] = time();
}

$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 for colleges (for filtering)
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if (!$colleges_stmt) {
    error_log("Prepare failed: " . $mysqli1->error);
    die("Database error");
}
$colleges_stmt->execute();
$colleges_result = $colleges_stmt->get_result();
$colleges = [];
while ($row = $colleges_result->fetch_assoc()) {
    $colleges[] = $row;
}
$colleges_stmt->close();

// Get existing sections with college information
if (!$canAll && $scopeCollege !== null) {
    // Committee restricted to specific college
    $sections_stmt = $mysqli1->prepare("
        SELECT s.*, c.name as college_name 
        FROM sections s
        LEFT JOIN colleges c ON s.parent = c.id
        WHERE s.deleted_at IS NULL 
        AND s.parent = ?
        ORDER BY s.id DESC
    ");
    if (!$sections_stmt) {
        error_log("Prepare failed: " . $mysqli1->error);
        die("Database error");
    }
    $sections_stmt->bind_param("i", $scopeCollege);
} else {
    // Committee with full access
    $sections_stmt = $mysqli1->prepare("
        SELECT s.*, c.name as college_name 
        FROM sections s
        LEFT JOIN colleges c ON s.parent = c.id
        WHERE s.deleted_at IS NULL 
        ORDER BY s.id DESC
    ");
    if (!$sections_stmt) {
        error_log("Prepare failed: " . $mysqli1->error);
        die("Database error");
    }
}
$sections_stmt->execute();
$sections_result = $sections_stmt->get_result();
$sections = [];
while ($row = $sections_result->fetch_assoc()) {
    // Sanitize output data
    $row['name'] = htmlspecialchars($row['name'] ?? '', ENT_QUOTES, 'UTF-8');
    $row['DepartmentNameE'] = htmlspecialchars($row['DepartmentNameE'] ?? '', ENT_QUOTES, 'UTF-8');
    $row['college_name'] = htmlspecialchars($row['college_name'] ?? '', ENT_QUOTES, 'UTF-8');
    $sections[] = $row;
}
$sections_stmt->close();

// If committee has restricted access, filter colleges list
if (!$canAll && $scopeCollege !== null) {
    $filtered_colleges = [];
    foreach ($colleges as $college) {
        if ($college['id'] == $scopeCollege) {
            $filtered_colleges[] = $college;
        }
    }
    $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">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
    <meta name="committee-can-all" content="<?= $canAll ? 'true' : 'false' ?>">
    <meta name="committee-scope" content="<?= (int)$scopeCollege ?>">
    <title>إدارة الأقسام - لوحة اللجنة</title>
    
    <!-- Bootstrap 5 RTL -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
    <!-- Bootstrap RTL -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" integrity="sha384-Tk7g9I5M8N2oqb5hQEqh6dSGfrC9I6IqYVr/mS8Q42BDgL8F4LRTkF4j8/7HojL" crossorigin="anonymous">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer">
    <!-- 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">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.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', system-ui, -apple-system, sans-serif !important;
            text-align: right !important;
        }
        
        .form-control, .form-select {
            text-align: right;
            direction: rtl;
        }
        
        .form-control[ltr], .form-select[ltr], [dir="ltr"] {
            text-align: left;
            direction: ltr;
        }
        
        .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;
        }
        
        .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 #3498db;
        }
        
        .badge-college {
            background-color: #e3f2fd;
            color: #0d47a1;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-active {
            background-color: #e8f5e8;
            color: #1b5e20;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .badge-inactive {
            background-color: #ffebee;
            color: #b71c1c;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            display: inline-block;
        }
        
        .table-actions {
            white-space: nowrap;
        }
        
        .table-actions .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            margin: 0 2px;
        }
        
        .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;
        }
        
        .info-label {
            font-weight: 600;
            color: #2c3e50;
            background-color: #f8f9fa;
            padding: 8px;
            border-radius: 8px;
            margin-bottom: 5px;
        }
        
        .info-value {
            padding: 8px;
            border-bottom: 1px solid #e9ecef;
            margin-bottom: 5px;
        }
        
        .info-value:last-child {
            border-bottom: none;
        }
        
        /* Loading spinner */
        .spinner-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            z-index: 9999;
            display: none;
            justify-content: center;
            align-items: center;
        }
        
        .spinner-overlay.show {
            display: flex;
        }
    </style>
</head>
<body class="bg-light" dir="rtl">
    <!-- Loading Spinner -->
    <div class="spinner-overlay" id="loadingSpinner">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">جاري التحميل...</span>
        </div>
    </div>

    <div class="container py-4" dir="rtl">
        <!-- Header -->
        <div class="d-flex flex-wrap align-items-center mb-4">
            <h3 class="mb-0 fw-bold text-dark">
                <i class="fas fa-building ms-2"></i>إدارة الأقسام
            </h3>
            <div class="me-auto mt-2 mt-sm-0">
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addSectionModal">
                    <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>
                <?= htmlspecialchars($_SESSION['success_message'], ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle ms-2"></i>
                <?= htmlspecialchars($_SESSION['error_message'], ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Sections Table -->
        <div class="card card-arabic p-3">
            <div class="table-responsive">
                <table id="sectionsTable" 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>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($sections as $section): ?>
                        <tr>
                            <td><?= (int)$section['id'] ?></td>
                            <td><?= htmlspecialchars($section['name'] ?? '-', ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($section['DepartmentNameE'] ?? '-', ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <span class="badge-college">
                                    <i class="fas fa-university ms-1"></i>
                                    <?= htmlspecialchars($section['college_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            </td>
                            <td><?= $section['created_at'] ? date('Y-m-d', strtotime($section['created_at'])) : '-' ?></td>
                            <td>
                                <?php if ($section['deleted_at'] === null): ?>
                                    <span class="badge-active">
                                        <i class="fas fa-check-circle ms-1"></i>نشط
                                    </span>
                                <?php else: ?>
                                    <span class="badge-inactive">
                                        <i class="fas fa-times-circle ms-1"></i>محذوف
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="table-actions">
                                <button class="btn btn-sm btn-info" onclick='editSection(<?= json_encode($section, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>)' 
                                        data-bs-toggle="tooltip" title="تعديل">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteSection(<?= (int)$section['id'] ?>, '<?= htmlspecialchars(addslashes($section['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>')"
                                        data-bs-toggle="tooltip" title="حذف">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <button class="btn btn-sm btn-primary" onclick='viewSectionDetails(<?= json_encode($section, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>)'
                                        data-bs-toggle="tooltip" title="عرض التفاصيل">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add Section Modal -->
    <div class="modal fade" id="addSectionModal" 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 id="addSectionForm" class="needs-validation" novalidate>
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                    <div class="modal-body">
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-building 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-university ms-2"></i>الكلية التابع لها
                                        </label>
                                        <select class="form-select" name="parent" id="add_parent" required
                                            <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                                            <option value="">اختر الكلية</option>
                                            <?php foreach ($colleges as $college): ?>
                                                <option value="<?= (int)($college['id'] ?? 0) ?>" 
                                                    <?= (!$canAll && $scopeCollege !== null && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($college['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if (!$canAll && $scopeCollege !== null): ?>
                                            <input type="hidden" name="parent" value="<?= (int)$scopeCollege ?>">
                                        <?php endif; ?>
                                        <div class="invalid-feedback">
                                            الرجاء اختيار الكلية
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <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="name" required
                                               placeholder="أدخل اسم القسم بالعربية"
                                               minlength="2" maxlength="191"
                                               pattern="[\s\S]{2,191}">
                                        <div class="invalid-feedback">
                                            الرجاء إدخال اسم القسم (2-191 حرف)
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-tag ms-2"></i>اسم القسم (إنجليزي)
                                        </label>
                                        <input type="text" class="form-control" name="DepartmentNameE"
                                               placeholder="Enter department name in English"
                                               maxlength="191" 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" id="btnSave">
                            <i class="fas fa-save ms-2"></i>حفظ القسم
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Section Modal -->
    <div class="modal fade" id="editSectionModal" 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 id="editSectionForm" class="needs-validation" novalidate>
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="modal-body">
                        <div class="form-section">
                            <h5 class="section-title">
                                <i class="fas fa-building 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-university ms-2"></i>الكلية التابع لها
                                        </label>
                                        <select class="form-select" name="parent" id="edit_parent" required>
                                            <option value="">اختر الكلية</option>
                                            <?php foreach ($colleges as $college): ?>
                                                <option value="<?= (int)($college['id'] ?? 0) ?>">
                                                    <?= htmlspecialchars($college['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="invalid-feedback">
                                            الرجاء اختيار الكلية
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <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="name" id="edit_name" required
                                               minlength="2" maxlength="191"
                                               pattern="[\s\S]{2,191}">
                                        <div class="invalid-feedback">
                                            الرجاء إدخال اسم القسم (2-191 حرف)
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <i class="fas fa-tag ms-2"></i>اسم القسم (إنجليزي)
                                        </label>
                                        <input type="text" class="form-control" name="DepartmentNameE" id="edit_name_en" 
                                               maxlength="191" 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-primary" id="btnUpdate">
                            <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">
                    <div class="info-label">المعرف:</div>
                    <div class="info-value" id="detail_id"></div>
                    
                    <div class="info-label">اسم القسم (عربي):</div>
                    <div class="info-value" id="detail_name"></div>
                    
                    <div class="info-label">اسم القسم (إنجليزي):</div>
                    <div class="info-value" id="detail_name_en"></div>
                    
                    <div class="info-label">الكلية التابع لها:</div>
                    <div class="info-value" id="detail_college"></div>
                    
                    <div class="info-label">تاريخ الإضافة:</div>
                    <div class="info-value" id="detail_created"></div>
                    
                    <div class="info-label">آخر تحديث:</div>
                    <div class="info-value" id="detail_updated"></div>
                    
                    <div class="info-label">الحالة:</div>
                    <div class="info-value" id="detail_status"></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>
                </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 id="deleteForm">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="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" id="btnDelete">
                            <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" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    
    <script>
        // تهيئة DataTable
        $(document).ready(function() {
            $('#sectionsTable').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: 6 } // منع ترتيب عمود الإجراءات
                ]
            });
            
            // تهيئة التلميحات
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            
            // تفعيل التحقق من النماذج
            const forms = document.querySelectorAll('.needs-validation');
            Array.from(forms).forEach(form => {
                form.addEventListener('submit', event => {
                    if (!form.checkValidity()) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                }, false);
            });
        });

        // إظهار/إخفاء مؤشر التحميل
        function showLoading() {
            document.getElementById('loadingSpinner').classList.add('show');
        }
        
        function hideLoading() {
            document.getElementById('loadingSpinner').classList.remove('show');
        }

        // دالة التعديل
        function editSection(section) {
            try {
                document.getElementById('edit_id').value = section.id || '';
                document.getElementById('edit_parent').value = section.parent || '';
                document.getElementById('edit_name').value = section.name || '';
                document.getElementById('edit_name_en').value = section.DepartmentNameE || '';
                
                // فتح النافذة المنبثقة
                new bootstrap.Modal(document.getElementById('editSectionModal')).show();
            } catch (error) {
                console.error('Error in editSection:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ',
                    text: 'حدث خطأ في تحميل بيانات القسم',
                    confirmButtonText: 'حسناً'
                });
            }
        }

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

        // دالة عرض التفاصيل
        function viewSectionDetails(section) {
            try {
                document.getElementById('detail_id').textContent = section.id || '-';
                document.getElementById('detail_name').textContent = section.name || '-';
                document.getElementById('detail_name_en').textContent = section.DepartmentNameE || '-';
                document.getElementById('detail_college').textContent = section.college_name || 'غير محدد';
                document.getElementById('detail_created').textContent = section.created_at ? new Date(section.created_at).toLocaleString('ar-EG') : '-';
                document.getElementById('detail_updated').textContent = section.updated_at ? new Date(section.updated_at).toLocaleString('ar-EG') : '-';
                document.getElementById('detail_status').textContent = section.deleted_at ? 'محذوف' : 'نشط';
                
                new bootstrap.Modal(document.getElementById('viewDetailsModal')).show();
            } catch (error) {
                console.error('Error in viewSectionDetails:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ',
                    text: 'حدث خطأ في عرض التفاصيل',
                    confirmButtonText: 'حسناً'
                });
            }
        }

        // معالجة إرسال نموذج الإضافة
        document.getElementById('addSectionForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!this.checkValidity()) {
                this.classList.add('was-validated');
                return;
            }
            
            const btn = document.getElementById('btnSave');
            if (btn.disabled) return;
            
            btn.disabled = true;
            showLoading();
            
            const formData = new FormData(this);
            
            fetch('save_section.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                hideLoading();
                btn.disabled = false;
                
                // إخفاء المودال
                bootstrap.Modal.getInstance(document.getElementById('addSectionModal')).hide();
                
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'تم بنجاح',
                        text: data.message,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        // إعادة تحميل الصفحة لعرض القسم الجديد
                        window.location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'خطأ',
                        text: data.message,
                        confirmButtonText: 'حسناً'
                    });
                }
            })
            .catch(error => {
                hideLoading();
                btn.disabled = false;
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ في الاتصال',
                    text: 'حدث خطأ في الاتصال بالخادم',
                    confirmButtonText: 'حسناً'
                });
            });
        });

        // معالجة نموذج التعديل
        document.getElementById('editSectionForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!this.checkValidity()) {
                this.classList.add('was-validated');
                return;
            }
            
            const btn = document.getElementById('btnUpdate');
            if (btn.disabled) return;
            
            btn.disabled = true;
            showLoading();
            
            const formData = new FormData(this);
            
            fetch('update_section.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                hideLoading();
                btn.disabled = false;
                
                bootstrap.Modal.getInstance(document.getElementById('editSectionModal')).hide();
                
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'تم بنجاح',
                        text: data.message,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'خطأ',
                        text: data.message,
                        confirmButtonText: 'حسناً'
                    });
                }
            })
            .catch(error => {
                hideLoading();
                btn.disabled = false;
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ في الاتصال',
                    text: 'حدث خطأ في الاتصال بالخادم',
                    confirmButtonText: 'حسناً'
                });
            });
        });

        // معالجة نموذج الحذف
        document.getElementById('deleteForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const btn = document.getElementById('btnDelete');
            if (btn.disabled) return;
            
            btn.disabled = true;
            showLoading();
            
            const formData = new FormData(this);
            
            fetch('delete_section.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                hideLoading();
                btn.disabled = false;
                
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'تم بنجاح',
                        text: data.message,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        window.location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'خطأ',
                        text: data.message,
                        confirmButtonText: 'حسناً'
                    });
                }
            })
            .catch(error => {
                hideLoading();
                btn.disabled = false;
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'خطأ في الاتصال',
                    text: 'حدث خطأ في الاتصال بالخادم',
                    confirmButtonText: 'حسناً'
                });
            });
        });

        // إعادة تعيين النماذج عند إغلاق المودالات
        document.getElementById('addSectionModal')?.addEventListener('hidden.bs.modal', function () {
            const form = document.getElementById('addSectionForm');
            form.reset();
            form.classList.remove('was-validated');
            document.getElementById('btnSave').disabled = false;
        });

        document.getElementById('editSectionModal')?.addEventListener('hidden.bs.modal', function () {
            document.getElementById('btnUpdate').disabled = false;
        });

        document.getElementById('deleteModal')?.addEventListener('hidden.bs.modal', function () {
            document.getElementById('btnDelete').disabled = false;
        });

        // إخفاء مؤشر التحميل عند تحميل الصفحة
        window.addEventListener('load', hideLoading);
    </script>
</body>
</html>