<?php
// تفعيل عرض الأخطاء للتطوير
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'تعديل بيانات الطالب';
include '../../includes/header.php';

// التحقق من الجلسة والصلاحيات
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

checkLogin();

// التحقق من صلاحية التعديل
if (!hasPermission('edit_student')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لتعديل بيانات الطلاب.';
    header('Location: index.php');
    exit();
}

$db = getDB();
$errors = [];
$success_msg = '';

// 1. التحقق من وجود المعرف (ID)
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = 'رقم الطالب غير صحيح.';
    header('Location: index.php');
    exit();
}

$student_id = (int)$_GET['id'];

// 2. جلب بيانات الطالب الحالية
$current_student = [];
try {
    $stmt_student = "SELECT * FROM students WHERE id = ? LIMIT 1";
    $result_student = $db->select($stmt_student, [$student_id]);

    if (empty($result_student)) {
        $_SESSION['error_message'] = 'الطالب غير موجود.';
        header('Location: index.php');
        exit();
    }
    $current_student = $result_student[0];
} catch (Exception $e) {
    $errors[] = 'خطأ في جلب بيانات الطالب: ' . $e->getMessage();
}

// 3. جلب القوائم المنسدلة (المحافظات، الكليات، الأقسام)
$governorates_list = [
    'بغداد', 'البصرة', 'نينوى', 'أربيل', 'السليمانية', 'دهوك', 'كركوك', 'صلاح الدين', 
    'ديالى', 'الأنبار', 'بابل', 'كربلاء المقدسة', 'النجف الأشرف', 'القادسية', 'المثنى', 
    'ذي قار', 'ميسان', 'واسط'
];

$colleges_list = [];
$departments_list = [];

try {
    $colleges_sql = "SELECT College_ID, College FROM colleges ORDER BY College ASC";
    $colleges_list = $db->select($colleges_sql);

    $dept_sql = "SELECT Departement_ID, College_ID, Departement FROM departemenets ORDER BY Departement ASC";
    $departments_list = $db->select($dept_sql);
} catch (Exception $e) {
    $errors[] = 'خطأ في جلب القوائم: ' . $e->getMessage();
}

// تهيئة البيانات للعرض (إما من البوست عند الخطأ أو من قاعدة البيانات)
$data = [
    'full_name' => $_POST['full_name'] ?? $current_student['full_name'],
    'national_id_number' => $_POST['national_id_number'] ?? $current_student['national_id_number'],
    'guardian_phone' => $_POST['guardian_phone'] ?? $current_student['guardian_phone'],
    'grade_level' => $_POST['grade_level'] ?? $current_student['grade_level'],
    'gender' => $_POST['gender'] ?? $current_student['gender'],
    'enrollment_date' => $_POST['enrollment_date'] ?? $current_student['enrollment_date'],
    'governorate' => $_POST['governorate'] ?? $current_student['address'], 
    'college_id' => $_POST['college_id'] ?? $current_student['College_ID'],
    'department_id' => $_POST['department_id'] ?? $current_student['Departement_ID'],
    'addmission' => $_POST['addmission'] ?? $current_student['addmission'],
    'Yearly_Cost' => $_POST['Yearly_Cost'] ?? $current_student['Yearly_Cost'],
    'status' => $_POST['status'] ?? $current_student['status'] // NEW: Status Field
];

// 4. معالجة طلب التعديل (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // تنظيف المدخلات
    $data['full_name'] = trim($_POST['full_name'] ?? '');
    $data['national_id_number'] = trim($_POST['national_id_number'] ?? '');
    $data['guardian_phone'] = trim($_POST['guardian_phone'] ?? '');
    $data['grade_level'] = trim($_POST['grade_level'] ?? '');
    $data['gender'] = $_POST['gender'] ?? 'male';
    $data['enrollment_date'] = $_POST['enrollment_date'] ?? date('Y-m-d');
    $data['governorate'] = trim($_POST['governorate'] ?? '');
    $data['college_id'] = trim($_POST['college_id'] ?? '');
    $data['department_id'] = trim($_POST['department_id'] ?? '');
    $data['addmission'] = trim($_POST['addmission'] ?? '');
    $data['Yearly_Cost'] = trim($_POST['Yearly_Cost'] ?? '');
    $data['status'] = isset($_POST['status']) ? (int)$_POST['status'] : 1; // NEW: Status Processing

    // التحقق من صحة البيانات
    if (empty($data['full_name'])) $errors[] = 'يرجى إدخال اسم الطالب.';
    if (empty($data['college_id'])) $errors[] = 'يرجى اختيار الكلية.';
    if (empty($data['department_id'])) $errors[] = 'يرجى اختيار القسم.';
    if (empty($data['addmission'])) $errors[] = 'يرجى اختيار نوع القبول.';

    // التحقق من تكرار الرقم الوطني (مع استثناء الطالب الحالي)
    if (!empty($data['national_id_number'])) {
        $check_sql = "SELECT id FROM students WHERE national_id_number = ? AND id != ?";
        $existing = $db->select($check_sql, [$data['national_id_number'], $student_id]);
        if (!empty($existing)) {
            $errors[] = 'الرقم الوطني مسجل لطالب آخر.';
        }
    }

    if (empty($errors)) {
        try {
            // جلب أسماء الكلية والقسم الجديدة
            $coll_res = $db->select("SELECT College FROM colleges WHERE College_ID = ? LIMIT 1", [$data['college_id']]);
            $college_name = $coll_res[0]['College'] ?? '';

            $dept_res = $db->select("SELECT Departement FROM departemenets WHERE Departement_ID = ? LIMIT 1", [$data['department_id']]);
            $dept_name = $dept_res[0]['Departement'] ?? '';

            // جملة التحديث
            $sql = "UPDATE students SET 
                    full_name = ?, 
                    national_id_number = ?, 
                    guardian_phone = ?, 
                    grade_level = ?, 
                    gender = ?, 
                    enrollment_date = ?, 
                    address = ?, 
                    College_ID = ?, 
                    College = ?, 
                    Departement_ID = ?, 
                    Departement = ?,
                    addmission = ?,
                    Yearly_Cost = ?,
                    status = ?  
                    WHERE id = ?";
            
            $params = [
                $data['full_name'],
                $data['national_id_number'],
                $data['guardian_phone'],
                $data['grade_level'],
                $data['gender'],
                $data['enrollment_date'],
                $data['governorate'],
                $data['college_id'],
                $college_name,
                $data['department_id'],
                $dept_name,
                $data['addmission'],
                $data['Yearly_Cost'] !== '' ? $data['Yearly_Cost'] : null,
                $data['status'], // Added Status Param
                $student_id
            ];

            // تنفيذ التحديث
            if (method_exists($db, 'update')) {
                $db->update($sql, $params);
            } else {
                $db->select($sql, $params); 
            }

            $_SESSION['success_message'] = 'تم تعديل بيانات الطالب بنجاح!';
            header('Location: index.php');
            exit();

        } catch (Exception $e) {
            error_log($e->getMessage());
            $errors[] = 'حدث خطأ أثناء التحديث: ' . $e->getMessage();
        }
    }
}
?>

<div class="content-area">
    <div class="page-header mb-4">
        <h2 class="page-title">تعديل بيانات الطالب</h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="../../index.php">الرئيسية</a></li>
                <li class="breadcrumb-item"><a href="index.php">الطلاب</a></li>
                <li class="breadcrumb-item active" aria-current="page">تعديل طالب</li>
            </ol>
        </nav>
    </div>

    <div class="card shadow-sm">
        <div class="card-header bg-warning text-dark">
            <h5 class="mb-0"><i class="fas fa-user-edit me-2"></i>تعديل بيانات: <?php echo htmlspecialchars($current_student['full_name']); ?></h5>
        </div>
        <div class="card-body p-4">
            
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="POST" action="">
                <div class="row g-3">
                    
                    <div class="col-12"><h6 class="text-muted border-bottom pb-2 mb-3">المعلومات الأكاديمية</h6></div>

                    <div class="col-md-6">
                        <label for="college_id" class="form-label">الكلية <span class="text-danger">*</span></label>
                        <select class="form-select" id="college_id" name="college_id" required onchange="filterDepartments()">
                            <option value="" disabled>-- اختر الكلية --</option>
                            <?php foreach ($colleges_list as $college): ?>
                                <option value="<?php echo $college['College_ID']; ?>" <?php echo ($data['college_id'] == $college['College_ID']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($college['College']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label for="department_id" class="form-label">القسم <span class="text-danger">*</span></label>
                        <select class="form-select" id="department_id" name="department_id" required>
                            <option value="" disabled>-- اختر الكلية أولاً --</option>
                            </select>
                    </div>

                    <div class="col-md-6">
                        <label for="grade_level" class="form-label">المرحلة الدراسية <span class="text-danger">*</span></label>
                        <select class="form-select" id="grade_level" name="grade_level" required>
                            <option value="" disabled>-- اختر المرحلة --</option>
                            <?php 
                            $grades = ['المرحلة الأولى', 'المرحلة الثانية', 'المرحلة الثالثة', 'المرحلة الرابعة', 'المرحلة الخامسة'];
                            foreach($grades as $grade) {
                                $selected = ($data['grade_level'] == $grade) ? 'selected' : '';
                                echo "<option value='$grade' $selected>$grade</option>";
                            }
                            ?>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label for="addmission" class="form-label">نوع القبول <span class="text-danger">*</span></label>
                        <select class="form-select" id="addmission" name="addmission" required>
                            <option value="" disabled>-- اختر نوع القبول --</option>
                            <option value="صباحي" <?php echo ($data['addmission'] == 'صباحي') ? 'selected' : ''; ?>>صباحي</option>
                            <option value="مسائي" <?php echo ($data['addmission'] == 'مسائي') ? 'selected' : ''; ?>>مسائي</option>
                            <option value="صباحي\شهداء" <?php echo ($data['addmission'] == 'صباحي\شهداء') ? 'selected' : ''; ?>>صباحي\شهداء</option>
                            <option value="مسائي\شهداء" <?php echo ($data['addmission'] == 'مسائي\شهداء') ? 'selected' : ''; ?>>مسائي\شهداء</option>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label for="Yearly_Cost" class="form-label">التكلفة السنوية</label>
                        <input type="number" class="form-control" id="Yearly_Cost" name="Yearly_Cost" value="<?php echo htmlspecialchars($data['Yearly_Cost']); ?>" placeholder="0">
                    </div>

                    <div class="col-md-6">
                        <label for="enrollment_date" class="form-label">تاريخ التسجيل</label>
                        <input type="date" class="form-control" id="enrollment_date" name="enrollment_date" value="<?php echo htmlspecialchars($data['enrollment_date']); ?>">
                    </div>

                    <div class="col-md-12">
                        <label for="status" class="form-label">حالة الطالب</label>
                        <select class="form-select" id="status" name="status">
                            <option value="1" <?php echo ($data['status'] == 1) ? 'selected' : ''; ?>>نشط / مستمر</option>
                            <option value="0" <?php echo ($data['status'] == 0) ? 'selected' : ''; ?>>منقطع / مؤجل</option>
                        </select>
                    </div>

                    <div class="col-12 mt-4"><h6 class="text-muted border-bottom pb-2 mb-3">المعلومات الشخصية</h6></div>

                    <div class="col-md-6">
                        <label for="full_name" class="form-label">الاسم الكامل <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="full_name" name="full_name" value="<?php echo htmlspecialchars($data['full_name']); ?>" required>
                    </div>

                    <div class="col-md-6">
                        <label for="national_id_number" class="form-label">الرقم الوطني / الهوية</label>
                        <input type="text" class="form-control" id="national_id_number" name="national_id_number" value="<?php echo htmlspecialchars($data['national_id_number']); ?>">
                    </div>

                    <div class="col-md-6">
                        <label for="gender" class="form-label">الجنس</label>
                        <select class="form-select" id="gender" name="gender">
                            <option value="male" <?php echo ($data['gender'] == 'male') ? 'selected' : ''; ?>>ذكر</option>
                            <option value="female" <?php echo ($data['gender'] == 'female') ? 'selected' : ''; ?>>أنثى</option>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label for="guardian_phone" class="form-label">رقم الهاتف</label>
                        <input type="text" class="form-control" id="guardian_phone" name="guardian_phone" value="<?php echo htmlspecialchars($data['guardian_phone']); ?>">
                    </div>

                    <div class="col-md-12">
                        <label for="governorate" class="form-label">المحافظة (السكن)</label>
                        <select class="form-select" id="governorate" name="governorate">
                            <option value="" disabled>-- اختر المحافظة --</option>
                            <?php foreach ($governorates_list as $gov): ?>
                                <option value="<?php echo $gov; ?>" <?php echo ($data['governorate'] == $gov) ? 'selected' : ''; ?>>
                                    <?php echo $gov; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                </div>

                <div class="mt-4 d-flex justify-content-end gap-2">
                    <a href="index.php" class="btn btn-secondary">إلغاء</a>
                    <button type="submit" class="btn btn-primary px-4"><i class="fas fa-save me-2"></i>حفظ التعديلات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const allDepartments = <?php echo json_encode($departments_list); ?>;
    const selectedDeptId = "<?php echo $data['department_id']; ?>";

    function filterDepartments() {
        const collegeSelect = document.getElementById('college_id');
        const departmentSelect = document.getElementById('department_id');
        const selectedCollegeId = collegeSelect.value;

        departmentSelect.innerHTML = '<option value="" disabled selected>-- اختر القسم --</option>';

        if (selectedCollegeId) {
            const filteredDepts = allDepartments.filter(dept => dept.College_ID == selectedCollegeId);

            if (filteredDepts.length > 0) {
                filteredDepts.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept.Departement_ID;
                    option.textContent = dept.Departement;
                    if (dept.Departement_ID == selectedDeptId) {
                        option.selected = true;
                    }
                    departmentSelect.appendChild(option);
                });
            } else {
                const option = document.createElement('option');
                option.textContent = "لا توجد أقسام لهذه الكلية";
                option.disabled = true;
                departmentSelect.appendChild(option);
            }
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        if (document.getElementById('college_id').value) {
            filterDepartments();
        }
    });
</script>

<?php include '../../includes/footer.php'; ?>