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

// Generate CSRF token if not exists
csrf_token();

$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;

// Validate and sanitize student_id
$student_id = $_GET['student_id'] ?? '';
$student_id = trim($student_id);

if (empty($student_id)) {
    die("Error: No student ID provided");
}

// Validate student_id format using preg_match directly (without external function)
if (!preg_match('/^[a-zA-Z0-9_-]+$/', $student_id)) {
    error_log("Invalid student_id format attempted: " . $student_id);
    die("Error: Invalid student ID format");
}

// Check if committee has access to this student using prepared statement
$accessCheck = $mysqli1->prepare("SELECT s.college_id FROM students s WHERE s.student_id = ?");
if (!$accessCheck) {
    error_log("Prepare failed: " . $mysqli1->error);
    die("Database error occurred");
}

$accessCheck->bind_param("s", $student_id);
$accessCheck->execute();
$studentData = $accessCheck->get_result()->fetch_assoc();
$accessCheck->close();

if (!$studentData) {
    die("Error: Student not found");
}

// Check access permissions using committee_scope()
$scope = committee_scope();
if (!$scope['can_all'] && $scope['college_id'] !== null && (int)$studentData['college_id'] !== $scope['college_id']) {
    die("Error: You don't have permission to access this student's profile");
}

// Get complete student data with specialization
$stmt = $mysqli1->prepare("
    SELECT 
        s.*,
        c.name AS college_name,
        p.name AS program_name,
        sec.name AS section_name,
        sp.specialization_name_ar AS specialization_name,
        sp.specialization_id AS specialization_id
    FROM students s
    LEFT JOIN colleges c ON s.college_id = c.id
    LEFT JOIN programs p ON s.program_id = p.id
    LEFT JOIN sections sec ON s.section_id = sec.id
    LEFT JOIN specializations sp ON s.specialization_id = sp.specialization_id
    WHERE s.student_id = ?
");

if (!$stmt) {
    error_log("Prepare failed: " . $mysqli1->error);
    die("Database error occurred");
}

$stmt->bind_param("s", $student_id);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$data) {
    die("Error: Student data not found");
}

// Get dropdown data with prepared statements
$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);
$colleges_stmt->close();

$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);
$programs_stmt->close();

// Get ALL sections 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);
$all_sections_stmt->close();

// 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);
$batches_stmt->close();

// Fetch admissions types from database
$admissions_stmt = $mysqli1->prepare("SELECT id, name FROM admissions ORDER BY id");
$admissions_stmt->execute();
$admissions = $admissions_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$admissions_stmt->close();

// Get specializations for the current section and program
$specializations = [];
if (!empty($data['section_id']) && !empty($data['program_id'])) {
    $spec_stmt = $mysqli1->prepare("
        SELECT specialization_id, specialization_name_ar 
        FROM specializations 
        WHERE section_id = ? AND program_id = ? AND deleted_at IS NULL 
        ORDER BY specialization_name_ar
    ");
    if ($spec_stmt) {
        $spec_stmt->bind_param("ii", $data['section_id'], $data['program_id']);
        $spec_stmt->execute();
        $specializations = $spec_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $spec_stmt->close();
    }
}

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">
    <!-- Cairo Font -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <?php base_head_css(); ?>
    <style>
        body, h1, h2, h3, h4, h5, h6, p, a, button, label { 
            font-family: 'Cairo', 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-field::after {
            content: " *";
            color: #dc2626;
        }
        .specialization-badge {
            background-color: #f59e0b;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            display: inline-block;
        }
        /* تغيير لون نص الأزرار إلى الأسود */
.btn-secondary, .btn-primary {
    color: #000000 !important;
}

/* للحفاظ على تأثير hover الافتراضي */
.btn-secondary:hover, .btn-primary:hover {
    color: #ffffff !important; /* أو أي لون تريده عند المرور */
}
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- CSRF Token -->
        <input type="hidden" id="csrf_token" value="<?= e($_SESSION['csrf'] ?? '') ?>">
        
        <!-- 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="student_profile_admin.php?student_id=<?= urlencode($student_id) ?>&csrf=<?= urlencode($_SESSION['csrf'] ?? '') ?>">
                    <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">
                <?= e($_SESSION['success_message']) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
        <?php endif; ?>

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

        <!-- Edit Student Form -->
        <div class="card card-arabic p-4" dir="rtl">
            <h4 class="rtl-heading mb-4">بيانات الطالب الأساسية</h4>
            
            <form action="update_student_admin.php" method="POST" class="needs-validation" novalidate>
                <input type="hidden" name="csrf" value="<?= e($_SESSION['csrf'] ?? '') ?>">
                <input type="hidden" name="student_id" value="<?= e($student_id ?? '') ?>">
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">رقم الطالب</label>
                            <input type="text" class="form-control" value="<?= e(formatStudentId($data['student_id'] ?? '')) ?>" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label required-field">الاسم بالعربية</label>
                            <input type="text" class="form-control" name="student_name" value="<?= e($data['student_name'] ?? '') ?>" required maxlength="255">
                            <div class="invalid-feedback">
                                الرجاء إدخال الاسم بالعربية
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الاسم بالإنجليزية</label>
                            <input type="text" class="form-control" name="student_name_eng" value="<?= e($data['student_name_eng'] ?? '') ?>" maxlength="255">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">البريد الإلكتروني</label>
                            <input type="email" class="form-control" name="email" value="<?= e($data['email'] ?? '') ?>" maxlength="255">
                            <div class="invalid-feedback">
                                الرجاء إدخال بريد إلكتروني صحيح
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم الهاتف</label>
                            <input type="text" class="form-control" name="phone_number" value="<?= e($data['phone_number'] ?? '') ?>" pattern="[0-9+\-\s]+" maxlength="50">
                            <div class="invalid-feedback">
                                الرجاء إدخال رقم هاتف صحيح
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم الهاتف البديل</label>
                            <input type="text" class="form-control" name="phone_number2" value="<?= e($data['phone_number2'] ?? '') ?>" pattern="[0-9+\-\s]+" maxlength="50">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label required-field">الكلية</label>
                            <select class="form-select" name="college_id" id="college_id" required onchange="loadSections()">
                                <option value="">اختر الكلية</option>
                                <?php foreach ($colleges as $college): ?>
                                    <option value="<?= (int)($college['id'] ?? 0) ?>" <?= ($data['college_id'] ?? '') == $college['id'] ? 'selected' : '' ?>>
                                        <?= e($college['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback">
                                الرجاء اختيار الكلية
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label required-field">البرنامج</label>
                            <select class="form-select" name="program_id" id="program_id" required>
                                <option value="">اختر البرنامج</option>
                                <?php foreach ($programs as $program): ?>
                                    <option value="<?= (int)($program['id'] ?? 0) ?>" <?= ($data['program_id'] ?? '') == $program['id'] ? 'selected' : '' ?>>
                                        <?= e($program['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback">
                                الرجاء اختيار البرنامج
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label required-field">القسم</label>
                            <select class="form-select" name="section_id" id="section_id" required>
                                <option value="">اختر القسم</option>
                                <!-- Sections will be populated by JavaScript -->
                                <?php foreach ($all_sections as $section): ?>
                                    <?php if ($section['parent'] == ($data['college_id'] ?? '')): ?>
                                        <option value="<?= (int)($section['id'] ?? 0) ?>" <?= ($data['section_id'] ?? '') == $section['id'] ? 'selected' : '' ?>>
                                            <?= e($section['name'] ?? '') ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback">
                                الرجاء اختيار القسم
                            </div>
                        </div>
                        
                        <!-- New Specialization Field -->
                        <div class="mb-3">
                            <label class="form-label">التخصص</label>
                            <select class="form-select" name="specialization_id" id="specialization_id">
                                <option value="">اختر التخصص (اختياري)</option>
                                <?php foreach ($specializations as $spec): ?>
                                    <option value="<?= (int)($spec['specialization_id'] ?? 0) ?>" <?= ($data['specialization_id'] ?? '') == $spec['specialization_id'] ? 'selected' : '' ?>>
                                        <?= e($spec['specialization_name_ar'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">اختر التخصص إذا كان متاحاً للقسم والبرنامج المحددين</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label required-field">الدفعة</label>
                            <select class="form-select" name="batch_id" required>
                                <option value="">اختر الدفعة</option>
                                <?php foreach ($batches as $batch): ?>
                                    <option value="<?= (int)($batch['id'] ?? 0) ?>" <?= ($data['batch_id'] ?? '') == $batch['id'] ? 'selected' : '' ?>>
                                        <?= e($batch['value'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback">
                                الرجاء اختيار الدفعة
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label required-field">نوع القبول</label>
                            <select class="form-select" name="admission_id" required>
                                <option value="">اختر نوع القبول</option>
                                <?php foreach ($admissions as $admission): ?>
                                    <option value="<?= (int)($admission['id'] ?? 0) ?>" <?= ($data['admission_id'] ?? '') == $admission['id'] ? 'selected' : '' ?>>
                                        <?= e($admission['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="invalid-feedback">
                                الرجاء اختيار نوع القبول
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label required-field">الجنس</label>
                            <div>
                                <?php
                                $gender = isset($data['gender']) ? (int)$data['gender'] : 0;
                                ?>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="radio" name="gender" id="gender_male" value="1" 
                                        <?= $gender === 1 ? 'checked' : '' ?> required>
                                    <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"
                                        <?= $gender === 2 ? 'checked' : '' ?>>
                                    <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"
                                        <?= $gender === 0 || $gender === null ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="gender_unknown">غير محدد</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="d-flex justify-content-end gap-2">
                            <a href="student_profile_admin.php?student_id=<?= urlencode($student_id ?? '') ?>&csrf=<?= urlencode($_SESSION['csrf'] ?? '') ?>" class="btn btn-secondary" >رجوع</a>
                            <button type="submit" class="btn btn-primary"  >
                                <i class="fas fa-save me-2"></i>حفظ التغييرات
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <script>
        // Store all sections data for filtering
        const allSections = <?= json_encode($all_sections, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
        const currentSectionId = <?= $data['section_id'] ?? 'null' ?>;
        const currentProgramId = <?= $data['program_id'] ?? 'null' ?>;
        const currentCollegeId = <?= $data['college_id'] ?? 'null' ?>;

        function loadSections() {
            const collegeId = document.getElementById('college_id').value;
            const sectionSelect = document.getElementById('section_id');
            const specSelect = document.getElementById('specialization_id');
            
            if (!collegeId) {
                sectionSelect.innerHTML = '<option value="">اختر القسم</option>';
                specSelect.innerHTML = '<option value="">اختر التخصص (اختياري)</option>';
                return;
            }
            
            // 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;
                // Set selected if this was the original section
                if (section.id == currentSectionId && collegeId == currentCollegeId) {
                    option.selected = true;
                }
                sectionSelect.appendChild(option);
            });
            
            // Clear specialization dropdown
            specSelect.innerHTML = '<option value="">اختر التخصص (اختياري)</option>';
        }

        function loadSpecializations() {
            const sectionId = document.getElementById('section_id').value;
            const programId = document.getElementById('program_id').value;
            const specSelect = document.getElementById('specialization_id');
            
            if (!sectionId || !programId) {
                specSelect.innerHTML = '<option value="">اختر التخصص (اختياري)</option>';
                return;
            }

            // Fetch specializations via AJAX
            fetch(`ajax/get_specializations.php?section_id=${encodeURIComponent(sectionId)}&program_id=${encodeURIComponent(programId)}`)
                .then(response => response.json())
                .then(data => {
                    specSelect.innerHTML = '<option value="">اختر التخصص (اختياري)</option>';
                    
                    if (Array.isArray(data) && data.length > 0) {
                        data.forEach(spec => {
                            const option = document.createElement('option');
                            option.value = spec.specialization_id;
                            option.textContent = spec.specialization_name_ar;
                            // Set selected if this was the original specialization
                            if (spec.specialization_id == <?= $data['specialization_id'] ?? 'null' ?>) {
                                option.selected = true;
                            }
                            specSelect.appendChild(option);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading specializations:', error);
                    specSelect.innerHTML = '<option value="">اختر التخصص (اختياري)</option>';
                });
        }

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            // Form validation
            'use strict';
            
            // Fetch all the forms we want to apply custom Bootstrap validation styles to
            var forms = document.querySelectorAll('.needs-validation');
            
            // Loop over them and prevent submission
            Array.prototype.slice.call(forms).forEach(function(form) {
                form.addEventListener('submit', function(event) {
                    if (!form.checkValidity()) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                }, false);
            });
            
            // Add event listeners for section and program changes to load specializations
            document.getElementById('section_id').addEventListener('change', loadSpecializations);
            document.getElementById('program_id').addEventListener('change', loadSpecializations);
            
            // Load specializations if both section and program are selected
            if (document.getElementById('section_id').value && document.getElementById('program_id').value) {
                loadSpecializations();
            }
        });
        </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>
<?php include 'footer.php'; ?>
