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

// Initialize session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Set default value for committee_role_id if not set
if (!isset($_SESSION['committee_role_id'])) {
    $_SESSION['committee_role_id'] = 2;
}

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

$student_id = $_GET['student_id'] ?? '';

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

// Check if committee has access to this student
$accessCheck = $mysqli1->prepare("SELECT s.college_id FROM students s WHERE s.student_id = ?");
$accessCheck->bind_param("s", $student_id);
$accessCheck->execute();
$studentData = $accessCheck->get_result()->fetch_assoc();

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

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

// Get complete student data
$stmt = $mysqli1->prepare("
    SELECT 
        s.*,
        c.name AS college_name,
        p.name AS program_name,
        sec.name AS section_name
    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
    WHERE s.student_id = ?
");

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

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

// Debug: Check what data we're getting
error_log("Student Data - Gender: " . ($data['gender'] ?? 'NULL') . ", Section ID: " . ($data['section_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);

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', 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;
        }
    </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_student_profile.php?student_id=<?= e($student_id) ?>">
                    <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; ?>

        <!-- Edit Student Form -->
        <div class="card card-arabic p-4">
            <h4 class="rtl-heading mb-4">بيانات الطالب الأساسية</h4>
            
            <form action="committee_update_student.php" method="POST">
                <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($data['student_id'] ?? '') ?>" readonly>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الاسم بالعربية *</label>
                            <input type="text" class="form-control" name="student_name" value="<?= e($data['student_name'] ?? '') ?>" required>
                        </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'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">البريد الإلكتروني *</label>
                            <input type="email" class="form-control" name="email" value="<?= e($data['email'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم الهاتف *</label>
                            <input type="text" class="form-control" name="phone_number" value="<?= e($data['phone_number'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">رقم الهاتف البديل</label>
                            <input type="text" class="form-control" name="phone_number2" value="<?= e($data['phone_number2'] ?? '') ?>">
                        </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" required onchange="loadSections()">
                                <option value="">اختر الكلية</option>
                                <?php foreach ($colleges as $college): ?>
                                    <option value="<?= e($college['id'] ?? '') ?>" <?= ($data['college_id'] ?? '') == $college['id'] ? 'selected' : '' ?>>
                                        <?= e($college['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">البرنامج *</label>
                            <select class="form-select" name="program_id" required>
                                <option value="">اختر البرنامج</option>
                                <?php foreach ($programs as $program): ?>
                                    <option value="<?= e($program['id'] ?? '') ?>" <?= ($data['program_id'] ?? '') == $program['id'] ? 'selected' : '' ?>>
                                        <?= 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" required>
                                <option value="">اختر القسم</option>
                                <?php foreach ($all_sections as $section): ?>
                                    <?php if ($section['parent'] == ($data['college_id'] ?? '')): ?>
                                        <option value="<?= e($section['id'] ?? '') ?>" <?= ($data['section_id'] ?? '') == $section['id'] ? 'selected' : '' ?>>
                                            <?= e($section['name'] ?? '') ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الدفعة *</label>
                            <select class="form-select" name="batch_id" required>
                                <option value="">اختر الدفعة</option>
                                <?php foreach ($batches as $batch): ?>
                                    <option value="<?= e($batch['id'] ?? '') ?>" <?= ($data['batch_id'] ?? '') == $batch['id'] ? 'selected' : '' ?>>
                                        <?= e($batch['value'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">الجنس *</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>
                
                <!-- Fees Information Card -->
                <div class="card card-arabic p-4 mt-4" dir="rtl">
                    <h4 class="rtl-heading mb-4">المعلومات المالية</h4>
                    
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">رسوم التسجيل</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" name="registration_fees" 
                                           value="<?= e($data['registration_fees'] ?? '0') ?>" 
                                           step="0.01" min="0">
                                    <span class="input-group-text">ج.س</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">رسوم البرنامج</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" name="program_fees" 
                                           value="<?= e($data['program_fees'] ?? '0') ?>" 
                                           step="0.01" min="0">
                                    <span class="input-group-text">ج.س</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">رسوم التأمين</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" name="insurance_fees" 
                                           value="<?= e($data['insurance_fees'] ?? '0') ?>" 
                                           step="0.01" min="0">
                                    <span class="input-group-text">ج.س</span>
                                </div>
                            </div>
                        </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" <?= ($data['interview_status'] ?? '') == 'pending' ? 'selected' : '' ?>>قيد الانتظار</option>
                                <option value="accepted" <?= ($data['interview_status'] ?? '') == 'accepted' ? 'selected' : '' ?>>مقبول</option>
                                <option value="rejected" <?= ($data['interview_status'] ?? '') == 'rejected' ? 'selected' : '' ?>>مرفوض</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="2" <?= ($data['medically_fit'] ?? '') == 2 ? 'selected' : '' ?>>بانتظار الفحص</option>
                                <option value="1" <?= ($data['medically_fit'] ?? '') == 1 ? 'selected' : '' ?>>لائق</option>
                                <option value="0" <?= ($data['medically_fit'] ?? '') == 0 ? 'selected' : '' ?>>غير لائق</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" <?= ($data['profile_completed'] ?? 0) == 0 ? 'selected' : '' ?>>غير مكتمل</option>
                                <option value="1" <?= ($data['profile_completed'] ?? 0) == 1 ? 'selected' : '' ?>>مكتمل</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" value="<?= e($data['nationality'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">تاريخ الميلاد</label>
                            <input type="date" class="form-control" name="date_of_birth" value="<?= e($data['date_of_birth'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">مكان الميلاد</label>
                            <input type="text" class="form-control" name="place_of_birth" value="<?= e($data['place_of_birth'] ?? '') ?>">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label">اسم الأب</label>
                            <input type="text" class="form-control" name="father_name" value="<?= e($data['father_name'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">اسم الأم</label>
                            <input type="text" class="form-control" name="mother_name" value="<?= e($data['mother_name'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">المهنة</label>
                            <input type="text" class="form-control" name="occupation" value="<?= e($data['occupation'] ?? '') ?>">
                        </div>
                    </div>
                </div>
                
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="d-flex justify-content-end gap-2">
                            <a href="committee_student_profile.php?student_id=<?= e($student_id) ?>" 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>
    </div>

    <script>
    // Store all sections data for filtering
    const allSections = <?= json_encode($all_sections) ?>;
    const currentSectionId = <?= json_encode($data['section_id'] ?? null) ?>;

    function loadSections() {
        const collegeId = document.getElementById('college_id').value;
        const sectionSelect = document.getElementById('section_id');
        
        if (!collegeId) {
            sectionSelect.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) {
                option.selected = true;
            }
            sectionSelect.appendChild(option);
        });
    }

    // Calculate total fees
    function calculateTotalFees() {
        const registrationFees = parseFloat(document.querySelector('input[name="registration_fees"]')?.value) || 0;
        const programFees = parseFloat(document.querySelector('input[name="program_fees"]')?.value) || 0;
        const insuranceFees = parseFloat(document.querySelector('input[name="insurance_fees"]')?.value) || 0;
        
        const total = registrationFees + programFees + insuranceFees;
        console.log('Total fees:', total);
    }

    // Initialize when page loads
    document.addEventListener('DOMContentLoaded', function() {
        // Calculate initial total
        calculateTotalFees();
        
        // Add event listeners for fee inputs
        const feeInputs = document.querySelectorAll('input[name="registration_fees"], input[name="program_fees"], input[name="insurance_fees"]');
        feeInputs.forEach(input => {
            input.addEventListener('input', calculateTotalFees);
        });
    });
    </script>

    <!-- 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>
