<?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
$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 for initial load (we'll filter with JavaScript)
$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 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);

// 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 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body, h1,h2,h3,h4,h5,h6, p, a, button, label { 
            font-family: 'Cairo', system-ui, -apple-system, sans-serif !important; 
        }
        .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-heading {
            text-align: right;
            font-weight: 700;
            color: #1F3A2E;
        }
        .form-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        .required::after {
            content: " *";
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Header -->
        <div class="d-flex align-items-center mb-4">
            <h3 class="mb-0 fw-bold">إضافة طالب جديد</h3>
            <div class="ms-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">
                <?= $_SESSION['success_message'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?= $_SESSION['error_message'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>

        <!-- Add Student Form -->
        <div class="card card-arabic p-4">
            <h4 class="rtl-heading mb-4">بيانات الطالب الأساسية</h4>
            
            <form action="committee_save_student.php" method="POST" id="studentForm">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label required">رقم الطالب</label>
                            <input type="text" class="form-control" name="student_id" id="student_id" required
                                   placeholder="أدخل رقم الطالب الجامعي">
                            <div class="form-text">رقم تعريف الطالب الجامعي الفريد</div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الاسم بالعربية</label>
                            <input type="text" class="form-control" name="student_name"
                                   placeholder="أدخل الاسم الكامل بالعربية">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الاسم بالإنجليزية</label>
                            <input type="text" class="form-control" name="student_name_eng"
                                   placeholder="أدخل الاسم بالإنجليزية">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">البريد الإلكتروني</label>
                            <input type="email" class="form-control" name="email"
                                   placeholder="example@university.edu">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم الهاتف</label>
                            <input type="text" class="form-control" name="phone_number"
                                   placeholder="05XXXXXXXX">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم الهاتف البديل</label>
                            <input type="text" class="form-control" name="phone_number2"
                                   placeholder="05XXXXXXXX">
                        </div>
                        
                        <!-- Financial Information -->
                        <div class="mt-4">
                            <h5 class="rtl-heading mb-3">المعلومات المالية</h5>
                            <div class="mb-3">
                                <label class="form-label">رسوم البرنامج</label>
                                <input type="number" step="0.01" class="form-control" name="program_fees"
                                       placeholder="رسوم البرنامج">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">رسوم التسجيل</label>
                                <input type="number" step="0.01" class="form-control" name="registration_fees"
                                       placeholder="رسوم التسجيل" value="0.00">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">رسوم التأمين</label>
                                <input type="number" step="0.01" class="form-control" name="insurance_fees"
                                       placeholder="رسوم التأمين" value="0">
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">الخصم (%)</label>
                                <input type="number" step="0.01" class="form-control" name="discount"
                                       placeholder="نسبة الخصم" value="0">
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">الكلية</label>
                            <select class="form-select" name="college_id" id="college_id" onchange="loadSections()"
                                <?= (!$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 class="mb-3">
                            <label class="form-label">البرنامج</label>
                            <select class="form-select" name="program_id">
                                <option value="">اختر البرنامج</option>
                                <?php foreach ($programs as $program): ?>
                                    <option value="<?= e($program['id'] ?? '') ?>">
                                        <?= e($program['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">القسم</label>
                            <select class="form-select" name="section_id" id="section_id">
                                <option value="">اختر القسم</option>
                                <!-- Sections will be populated by JavaScript -->
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الدفعة</label>
                            <select class="form-select" name="batch_id">
                                <option value="">اختر الدفعة</option>
                                <?php foreach ($batches as $batch): ?>
                                    <option value="<?= e($batch['id'] ?? '') ?>">
                                        <?= e($batch['value'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الجنس</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">ذكر</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">أنثى</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>
                        
                        <!-- Additional Fields -->
                        <div class="mb-3">
                            <label class="form-label">رقم القبول</label>
                            <input type="text" class="form-control" name="admission_id"
                                   placeholder="رقم القبول">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">نوع القبول</label>
                            <input type="text" class="form-control" name="addmission_type"
                                   placeholder="نوع القبول">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">نوع الشهادة</label>
                            <input type="text" class="form-control" name="certificate_type"
                                   placeholder="نوع الشهادة">
                        </div>
                    </div>
                </div>
                
                <!-- Status Information -->
                <div class="row mt-4">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label class="form-label">حالة المقابلة</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">الحالة الطبية</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">حالة الملف</label>
                            <select class="form-select" name="profile_completed">
                                <option value="0" selected>غير مكتمل</option>
                                <option value="1">مكتمل</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Additional Information -->
                <div class="row mt-4">
                    <div class="col-12">
                        <h5 class="rtl-heading mb-3">معلومات إضافية</h5>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">الجنسية</label>
                            <input type="text" class="form-control" name="nationality"
                                   placeholder="الجنسية">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">تاريخ الميلاد</label>
                            <input type="date" class="form-control" name="date_of_birth">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">مكان الميلاد</label>
                            <input type="text" class="form-control" name="place_of_birth"
                                   placeholder="مكان الميلاد">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">اسم الأب</label>
                            <input type="text" class="form-control" name="father_name"
                                   placeholder="اسم الأب">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">اسم الأم</label>
                            <input type="text" class="form-control" name="mother_name"
                                   placeholder="اسم الأم">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">المهنة</label>
                            <input type="text" class="form-control" name="occupation"
                                   placeholder="المهنة">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">اسم ولي الأمر</label>
                            <input type="text" class="form-control" name="guardian_name"
                                   placeholder="اسم ولي الأمر">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم هاتف ولي الأمر</label>
                            <input type="text" class="form-control" name="guardian_phone_number"
                                   placeholder="رقم هاتف ولي الأمر">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">عنوان ولي الأمر</label>
                            <input type="text" class="form-control" name="guardian_address"
                                   placeholder="عنوان ولي الأمر">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">عنوان السكن</label>
                            <input type="text" class="form-control" name="home_address"
                                   placeholder="عنوان السكن">
                        </div>
                    </div>
                </div>
                
                <!-- Notes -->
                <div class="row mt-3">
                    <div class="col-12">
                        <div class="mb-3">
                            <label class="form-label">ملاحظات</label>
                            <textarea class="form-control" name="notes" rows="3"
                                      placeholder="أي ملاحظات إضافية عن الطالب"></textarea>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="d-flex justify-content-end gap-2">
                            <a href="committee_dashboard.php" class="btn btn-secondary">إلغاء</a>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-user-plus me-2"></i>إضافة الطالب
                            </button>
                        </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');
            
            // Filter sections by college
            const filteredSections = allSections.filter(section => section.parent == collegeId);
            
            sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
            filteredSections.forEach(section => {
                const option = document.createElement('option');
                option.value = section.id;
                option.textContent = section.name;
                sectionSelect.appendChild(option);
            });
        }

        // Initialize sections 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 if student ID already exists
            const studentIdInput = document.getElementById('student_id');
            studentIdInput.addEventListener('blur', function() {
                if (this.value.trim()) {
                    checkStudentIdExists(this.value);
                }
            });
        });

        // Function to check if student ID already exists
        function checkStudentIdExists(studentId) {
            $.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();
                    }
                },
                error: function() {
                    console.log('Error checking student ID');
                }
            });
        }
        </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>