<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

try {
    require_once __DIR__ . '/config/config.php';
    require_once __DIR__ . '/classes/Auth.php';
} catch (Exception $e) {
    die('خطأ في تحميل الملفات: ' . htmlspecialchars($e->getMessage()));
}

$auth = new Auth();
if (!$auth->isLoggedIn() || (!$auth->hasRole('admin') && !$auth->hasRole('college_admin') && !$auth->hasRole('registrar'))) {
    header('Location: index.php');
    exit;
}

$db = Database::getInstance();
$student_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$return_url = isset($_GET['return']) ? $_GET['return'] : 'students.php';
// تأمين رابط العودة لصفحة داخل الموقع فقط
if (strpos($return_url, 'http') === 0 || strpos($return_url, '//') === 0) {
    $return_url = 'students.php';
}
if (strpos($return_url, '?') !== false && preg_match('/[&?]id=/', $return_url) && !preg_match('/students\.php/', $return_url)) {
    $return_url = 'students.php';
}

if (!$student_id || !$auth->canAccessStudent($student_id)) {
    header('Location: ' . $return_url);
    exit;
}

$student = $db->fetchOne(
    "SELECT s.*, m.name_ar as major_name, c.name_ar as college_name
     FROM students s
     LEFT JOIN majors m ON s.major_id = m.id
     LEFT JOIN colleges c ON s.college_id = c.id
     WHERE s.id = ?",
    [$student_id]
);

if (!$student) {
    header('Location: ' . $return_url);
    exit;
}

$message = '';

// معالجة التحديث
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $full_name_ar = trim($_POST['full_name_ar'] ?? '');
    $full_name_en = trim($_POST['full_name_en'] ?? '');
    $national_id_raw = trim($_POST['national_id'] ?? '');
    $national_id = ($national_id_raw !== '') ? $national_id_raw : null;
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $college_id = (int)($_POST['college_id'] ?? $student['college_id']);
    $major_id_post = (int)($_POST['major_id'] ?? 0);
    $enrollment_date_raw = $_POST['enrollment_date'] ?? $student['enrollment_date'];
    $enrollment_ts = strtotime($enrollment_date_raw);
    $enrollment_date = ($enrollment_ts !== false) ? date('Y-m-d', $enrollment_ts) : $student['enrollment_date'];
    $graduation_date_raw = trim($_POST['graduation_date'] ?? '');
    $graduation_date = null;
    if ($graduation_date_raw !== '') {
        $gt = strtotime($graduation_date_raw);
        $graduation_date = ($gt !== false) ? date('Y-m-d', $gt) : null;
    }
    $status = in_array($_POST['status'] ?? '', ['active', 'graduated', 'suspended', 'withdrawn'])
        ? $_POST['status'] : $student['status'];

    if (empty($full_name_ar)) {
        $message = '<div class="alert alert-error">الاسم الكامل (عربي) مطلوب</div>';
    } elseif (!$auth->belongsToCollege($college_id) && !$auth->hasRole('admin')) {
        $message = '<div class="alert alert-error">ليس لديك صلاحية لتعديل طالب في هذه الكلية</div>';
    } elseif ($major_id_post <= 0) {
        $message = '<div class="alert alert-error">يجب اختيار التخصص</div>';
    } else {
        // التحقق من الرقم الوطني إذا تغير ولم يكن فارغاً (عدم التكرار مع طالب آخر)
        if ($national_id !== null) {
            $existing_nid = $db->fetchOne(
                "SELECT id FROM students WHERE national_id = ? AND national_id IS NOT NULL AND national_id != '' AND id != ?",
                [$national_id, $student_id]
            );
            if ($existing_nid) {
                $message = '<div class="alert alert-error">الرقم الوطني مسجل لطالب آخر</div>';
            }
        }
        if ($message === '') {
            try {
                $db->query(
                    "UPDATE students SET full_name_ar = ?, full_name_en = ?, national_id = ?, email = ?, phone = ?, address = ?, college_id = ?, major_id = ?, enrollment_date = ?, graduation_date = ?, status = ? WHERE id = ?",
                    [$full_name_ar, $full_name_en ?: null, $national_id, $email ?: null, $phone ?: null, $address ?: null, $college_id, $major_id_post, $enrollment_date, $graduation_date, $status, $student_id]
                );
                // تحديث بيانات المستخدم المرتبط (الاسم والبريد)
                if (!empty($student['user_id'])) {
                    $db->query(
                        "UPDATE users SET full_name_ar = ?, full_name_en = ?, email = ? WHERE id = ?",
                        [$full_name_ar, $full_name_en ?: null, $email ?: null, $student['user_id']]
                    );
                }
                require_once __DIR__ . '/classes/ActivityLogger.php';
                $logger = new ActivityLogger();
                $logger->log('update', 'student', $student_id, 'تعديل بيانات الطالب: ' . $full_name_ar . ' (الرقم الجامعي: ' . $student['student_number'] . ')');
                $message = '<div class="alert alert-success">تم تحديث بيانات الطالب بنجاح</div>';
                $student = $db->fetchOne(
                    "SELECT s.*, m.name_ar as major_name, c.name_ar as college_name FROM students s LEFT JOIN majors m ON s.major_id = m.id LEFT JOIN colleges c ON s.college_id = c.id WHERE s.id = ?",
                    [$student_id]
                );
            } catch (PDOException $e) {
                $message = '<div class="alert alert-error">خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>';
            }
        }
    }
}

// جلب الكليات والتخصصات
if ($auth->hasRole('admin')) {
    $colleges = $db->fetchAll("SELECT * FROM colleges ORDER BY name_ar");
    $majors = $db->fetchAll("SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar", [$student['college_id']]);
} else {
    $college_id = $_SESSION['college_id'] ?? 0;
    $college_name = $_SESSION['college_name'] ?? 'غير محدد';
    $colleges = [['id' => $college_id, 'name_ar' => $college_name]];
    $majors = $db->fetchAll("SELECT * FROM majors WHERE college_id = ? ORDER BY name_ar", [$college_id]);
}
?>
<!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>
    <?php include __DIR__ . '/includes/compatibility.php'; ?>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/header.php'; ?>

    <div class="container">
        <div class="page-header">
            <h2>تعديل الطالب</h2>
            <div>
                <a href="<?php echo htmlspecialchars($return_url); ?>" class="btn btn-secondary">العودة</a>
                <a href="student_details.php?id=<?php echo $student_id; ?>" class="btn btn-primary">التفاصيل</a>
            </div>
        </div>

        <?php echo $message; ?>

        <div class="card">
            <div class="card-header">
                <h3>تعديل بيانات الطالب (الرقم الجامعي: <?php echo htmlspecialchars($student['student_number']); ?>)</h3>
            </div>
            <form method="POST" style="padding: 20px;">
                <input type="hidden" name="action" value="update">
                <div class="form-group">
                    <label>الرقم الجامعي</label>
                    <input type="text" value="<?php echo htmlspecialchars($student['student_number']); ?>" disabled style="background:#eee;">
                    <small style="color:#666;">لا يمكن تغيير الرقم الجامعي</small>
                </div>
                <div class="form-group">
                    <label>الرقم الوطني</label>
                    <input type="text" name="national_id" value="<?php echo htmlspecialchars($student['national_id'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>الاسم الكامل (عربي) *</label>
                    <input type="text" name="full_name_ar" value="<?php echo htmlspecialchars($student['full_name_ar']); ?>" required>
                </div>
                <div class="form-group">
                    <label>الاسم الكامل (إنجليزي)</label>
                    <input type="text" name="full_name_en" value="<?php echo htmlspecialchars($student['full_name_en'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>البريد الإلكتروني</label>
                    <input type="email" name="email" value="<?php echo htmlspecialchars($student['email'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>الهاتف</label>
                    <input type="text" name="phone" value="<?php echo htmlspecialchars($student['phone'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>العنوان</label>
                    <input type="text" name="address" value="<?php echo htmlspecialchars($student['address'] ?? ''); ?>">
                </div>
                <?php if ($auth->hasRole('admin')): ?>
                <div class="form-group">
                    <label>الكلية</label>
                    <select name="college_id" id="edit_college_id" required onchange="loadMajorsEdit()">
                        <?php foreach ($colleges as $c): ?>
                            <option value="<?php echo (int)$c['id']; ?>"<?php echo ($student['college_id'] == $c['id']) ? ' selected' : ''; ?>><?php echo htmlspecialchars($c['name_ar']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php else: ?>
                    <input type="hidden" name="college_id" id="edit_college_id" value="<?php echo (int)$student['college_id']; ?>">
                <?php endif; ?>
                <div class="form-group">
                    <label>التخصص *</label>
                    <select name="major_id" id="edit_major_id" required <?php echo $auth->hasRole('admin') ? '' : ''; ?>>
                        <?php foreach ($majors as $m): ?>
                            <option value="<?php echo (int)$m['id']; ?>"<?php echo ($student['major_id'] == $m['id']) ? ' selected' : ''; ?>><?php echo htmlspecialchars($m['name_ar']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>تاريخ التسجيل</label>
                    <input type="date" name="enrollment_date" value="<?php echo htmlspecialchars($student['enrollment_date']); ?>" required>
                </div>
                <div class="form-group">
                    <label>تاريخ التخرج (اختياري)</label>
                    <input type="date" name="graduation_date" value="<?php echo !empty($student['graduation_date']) ? htmlspecialchars($student['graduation_date']) : ''; ?>">
                </div>
                <div class="form-group">
                    <label>الحالة</label>
                    <select name="status">
                        <?php
                        $statuses = ['active' => 'نشط', 'graduated' => 'متخرج', 'suspended' => 'معلق', 'withdrawn' => 'منسحب'];
                        foreach ($statuses as $val => $label):
                        ?>
                            <option value="<?php echo $val; ?>"<?php echo ($student['status'] === $val) ? ' selected' : ''; ?>><?php echo $label; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-success">حفظ التعديلات</button>
                <a href="<?php echo htmlspecialchars($return_url); ?>" class="btn btn-secondary">إلغاء</a>
            </form>
        </div>
    </div>

    <script>
    function loadMajorsEdit() {
        var collegeId = document.getElementById('edit_college_id').value;
        var majorSelect = document.getElementById('edit_major_id');
        if (!collegeId) {
            majorSelect.innerHTML = '<option value="">-- اختر الكلية أولاً --</option>';
            return;
        }
        majorSelect.innerHTML = '<option value="">-- جاري التحميل --</option>';
        fetch('students.php?action=get_majors&college_id=' + collegeId)
            .then(function(r) { return r.json(); })
            .then(function(data) {
                majorSelect.innerHTML = '<option value="">اختر التخصص</option>';
                data.forEach(function(m) {
                    var opt = document.createElement('option');
                    opt.value = m.id;
                    opt.textContent = m.name_ar;
                    majorSelect.appendChild(opt);
                });
            })
            .catch(function() {
                majorSelect.innerHTML = '<option value="">خطأ في تحميل التخصصات</option>';
            });
    }
    </script>
    <?php include 'includes/footer.php'; ?>
</body>
</html>
