<?php
// add-student.php - النسخة المحدثة مع الاحتفاظ بنوع القبول فقط
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

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

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

$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
$colleges = [];
$colleges_stmt = $mysqli1->prepare("SELECT id, name FROM colleges WHERE deleted_at IS NULL ORDER BY name");
if ($colleges_stmt) {
    $colleges_stmt->execute();
    $result = $colleges_stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $colleges[] = [
            'id' => (int)$row['id'],
            'name' => htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8')
        ];
    }
    $colleges_stmt->close();
}

// Programs
$programs = [];
$programs_stmt = $mysqli1->prepare("SELECT id, name FROM programs WHERE deleted_at IS NULL ORDER BY name");
if ($programs_stmt) {
    $programs_stmt->execute();
    $result = $programs_stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $programs[] = [
            'id' => (int)$row['id'],
            'name' => htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8')
        ];
    }
    $programs_stmt->close();
}

// Get ALL sections
$all_sections = [];
$all_sections_stmt = $mysqli1->prepare("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
if ($all_sections_stmt) {
    $all_sections_stmt->execute();
    $result = $all_sections_stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $all_sections[] = [
            'id' => (int)$row['id'],
            'name' => htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8'),
            'parent' => (int)$row['parent']
        ];
    }
    $all_sections_stmt->close();
}

// Batches
$batches = [];
$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value");
if ($batches_stmt) {
    $batches_stmt->execute();
    $result = $batches_stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $batches[] = [
            'id' => (int)$row['id'],
            'value' => htmlspecialchars($row['value'], ENT_QUOTES, 'UTF-8')
        ];
    }
    $batches_stmt->close();
}

// Admissions types
$admissions = [];
try {
    $admissions_stmt = $mysqli1->prepare("SELECT id, name FROM admissions ORDER BY name");
    if ($admissions_stmt) {
        $admissions_stmt->execute();
        $result = $admissions_stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $admissions[] = [
                'id' => (int)$row['id'],
                'name' => htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8')
            ];
        }
        $admissions_stmt->close();
    }
} catch (Exception $e) {
    error_log("Error fetching admissions: " . $e->getMessage());
}

// 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 ?: [];
}

// إعادة تعبئة النموذج في حالة وجود خطأ
$form_data = $_SESSION['form_data'] ?? [];
unset($_SESSION['form_data']);

// دالة مساعدة للقيم السابقة
function old($field, $default = '') {
    global $form_data;
    return isset($form_data[$field]) ? htmlspecialchars($form_data[$field], ENT_QUOTES, 'UTF-8') : htmlspecialchars($default, ENT_QUOTES, 'UTF-8');
}

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">
    <!-- 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;
        }
        
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        
        .generated-id {
            background-color: #e8f5e9 !important;
            font-weight: bold;
            color: #2e7d32;
            border-color: #81c784;
        }
        
        .manual-entry {
            background-color: #fff3cd !important;
            font-weight: bold;
            color: #856404;
            border-color: #ffeaa7;
        }
        
        .spinner-border-sm {
            width: 1rem;
            height: 1rem;
            border-width: 0.2em;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 0.875em;
            margin-top: 0.25rem;
        }
        
        .mode-indicator {
            font-size: 0.85rem;
            padding: 8px 12px;
            border-radius: 6px;
            margin-top: 8px;
            display: block;
            line-height: 1.5;
        }
        
        .mode-auto {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .mode-manual {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        .btn-group-mode {
            margin-top: 5px;
        }
        
        .btn-mode {
            font-size: 0.85rem;
            padding: 0.35rem 0.75rem;
        }
        
        .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;
        }
        
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #2596be;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-light">
    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>

    <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-user-plus ms-2"></i>إضافة طالب جديد
            </h3>
            <div class="me-auto">
                <a class="btn btn-outline-secondary" href="admin_dashboard.php">
                    <i class="fas fa-arrow-right me-2"></i>العودة لقائمة الطلاب
                </a>
            </div>
        </div>

        <?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 float-start" 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>
                <?= htmlspecialchars($_SESSION['error_message'], ENT_QUOTES, 'UTF-8') ?>
                <button type="button" class="btn-close float-start" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Add Student Form -->
        <div class="card card-arabic p-4">
            <form action="save_student.php" method="POST" id="studentForm">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                
                <!-- القسم 1: البيانات الأساسية -->
                <div class="form-section">
                    <h5 class="section-title">
                        <i class="fas fa-id-card ms-3"></i>البيانات الأساسية للطالب
                    </h5>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="student_id" class="form-label required">
                                    <i class="fas fa-hashtag ms-2"></i>رقم الطالب
                                    <span class="badge bg-info ms-2" data-bs-toggle="tooltip" title="يتم توليد الرقم تلقائياً: أكبر رقم في نفس القسم والدفعة + 1">
                                        <i class="fas fa-info-circle"></i>
                                    </span>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control text-end generated-id" name="student_id" id="student_id" required
                                           placeholder="سيتم توليد الرقم تلقائياً" dir="ltr" readonly
                                           value="<?= old('student_id') ?>"
                                           maxlength="50">
                                    <button type="button" class="btn btn-outline-primary" id="generateIdBtn">
                                        <i class="fas fa-sync-alt ms-2"></i>توليد رقم طالب
                                    </button>
                                </div>
                                
                                <!-- Mode selector buttons -->
                                <div class="btn-group-mode d-flex gap-2 mt-2">
                                    <button type="button" class="btn btn-success btn-sm btn-mode active" id="btnAutoMode" data-mode="auto">
                                        <i class="fas fa-robot ms-1"></i>توليد تلقائي
                                    </button>
                                    <button type="button" class="btn btn-warning btn-sm btn-mode" id="btnManualMode" data-mode="manual">
                                        <i class="fas fa-edit ms-1"></i>إدخال يدوي
                                    </button>
                                </div>
                                
                                <!-- Mode indicator -->
                                <div id="modeIndicator" class="mode-indicator mode-auto">
                                    <i class="fas fa-robot ms-1"></i>
                                    <strong>وضع التوليد التلقائي</strong><br>
                                    <small>سيتم توليد الرقم: (أكبر رقم في نفس القسم والدفعة + 1)</small>
                                </div>
                                
                                <!-- Error message container -->
                                <div id="studentIdError" class="error-message"></div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="fas fa-user ms-2"></i>الاسم بالعربية
                                </label>
                                <input type="text" class="form-control" name="student_name" required
                                       placeholder="أدخل الاسم الكامل بالعربية"
                                       value="<?= old('student_name') ?>"
                                       maxlength="191">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-font ms-2"></i>الاسم بالإنجليزية
                                </label>
                                <input type="text" class="form-control" name="student_name_eng"
                                       placeholder="أدخل الاسم بالإنجليزية (اختياري)"
                                       value="<?= old('student_name_eng') ?>"
                                       maxlength="191">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="fas fa-venus-mars ms-2"></i>الجنس
                                </label>
                                <div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="gender_male" value="1" required
                                               <?= (old('gender') == '1') ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="gender_male">
                                            <i class="fas fa-male ms-1"></i>ذكر
                                        </label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="gender_female" value="2"
                                               <?= (old('gender') == '2') ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="gender_female">
                                            <i class="fas fa-female ms-1"></i>أنثى
                                        </label>
                                    </div>
                                </div>
                                <div class="error-message" id="genderError"></div>
                            </div>
                        </div>
                        
                        <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="college_id" id="college_id" required
                                    <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                                    <option value="">اختر الكلية</option>
                                    <?php foreach ($colleges as $college): ?>
                                        <option value="<?= $college['id'] ?>"
                                            <?= ((!$canAll && $scopeCollege !== null && $scopeCollege == $college['id']) || old('college_id') == $college['id']) ? 'selected' : '' ?>>
                                            <?= $college['name'] ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if (!$canAll && $scopeCollege !== null): ?>
                                    <input type="hidden" name="college_id" value="<?= htmlspecialchars($scopeCollege, ENT_QUOTES, 'UTF-8') ?>">
                                    <div class="form-text">يتم تعيين الكلية بناءً على صلاحياتك</div>
                                <?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" id="program_id" required>
                                    <option value="">اختر البرنامج</option>
                                    <?php foreach ($programs as $program): ?>
                                        <option value="<?= $program['id'] ?>"
                                            <?= (old('program_id') == $program['id']) ? 'selected' : '' ?>>
                                            <?= $program['name'] ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <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="section_id" required>
                                    <option value="">اختر القسم</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-microscope ms-2"></i>التخصص
                                </label>
                                <select class="form-select" name="specialization_id" id="specialization_id">
                                    <option value="">اختر القسم والبرنامج أولاً</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label required">
                                    <i class="fas fa-users ms-2"></i>الدفعة
                                </label>
                                <select class="form-select" name="batch_id" id="batch_id" required>
                                    <option value="">اختر الدفعة</option>
                                    <?php foreach ($batches as $batch): ?>
                                        <option value="<?= $batch['id'] ?>"
                                            <?= (old('batch_id') == $batch['id']) ? 'selected' : '' ?>>
                                            <?= $batch['value'] ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <!-- نوع القبول - الحقل الوحيد المتبقي من المعلومات الإدارية -->
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-tag ms-2"></i>نوع القبول
                                </label>
                                <select class="form-select" name="admission_id">
                                    <option value="">اختر نوع القبول</option>
                                    <?php foreach ($admissions as $admission): ?>
                                        <option value="<?= $admission['id'] ?>"
                                            <?= (old('admission_id') == $admission['id']) ? 'selected' : '' ?>>
                                            <?= $admission['name'] ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- تم حذف قسم المعلومات الإدارية بالكامل -->
                
                <!-- القسم 3: المعلومات المالية -->
                <div class="form-section">
                    <h5 class="section-title">
                        <i class="fas fa-money-bill-wave ms-3"></i>المعلومات المالية
                    </h5>
                    
                    <div class="row">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">رسوم البرنامج</label>
                                <div class="input-group">
                                    <input type="number" step="0.01" min="0" class="form-control text-end" name="program_fees"
                                           placeholder="0.00" dir="ltr" 
                                           value="<?= old('program_fees', '0') ?>">
                                    <span class="input-group-text">ج.س</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">رسوم التسجيل</label>
                                <div class="input-group">
                                    <input type="number" step="0.01" min="0" class="form-control text-end" name="registration_fees"
                                           placeholder="0.00" 
                                           value="<?= old('registration_fees', '0') ?>" dir="ltr">
                                    <span class="input-group-text">ج.س</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">رسوم التأمين</label>
                                <div class="input-group">
                                    <input type="number" step="0.01" min="0" class="form-control text-end" name="insurance_fees"
                                           placeholder="0.00" 
                                           value="<?= old('insurance_fees', '0') ?>" dir="ltr">
                                    <span class="input-group-text">ج.س</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">الخصم (%)</label>
                                <div class="input-group">
                                    <input type="number" step="0.01" min="0" max="100" class="form-control text-end" name="discount"
                                           placeholder="0" 
                                           value="<?= old('discount', '0') ?>" dir="ltr">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-info mb-0">
                                <i class="fas fa-info-circle ms-2"></i>
                                <strong>ملاحظة:</strong> يمكنك ترك القيم المالية صفراً إذا لم تكن متوفرة حالياً.
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- أزرار التحكم -->
                <div class="row mt-4 pt-3 border-top">
                    <div class="col-12">
                        <div class="d-flex justify-content-start gap-2">
                            <button type="submit" class="btn btn-success px-4 py-2" id="submitBtn">
                                <i class="fas fa-user-plus ms-2"></i>إضافة الطالب
                            </button>
                            <a href="admin_dashboard.php" class="btn btn-secondary px-4 py-2">
                                <i class="fas fa-times ms-2"></i>إلغاء
                            </a>
                            <button type="button" class="btn btn-outline-warning px-4 py-2" id="resetBtn">
                                <i class="fas fa-redo ms-2"></i>إعادة تعيين
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        
        <script>
        // تخزين بيانات جميع الأقسام
        const allSections = <?= json_encode($all_sections, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
        let isManualEntry = false;

        // دالة لتحميل القسم المحدد سابقاً
        function loadSelectedSection() {
            const selectedSectionId = "<?= old('section_id') ?>";
            const collegeId = document.getElementById('college_id').value;
            
            if (!collegeId) return;
            
            const sectionSelect = document.getElementById('section_id');
            sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
            
            // تصفية الأقسام حسب الكلية
            const filteredSections = allSections.filter(section => section.parent == collegeId);
            
            filteredSections.forEach(section => {
                const option = document.createElement('option');
                option.value = section.id;
                option.textContent = section.name;
                
                // تحديد القسم المحدد سابقاً
                if (section.id == selectedSectionId) {
                    option.selected = true;
                }
                
                sectionSelect.appendChild(option);
            });
            
            // تحميل التخصصات بعد تحديد القسم
            if (selectedSectionId) {
                loadSpecializations();
            }
        }

        // دالة لتحميل التخصصات باستخدام AJAX
        function loadSpecializations() {
            const sectionId = document.getElementById('section_id').value;
            const programId = document.getElementById('program_id').value;
            const specSelect = document.getElementById('specialization_id');
            const selectedSpecId = "<?= old('specialization_id') ?>";
            
            // إظهار حالة التحميل
            specSelect.innerHTML = '<option value="">جاري تحميل التخصصات...</option>';
            specSelect.disabled = true;
            
            // التحقق من وجود القسم والبرنامج
            if (!sectionId || !programId) {
                specSelect.innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
                specSelect.disabled = false;
                return;
            }
            
            // استدعاء AJAX
            $.ajax({
                url: 'ajax/get_specializations.php',
                type: 'GET',
                data: {
                    section_id: sectionId,
                    program_id: programId
                },
                dataType: 'json',
                success: function(data) {
                    specSelect.innerHTML = '<option value="">اختر التخصص (اختياري)</option>';
                    
                    if (data && data.length > 0) {
                        data.forEach(function(spec) {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            
                            // تحديد التخصص المحدد سابقاً
                            if (selectedSpecId && spec.specialization_id == selectedSpecId) {
                                option.selected = true;
                            }
                            
                            specSelect.appendChild(option);
                        });
                    } else {
                        specSelect.innerHTML = '<option value="">لا توجد تخصصات</option>';
                    }
                    
                    specSelect.disabled = false;
                },
                error: function(xhr, status, error) {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">خطأ في تحميل التخصصات</option>';
                    specSelect.disabled = false;
                }
            });
        }

        // دالة للتبديل بين الوضع التلقائي واليدوي
        function toggleEntryMode(mode) {
            const studentIdInput = document.getElementById('student_id');
            const generateBtn = document.getElementById('generateIdBtn');
            const btnAutoMode = document.getElementById('btnAutoMode');
            const btnManualMode = document.getElementById('btnManualMode');
            const modeIndicator = document.getElementById('modeIndicator');
            
            isManualEntry = (mode === 'manual');
            
            if (isManualEntry) {
                // التبديل إلى الوضع اليدوي
                studentIdInput.readOnly = false;
                studentIdInput.placeholder = "أدخل رقم الطالب يدوياً";
                studentIdInput.classList.remove('generated-id');
                studentIdInput.classList.add('manual-entry');
                generateBtn.disabled = true;
                
                btnAutoMode.classList.remove('active', 'btn-success');
                btnAutoMode.classList.add('btn-outline-success');
                btnManualMode.classList.add('active', 'btn-warning');
                btnManualMode.classList.remove('btn-outline-warning');
                
                modeIndicator.className = "mode-indicator mode-manual";
                modeIndicator.innerHTML = `
                    <i class="fas fa-edit ms-1"></i>
                    <strong>وضع الإدخال اليدوي</strong><br>
                    <small>يمكنك إدخال أي رقم ترغب فيه</small>
                `;
                
            } else {
                // التبديل إلى الوضع التلقائي
                studentIdInput.readOnly = true;
                studentIdInput.placeholder = "سيتم توليد الرقم تلقائياً";
                studentIdInput.classList.remove('manual-entry');
                studentIdInput.classList.add('generated-id');
                generateBtn.disabled = false;
                
                btnAutoMode.classList.add('active', 'btn-success');
                btnAutoMode.classList.remove('btn-outline-success');
                btnManualMode.classList.remove('active', 'btn-warning');
                btnManualMode.classList.add('btn-outline-warning');
                
                modeIndicator.className = "mode-indicator mode-auto";
                modeIndicator.innerHTML = `
                    <i class="fas fa-robot ms-1"></i>
                    <strong>وضع التوليد التلقائي</strong><br>
                    <small>سيتم توليد الرقم: (أكبر رقم في نفس القسم والدفعة + 1)</small>
                `;
                
                autoGenerateIfConditionsMet();
            }
        }

        // دالة تحميل الأقسام بناءً على الكلية المحددة
        function loadSections() {
            const collegeId = document.getElementById('college_id').value;
            const sectionSelect = document.getElementById('section_id');
            const specSelect = document.getElementById('specialization_id');
            
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            specSelect.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);
                });
                
                autoGenerateIfConditionsMet();
            }, 300);
        }

        // دالة توليد رقم الطالب التالي
        function generateNextStudentId() {
            const sectionId = document.getElementById('section_id').value;
            const batchId = document.getElementById('batch_id').value;
            
            if (!sectionId || !batchId) {
                alert('❌ الرجاء اختيار القسم والدفعة أولاً');
                return;
            }
            
            const studentIdInput = document.getElementById('student_id');
            const generateBtn = document.getElementById('generateIdBtn');
            const errorContainer = document.getElementById('studentIdError');
            const modeIndicator = document.getElementById('modeIndicator');
            
            const originalBtnText = generateBtn.innerHTML;
            generateBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>جاري التوليد...';
            generateBtn.disabled = true;
            
            errorContainer.textContent = '';
            studentIdInput.classList.remove('is-invalid');
            
            fetch('generate_student_id.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    section_id: sectionId,
                    batch_id: batchId,
                    csrf_token: '<?= $_SESSION['csrf_token'] ?>'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    studentIdInput.value = data.next_student_id;
                    studentIdInput.classList.remove('is-invalid');
                    studentIdInput.classList.add('is-valid', 'generated-id');
                    
                    let indicatorHtml = `
                        <i class="fas fa-check-circle ms-1 text-success"></i>
                        <strong>${data.message}</strong><br>
                    `;
                    
                    if (data.last_student_id) {
                        indicatorHtml += `<small class="text-success">
                            <i class="fas fa-calculator ms-1"></i>
                            ${data.last_student_id} → ${data.next_student_id}
                        </small>`;
                    } else {
                        indicatorHtml += `<small class="text-info">
                            <i class="fas fa-star ms-1"></i>
                            أول طالب في هذا القسم والدفعة
                        </small>`;
                    }
                    
                    modeIndicator.innerHTML = indicatorHtml;
                } else {
                    errorContainer.textContent = '❌ ' + data.message;
                    studentIdInput.classList.add('is-invalid');
                    studentIdInput.classList.remove('generated-id');
                    
                    modeIndicator.innerHTML = `
                        <i class="fas fa-exclamation-triangle ms-1 text-danger"></i>
                        <strong class="text-danger">${data.message}</strong>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                errorContainer.textContent = '❌ حدث خطأ في الاتصال';
                studentIdInput.classList.add('is-invalid');
            })
            .finally(() => {
                generateBtn.innerHTML = originalBtnText;
                generateBtn.disabled = false;
            });
        }

        // دالة التوليد التلقائي
        function autoGenerateIfConditionsMet() {
            if (isManualEntry) return;
            
            const sectionId = document.getElementById('section_id').value;
            const batchId = document.getElementById('batch_id').value;
            const studentIdInput = document.getElementById('student_id');
            
            if (sectionId && batchId && !studentIdInput.value) {
                generateNextStudentId();
            }
        }

        // التهيئة عند تحميل الصفحة
        document.addEventListener('DOMContentLoaded', function() {
            const hasFormData = "<?= !empty($form_data) ? 'true' : 'false' ?>";
            
            if (hasFormData === 'true') {
                loadSelectedSection();
                
                const studentIdValue = document.getElementById('student_id').value;
                if (studentIdValue) {
                    toggleEntryMode('manual');
                }
            }
            
            const collegeSelect = document.getElementById('college_id');
            const initialCollegeId = collegeSelect.value;
            
            if (initialCollegeId && !hasFormData) {
                loadSections();
            }
            
            // Add event listeners
            document.getElementById('generateIdBtn').addEventListener('click', generateNextStudentId);
            
            document.getElementById('btnAutoMode').addEventListener('click', () => toggleEntryMode('auto'));
            document.getElementById('btnManualMode').addEventListener('click', () => toggleEntryMode('manual'));
            
            document.getElementById('section_id').addEventListener('change', function() {
                autoGenerateIfConditionsMet();
                loadSpecializations();
            });
            
            document.getElementById('program_id').addEventListener('change', function() {
                loadSpecializations();
            });
            
            document.getElementById('batch_id').addEventListener('change', autoGenerateIfConditionsMet);
            document.getElementById('college_id').addEventListener('change', loadSections);
            
            // Form submission
            const form = document.getElementById('studentForm');
            const submitBtn = document.getElementById('submitBtn');
            
            form.addEventListener('submit', function(e) {
                document.getElementById('loadingOverlay').style.display = 'flex';
                submitBtn.disabled = true;
                
                const requiredFields = form.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');
                    }
                });
                
                const genderSelected = document.querySelector('input[name="gender"]:checked');
                if (!genderSelected) {
                    document.getElementById('genderError').textContent = 'الرجاء اختيار الجنس';
                    isValid = false;
                }
                
                if (!isValid) {
                    e.preventDefault();
                    document.getElementById('loadingOverlay').style.display = 'none';
                    submitBtn.disabled = false;
                    alert('❌ الرجاء ملء جميع الحقول المطلوبة');
                }
            });
            
            // Reset button
            document.getElementById('resetBtn').addEventListener('click', function() {
                if (confirm('هل أنت متأكد من إعادة تعيين جميع الحقول؟')) {
                    form.reset();
                    setTimeout(() => {
                        toggleEntryMode('auto');
                        if (document.getElementById('college_id').value) {
                            loadSections();
                        }
                        document.getElementById('specialization_id').innerHTML = '<option value="">اختر القسم والبرنامج أولاً</option>';
                    }, 500);
                }
            });
            
            // Initialize tooltips
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });
        </script>
    </div>
</body>
</html>
