<?php
// Add-student.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'db.php';
require 'helpers.php';
require_committee();

$committeeId   = (int)($_SESSION['committee_id'] ?? 0);
$committeeName = (string)($_SESSION['committee_name'] ?? '');
$canAll        = (bool)($_SESSION['committee_can_all'] ?? false);
$scopeCollege  = isset($_SESSION['committee_college_id']) ? (int)$_SESSION['committee_college_id'] : null;

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

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

// Get ALL sections WITHOUT code column for initial load
$all_sections_stmt = $mysqli1->prepare("SELECT id, name, parent FROM sections WHERE deleted_at IS NULL ORDER BY name");
$all_sections_stmt->execute();
$all_sections = $all_sections_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch batches WITHOUT code column from database
$batches_stmt = $mysqli1->prepare("SELECT id, value FROM batches WHERE deleted_at IS NULL ORDER BY value");
$batches_stmt->execute();
$batches = $batches_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get admissions types from database - FIXED: removed deleted_at condition
$admissions_stmt = $mysqli1->prepare("SELECT id, name FROM admissions ORDER BY name");
$admissions_stmt->execute();
$admissions = $admissions_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

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

include 'header.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إضافة طالب جديد - لوحة اللجنة</title>
    
    <!-- Bootstrap 5 RTL -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap RTL -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Google Fonts: Cairo (Arabic font) -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        /* RTL Styling */
        :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;
        }
        
        /* RTL Form Controls */
        .form-control, .form-select {
            text-align: right;
            direction: rtl;
            padding-right: 12px;
            padding-left: 40px; /* Space for icons on left */
        }
        
        /* RTL Dropdown Menu */
        .dropdown-menu {
            text-align: right;
            direction: rtl;
        }
        
        .form-select {
            background-position: left 0.75rem center;
        }
        
        /* RTL Radio and Checkbox */
        .form-check {
            padding-right: 1.5em;
            padding-left: 0;
        }
        
        .form-check-input {
            float: right;
            margin-right: -1.5em;
            margin-left: 0;
        }
        
        .form-check-inline {
            margin-left: 1rem;
            margin-right: 0;
        }
        
        /* RTL Labels and Text */
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            text-align: right;
        }
        
        .required::after {
            content: " *";
            color: #dc3545;
        }
        
        /* RTL Form Text */
        .form-text {
            text-align: right;
            margin-top: 0.25rem;
        }
        
        /* RTL Headings */
        .rtl-heading {
            text-align: right;
            font-weight: 700;
            color: #1F3A2E;
            border-right: 4px solid #2ecc71;
            padding-right: 15px;
            margin: 20px 0;
        }
        
        /* RTL Card */
        .card-arabic {
            border: 1px solid #e5e7eb;
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 10px 24px rgba(0,0,0,.06);
            margin-bottom: 20px;
        }
        
        /* RTL Container */
        .container {
            padding-right: 15px;
            padding-left: 15px;
            margin-right: auto;
            margin-left: auto;
        }
        
        /* RTL Buttons */
        .btn i {
            margin-left: 8px;
            margin-right: 0;
        }
        
        .btn-outline-secondary i {
            margin-right: 8px;
            margin-left: 0;
        }
        
        /* RTL Alert */
        .alert {
            text-align: right;
            direction: rtl;
        }
        
        .alert-dismissible .btn-close {
            margin-left: -0.75rem;
            margin-right: auto;
            float: left;
        }
        
        /* RTL Input Groups */
        .input-group {
            direction: rtl;
        }
        
        .input-group-text {
            border-radius: 0 0.375rem 0.375rem 0;
        }
        
        .input-group .form-control {
            border-radius: 0.375rem 0 0 0.375rem;
        }
        
        /* RTL Grid Adjustments */
        .row {
            margin-right: -15px;
            margin-left: -15px;
        }
        
        .col-md-6, .col-md-4, .col-12 {
            padding-right: 15px;
            padding-left: 15px;
        }
        
        /* RTL Spacing Utilities */
        .me-auto {
            margin-left: auto !important;
            margin-right: 0 !important;
        }
        
        .ms-auto {
            margin-right: auto !important;
            margin-left: 0 !important;
        }
        
        .me-2 {
            margin-left: 0.5rem !important;
            margin-right: 0 !important;
        }
        
        .ms-2 {
            margin-right: 0.5rem !important;
            margin-left: 0 !important;
        }
        
        /* RTL Gap */
        .gap-2 {
            gap: 0.5rem;
            margin-left: 0.5rem;
            margin-right: 0;
        }
        
        /* RTL Radio Button Group */
        .form-check-inline:first-child {
            margin-right: 0;
        }
        
        /* RTL Date Input */
        input[type="date"] {
            direction: rtl;
        }
        
        /* Placeholder RTL */
        ::placeholder {
            text-align: right;
            direction: rtl;
        }
        
        /* RTL Table */
        table {
            direction: rtl;
        }
        
        th {
            text-align: right;
        }
        
        /* Custom RTL Classes */
        .text-start {
            text-align: right !important;
        }
        
        .text-end {
            text-align: left !important;
        }
        
        /* RTL Form Validation */
        .is-valid, .is-invalid {
            padding-left: 2.25rem;
            padding-right: 0.75rem;
            background-position: left 0.375rem center;
        }
        
        /* Auto-generated ID styling */
        .generated-id {
            background-color: #e8f5e9 !important;
            font-weight: bold;
            color: #2e7d32;
            border-color: #81c784;
        }
        
        .generated-id:focus {
            background-color: #c8e6c9 !important;
            border-color: #4caf50;
            box-shadow: 0 0 0 0.25rem rgba(76, 175, 80, 0.25);
        }
        
        /* Loading spinner */
        .spinner-border-sm {
            width: 1rem;
            height: 1rem;
            border-width: 0.2em;
        }
        
        /* Info badge */
        .info-badge {
            background-color: #e3f2fd;
            color: #1565c0;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.85em;
            margin-right: 5px;
        }
        
        /* Compact spacing */
        .compact-section {
            margin-bottom: 1.5rem;
        }
    </style>
</head>
<body class="bg-light">
    <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="committee_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>
                <?= $_SESSION['success_message'] ?>
                <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>
                <?= $_SESSION['error_message'] ?>
                <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">
                
                <!-- Section 1: Student Basic Information -->
                <div class="compact-section">
                    <h4 class="rtl-heading mb-3">
                        <i class="fas fa-id-card ms-3"></i>المعلومات الأساسية
                    </h4>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="student_id" class="form-label required">
                                    <i class="fas fa-hashtag ms-2"></i>رقم الطالب
                                </label>
                                <input type="text" 
                                       class="form-control text-end" 
                                       name="student_id" 
                                       id="student_id" 
                                       required
                                       placeholder="أدخل رقم الطالب يدوياً" 
                                       dir="ltr"
                                       autocomplete="off">
                                <div class="form-text">
                                    <i class="fas fa-info-circle ms-2"></i>
                                    أدخل رقم الطالب يدوياً
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <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"
                                       placeholder="أدخل الاسم الكامل بالعربية"
                                       required>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <!-- حقل الاسم بالإنجليزية تم حذفه -->
                        </div>
                    </div>
                </div>
                
                <!-- Section 2: Academic Information -->
                <div class="compact-section border-top pt-3">
                    <h4 class="rtl-heading mb-3">
                        <i class="fas fa-graduation-cap ms-3"></i>المعلومات الأكاديمية
                    </h4>
                    
                    <div class="row">
                        <div class="col-md-3">
                            <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" onchange="loadSections()" required
                                    <?= (!$canAll && $scopeCollege !== null) ? 'disabled' : '' ?>>
                                    <option value="">اختر الكلية</option>
                                    <?php foreach ($colleges as $college): ?>
                                        <option value="<?= e($college['id'] ?? '') ?>"
                                            <?= (!$canAll && $scopeCollege !== null && $scopeCollege == $college['id']) ? 'selected' : '' ?>>
                                            <?= e($college['name'] ?? '') ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <?php if (!$canAll && $scopeCollege !== null): ?>
                                    <input type="hidden" name="college_id" value="<?= $scopeCollege ?>">
                                    <div class="form-text">يتم تعيين الكلية بناءً على صلاحياتك</div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <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="<?= e($program['id'] ?? '') ?>">
                                            <?= e($program['name'] ?? '') ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <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>
                                    <!-- Sections will be populated by JavaScript -->
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <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="<?= e($batch['id'] ?? '') ?>">
                                            <?= e($batch['value'] ?? '') ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Section 3: Admission & Gender -->
                <div class="compact-section border-top pt-3">
                    <div class="row">
                        <div class="col-md-4">
                            <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">
                                        <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">
                                        <label class="form-check-label" for="gender_female">
                                            <i class="fas fa-female ms-1"></i>أنثى
                                        </label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="gender_unknown" value="0" checked>
                                        <label class="form-check-label" for="gender_unknown">غير محدد</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <!-- حقل رقم القبول تم حذفه -->
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-tag ms-2"></i>نوع القبول
                                </label>
                                <select class="form-select" name="admission_type">
                                    <option value="">اختر نوع القبول</option>
                                    <?php foreach ($admissions as $admission): ?>
                                        <option value="<?= e($admission['name'] ?? '') ?>">
                                            <?= e($admission['name'] ?? '') ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Section 4: Financial Information -->
                <div class="compact-section border-top pt-3">
                    <h4 class="rtl-heading mb-3">
                        <i class="fas fa-money-bill-wave ms-3"></i>المعلومات المالية
                    </h4>
                    
                    <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" class="form-control text-end" name="program_fees"
                                           placeholder="رسوم البرنامج" 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" class="form-control text-end" name="registration_fees"
                                           placeholder="رسوم التسجيل" value="0.00" 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" class="form-control text-end" name="insurance_fees"
                                           placeholder="رسوم التأمين" value="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>
                                <input type="number" step="0.01" class="form-control text-end" name="discount"
                                       placeholder="نسبة الخصم" value="0" dir="ltr">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Section 5: Status Information -->
                <div class="compact-section border-top pt-3">
                    <h4 class="rtl-heading mb-3">
                        <i class="fas fa-clipboard-check ms-3"></i>حالة الطالب
                    </h4>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-comments ms-2"></i>حالة المقابلة
                                </label>
                                <select class="form-select" name="interview_status">
                                    <option value="pending" selected>قيد الانتظار</option>
                                    <option value="accepted">مقبول</option>
                                    <option value="rejected">مرفوض</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-heartbeat ms-2"></i>الحالة الطبية
                                </label>
                                    <select class="form-select" name="medically_fit">
                                        <option value="" selected>غير محدد</option>
                                        <option value="1">لائق</option>
                                        <option value="0">غير لائق</option>
                                    </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-folder ms-2"></i>حالة الملف
                                </label>
                                <select class="form-select" name="profile_completed">
                                    <option value="0" selected>غير مكتمل</option>
                                    <option value="1">مكتمل</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Submit Buttons -->
                <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">
                                <i class="fas fa-user-plus ms-2"></i>إضافة الطالب
                            </button>
                            <a href="committee_dashboard.php" class="btn btn-secondary px-4 py-2">
                                <i class="fas fa-times ms-2"></i>إلغاء
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <script>
        // Store all sections data for filtering
        const allSections = <?= json_encode($all_sections) ?>;

        function loadSections() {
            const collegeId = document.getElementById('college_id').value;
            const sectionSelect = document.getElementById('section_id');
            
            // Show loading
            sectionSelect.innerHTML = '<option value="">جاري تحميل الأقسام...</option>';
            
            // Small delay to show loading (UX)
            setTimeout(() => {
                // Filter sections by college
                const filteredSections = allSections.filter(section => section.parent == collegeId);
                
                if (filteredSections.length === 0) {
                    sectionSelect.innerHTML = '<option value="">لا توجد أقسام لهذه الكلية</option>';
                    return;
                }
                
                sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
                filteredSections.forEach(section => {
                    const option = document.createElement('option');
                    option.value = section.id;
                    option.textContent = section.name;
                    sectionSelect.appendChild(option);
                });
            }, 300);
        }

        // Function to check if student ID already exists
        function checkStudentIdExists(studentId) {
            if (!studentId) return;
            
            $.ajax({
                url: 'check_student_id.php',
                type: 'POST',
                data: { student_id: studentId },
                dataType: 'json',
                success: function(response) {
                    if (response.exists) {
                        alert('رقم الطالب هذا مسجل مسبقاً! الرجاء إدخال رقم مختلف.');
                        document.getElementById('student_id').focus();
                        document.getElementById('student_id').classList.add('is-invalid');
                    } else {
                        document.getElementById('student_id').classList.remove('is-invalid');
                        document.getElementById('student_id').classList.add('is-valid');
                    }
                },
                error: function() {
                    console.log('حدث خطأ في التحقق من رقم الطالب');
                }
            });
        }

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            // If college is pre-selected (due to permissions), load its sections
            const collegeSelect = document.getElementById('college_id');
            const initialCollegeId = collegeSelect.value;
            
            if (initialCollegeId) {
                loadSections();
            }
            
            // Check student ID when field loses focus
            const studentIdInput = document.getElementById('student_id');
            studentIdInput.addEventListener('blur', function() {
                if (this.value.trim()) {
                    checkStudentIdExists(this.value);
                }
            });
            
            // RTL form validation
            const form = document.getElementById('studentForm');
            form.addEventListener('submit', function(e) {
                // Add RTL validation feedback
                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');
                        if (field.id === 'student_id') {
                            field.classList.add('is-valid');
                        }
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    alert('الرجاء ملء جميع الحقول المطلوبة (المميزة بعلامة *)');
                }
            });
        });
        </script>
    </div>

    <!-- Bootstrap & jQuery -->
    <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>
</body>
</html>
