<?php
session_start();

// --- نظام جلب اللغة (عربي، تركي، إنجليزي) ---
$current_lang = $_SESSION['lang'] ?? 'ar';
$lang_file = "../languages/" . $current_lang . ".php";
$translations = file_exists($lang_file) ? include($lang_file) : [];

// ✅ التحقق من تسجيل الدخول
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// قائمة الـ 195 دولة (نفس القائمة في صفحة الإضافة)
$all_nationalities = [
    "أردني", "فلسطيني", "سوري", "عراقي", "لبناني", "مصري", "سعودي", "إماراتي", "كويتي", "قطري", "بحريني", "عماني", "يمني", "ليبي", "تونسي", "جزائري", "مغربي", "سوداني", "صومالي", "موريتاني", "جيبوتي", "جزر القمر",
    "تركي", "أفغاني", "ألباني", "ألماني", "أندوري", "أنغولي", "أنتيجوا وباربودا", "أرجنتيني", "أرميني", "أسترالي", "نمساوي", "أذربيجاني", "باهامي", "بنغلاديشي", "باربادوسي", "بيلاروسي", "بلجيكي", "بليزي", "بنيني", "بوتاني", "بوليفي", "بوسني", "بوتسواني", "برازيلي", "بريطاني", "بروني", "بلغاري", "بوركينا فاسو", "بوروندي", "كابو فيردي", "كمبودي", "كاميروني", "كندي", "وسط أفريقي", "تشادي", "تشيلي", "صيني", "كولومبي", "كونغولي", "كوستاريكي", "كرواتي", "كوبي", "قبرصي", "تشيكي", "دنماركي", "دومينيكي", "إكوادوري", "سلفادوري", "غيني استوائي", "إريتري", "إستوني", "إسواتيني", "إثيوبي", "فيجي", "فنلندي", "فرنسي", "غابوني", "غامبي", "جورجي", "غاني", "يوناني", "غرينادي", "غواتيمالي", "غيني", "غينيا بيساو", "غياني", "هايتي", "هندوراسي", "مجري", "آيسلندي", "هندي", "إندونيسي", "إيراني", "إيرلندي", "إيطالي", "إيفواري", "جامايكي", "ياباني", "كازاخستاني", "كيني", "كيريباتي", "كوري شمالي", "كوري جنوبي", "كوسوفي", "قيرغيزستاني", "لاوسي", "لاتفي", "ليبيري", "ليختنشتاين", "ليتواني", "لوكسمبورغي", "مدغشقري", "ملاوي", "ماليزي", "مالديفي", "مالي", "مالطي", "مارشالي", "مكسيكي", "ميكرونيزي", "مولدوفي", "موناكي", "منغولي", "منتنيغري", "موزمبيقي", "ميانماري", "ناميبي", "ناورو", "نيبالي", "هولندي", "نيوزيلندي", "نيكاراغوي", "نيجري", "نيجيري", "مقدوني", "نرويجي", "باكستاني", "بالاوي", "بنماني", "بابوا غينيا الجديدة", "باراغواياني", "بيروفي", "فلبيني", "بولندي", "برتغالي", "روماني", "روسي", "رواندي", "سانت كيتس ونيفيس", "سانت لوسيا", "سانت فينسنت", "ساموا", "سان مارينو", "ساو تومي وبرينسيب", "سنغالي", "صربي", "سيشلي", "سيراليوني", "سنغافوري", "سلوفاكي", "سلوفيني", "سليماني", "جنوب أفريقي", "إسباني", "سريلانكي", "سورينامي", "سويدي", "سويسري", "طاجيكستاني", "تنزاني", "تايلاندي", "تيموري", "توغولي", "تونغي", "ترينيدادي", "تركمانستاني", "توفالي", "أوغندي", "أوكراني", "أمريكي", "أوروغواياني", "أوزبكستاني", "فانواتي", "فنزويلي", "فيتنامي", "زامبي", "زيمبابوي"
];

// التحقق من معرف الطالب
$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
    header('Location: list.php?error=invalid_id');
    exit;
}

$error = '';
$success = '';

// جلب بيانات الطالب الحالية
try {
    $stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$id]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$student) {
        header('Location: list.php?error=not_found');
        exit;
    }
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

// جلب قائمة المسوقين
$marketers = [];
try {
    $stmt = $conn->query("SELECT id, name FROM marketers ORDER BY name ASC");
    $marketers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name             = trim($_POST['full_name'] ?? '');
    $phone                 = trim($_POST['phone'] ?? '');
    $guardian_phone        = trim($_POST['guardian_phone'] ?? '');
    $national_id           = trim($_POST['national_id'] ?? '');
    $nationality           = $_POST['nationality'] ?? '';
    $email                 = trim($_POST['email'] ?? '');
    $gender                = $_POST['gender'] ?? null;
    $birth_date            = $_POST['birth_date'] ?? null;
    $address               = trim($_POST['address'] ?? '');
    $address_details       = trim($_POST['address_details'] ?? '');
    $study_system          = trim($_POST['study_system'] ?? '');
    $marketing_source_name = trim($_POST['marketing_source'] ?? ''); 
    $marketer_id           = null;

    if ($marketing_source_name !== '') {
        $found = false;
        foreach ($marketers as $m) {
            if ($m['name'] === $marketing_source_name) {
                $marketer_id = $m['id'];
                $found = true;
                break;
            }
        }
        if (!$found) { $marketing_source_name = null; }
    } else {
        $marketing_source_name = null;
    }
    
    // التحقق من صحة البيانات
    if ($full_name === '') {
        $error = $translations['error_name_required'] ?? "Name required";
    } elseif ($phone === '') {
        $error = $translations['error_phone_required'] ?? "Phone required";
    } elseif (!preg_match('/^[0-9]{10}$/', $phone)) {
        $error = $translations['error_phone_10_digits'] ?? "Phone must be 10 digits";
    } 
    elseif ($national_id !== '' && !preg_match('/^[0-9]{5,15}$/', $national_id)) {
        $error = $translations['error_national_id_invalid'] ?? "Invalid national ID";
    } elseif ($birth_date !== null && $birth_date !== '' && strtotime($birth_date) > time()) {
        $error = $translations['error_future_date'] ?? "Date cannot be in future";
    }

    if ($error === '' && $national_id !== '') {
        $stmtCheck = $conn->prepare("SELECT id FROM students WHERE national_id = ? AND id != ?");
        $stmtCheck->execute([$national_id, $id]);
        if ($stmtCheck->fetch(PDO::FETCH_ASSOC)) {
            $error = ($translations['error_national_id_exists'] ?? "National ID exists: ") . $national_id;
        }
    }

    if ($error === '') {
        try {
            $stmt = $conn->prepare("
                UPDATE students SET 
                full_name = ?, phone = ?, guardian_phone = ?, national_id = ?, nationality = ?, email = ?, gender = ?, birth_date = ?, 
                address = ?, address_details = ?, study_system = ?, marketing_source = ?, marketer_id = ?
                WHERE id = ?
            ");
            $updated = $stmt->execute([
                $full_name, $phone, $guardian_phone ?: null, $national_id ?: null, $nationality,
                $email ?: null, $gender ?: null, $birth_date ?: null, $address ?: null,
                $address_details ?: null, $study_system ?: null, $marketing_source_name,
                $marketer_id, $id
            ]);

            if ($updated) {
                $success = $translations['update_success'] ?? "Updated successfully";
                $stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
                $stmt->execute([$id]);
                $student = $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                $error = $translations['update_no_changes'] ?? "No changes made";
            }
        } catch (PDOException $e) {
            $error = "DB Error: " . $e->getMessage();
        }
    }
}
?>

<?php include('../includes/header.php'); ?>
<?php include('../includes/navbar.php'); ?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

<style>
    /* تنسيق صندوق البحث ليتوافق مع الوضع الليلي والعادي */
    .choices__inner { border-radius: 0.5rem !important; min-height: 50px !important; border: 1px solid #d1d5db !important; background-color: transparent !important; }
    .dark .choices__inner { background-color: #374151 !important; border-color: #4b5563 !important; color: white !important; }
    .choices__list--dropdown { background-color: white !important; }
    .dark .choices__list--dropdown { background-color: #374151 !important; color: white !important; }
</style>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900 pb-16 font-[Cairo] flex items-center justify-center" dir="<?= ($current_lang == 'ar') ? 'rtl' : 'ltr' ?>">
    <div class="max-w-4xl mx-auto py-10 px-4 sm:px-6 lg:px-8 w-full">

        <div class="bg-white dark:bg-gray-800 shadow-2xl rounded-xl p-8 border-t-8 border-indigo-600">
            <h2 class="text-4xl font-extrabold mb-8 text-gray-800 dark:text-gray-100 text-center border-b pb-4 border-indigo-200 dark:border-indigo-900">
                <i class="fas fa-edit text-indigo-500 <?= ($current_lang == 'ar') ? 'ml-3' : 'mr-3' ?>"></i> 
                <?= ($translations['edit_student_title'] ?? 'Edit Student') . ": #" . $id ?>
            </h2>

            <?php if ($error): ?>
                <div class="mb-6 bg-red-100 dark:bg-red-900 border border-red-400 text-red-700 dark:text-red-300 rounded-lg p-4 font-semibold shadow-md flex items-center">
                    <i class="fas fa-exclamation-triangle <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?> text-xl"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php elseif ($success): ?>
                <div class="mb-6 bg-green-100 dark:bg-green-900 border border-green-400 text-green-700 dark:text-green-300 rounded-lg p-4 font-semibold shadow-md flex items-center">
                    <i class="fas fa-check-circle <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?> text-xl"></i>
                    <?= htmlspecialchars($success) ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="edit.php?id=<?= $id ?>" class="grid grid-cols-1 md:grid-cols-2 gap-8">
                
                <div class="md:col-span-2 text-2xl font-bold text-indigo-600 dark:text-indigo-400 border-b-2 border-indigo-200 dark:border-indigo-700 pb-2 mb-4">
                    <i class="fas fa-id-card <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?>"></i> <?= $translations['personal_info'] ?? 'Personal Info' ?>
                </div>
                
                <div class="form-group">
                    <label for="full_name" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_full_name'] ?? 'Full Name' ?> <span class="text-red-500">*</span></label>
                    <input type="text" id="full_name" name="full_name" required
                        value="<?= htmlspecialchars($student['full_name'] ?? '') ?>"
                        placeholder="<?= $translations['ph_full_name'] ?? 'Full Name' ?>"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>

                <div class="form-group">
                    <label for="national_id" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_national_id'] ?? 'National ID' ?> <span class="text-gray-400 text-xs">(<?= $translations['ph_optional'] ?? 'Optional' ?>)</span></label>
                    <input type="text" id="national_id" name="national_id"
                        value="<?= htmlspecialchars($student['national_id'] ?? '') ?>"
                        placeholder="<?= $translations['ph_national_id'] ?? 'National ID' ?>"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>

                <div class="form-group">
                    <label for="nationality" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_nationality'] ?? 'Nationality' ?> <span class="text-red-500">*</span></label>
                    <select id="nationality" name="nationality" required>
                        <?php foreach($all_nationalities as $nat): 
                             $key = 'nat_' . str_replace([' ', '(', ')'], '_', $nat);
                             $isSelected = (($student['nationality'] ?? '') === $nat) ? 'selected' : '';
                        ?>
                            <option value="<?= $nat ?>" <?= $isSelected ?>>
                                <?= $translations[$key] ?? $nat ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label for="gender" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_gender'] ?? 'Gender' ?> <span class="text-red-500">*</span></label>
                    <select id="gender" name="gender" required
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
                        <option value=""><?= $translations['select_option'] ?? '-- Select --' ?></option>
                        <option value="ذكر" <?= (($student['gender'] ?? '') === 'ذكر') ? 'selected' : '' ?>><?= $translations['male'] ?? 'Male' ?></option>
                        <option value="أنثى" <?= (($student['gender'] ?? '') === 'أنثى') ? 'selected' : '' ?>><?= $translations['female'] ?? 'Female' ?></option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="birth_date" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_birth_date'] ?? 'Birth Date' ?></label>
                    <input type="date" id="birth_date" name="birth_date"
                        value="<?= htmlspecialchars($student['birth_date'] ?? '') ?>"
                        max="<?= date('Y-m-d') ?>" 
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>
                
                <div class="md:col-span-2 text-2xl font-bold text-indigo-600 dark:text-indigo-400 border-b-2 border-indigo-200 dark:border-indigo-700 pb-2 mb-4 mt-6">
                    <i class="fas fa-phone-alt <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?>"></i> <?= $translations['contact_info'] ?? 'Contact' ?>
                </div>

                <div class="form-group">
                    <label for="phone" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_phone'] ?? 'Phone' ?> <span class="text-red-500">*</span></label>
                    <input type="text" id="phone" name="phone" required
                        value="<?= htmlspecialchars($student['phone'] ?? '') ?>"
                        placeholder="<?= $translations['ph_phone'] ?? 'Phone' ?>"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>
                
                <div class="form-group">
                    <label for="guardian_phone" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_guardian_phone'] ?? 'Guardian Phone' ?></label>
                    <input type="text" id="guardian_phone" name="guardian_phone"
                        value="<?= htmlspecialchars($student['guardian_phone'] ?? '') ?>"
                        placeholder="<?= $translations['ph_optional'] ?? 'Optional' ?>"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>
                
                <div class="form-group">
                    <label for="email" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_school_uni'] ?? 'University / School' ?></label>
                    <input type="text" id="email" name="email"
                        value="<?= htmlspecialchars($student['email'] ?? '') ?>"
                        placeholder="<?= $translations['ph_optional'] ?? 'Optional' ?>"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>
                
                <div class="form-group">
                    <label for="address_details" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_address_details'] ?? 'Address Details' ?></label>
                    <input type="text" id="address_details" name="address_details"
                        value="<?= htmlspecialchars($student['address_details'] ?? '') ?>"
                        placeholder="<?= $translations['ph_address_details'] ?? 'Details' ?>"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner" />
                </div>

                <div class="md:col-span-2 text-2xl font-bold text-indigo-600 dark:text-indigo-400 border-b-2 border-indigo-200 dark:border-indigo-700 pb-2 mb-4 mt-6">
                    <i class="fas fa-graduation-cap <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?>"></i> <?= $translations['study_marketing_info'] ?? 'Study Info' ?>
                </div>

                <div class="form-group">
                    <label for="address" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_branch'] ?? 'Branch' ?> <span class="text-red-500">*</span></label>
                    <select id="address" name="address" required
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
                        <option value=""><?= $translations['select_option'] ?? '-- Select --' ?></option>
                        <option value="عمان" <?= (($student['address'] ?? '') === 'عمان') ? 'selected' : '' ?>><?= $translations['branch_amman'] ?? 'Amman' ?></option>
                        <option value="اربد" <?= (($student['address'] ?? '') === 'اربد') ? 'selected' : '' ?>><?= $translations['branch_irbid'] ?? 'Irbid' ?></option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="study_system" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_study_system'] ?? 'Study System' ?> <span class="text-red-500">*</span></label>
                    <select id="study_system" name="study_system" required
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
                        <option value=""><?= $translations['select_option'] ?? '-- Select --' ?></option>
                        <option value="منتظم" <?= (($student['study_system'] ?? '') === 'منتظم') ? 'selected' : '' ?>><?= $translations['regular'] ?? 'Regular' ?></option>
                        <option value="منسحب" <?= (($student['study_system'] ?? '') === 'منسحب') ? 'selected' : '' ?>><?= $translations['withdrawn'] ?? 'Withdrawn' ?></option>
                    </select>
                </div>

                <div class="form-group md:col-span-2">
                    <label for="marketing_source" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_marketer_name'] ?? 'Marketer' ?></label>
                    <select id="marketing_source" name="marketing_source"
                        class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner">
                        <option value=""><?= $translations['select_marketer_optional'] ?? '-- Select Marketer --' ?></option>
                        <?php 
                        $current_marketer_id = $student['marketer_id'] ?? null; 
                        ?>
                        <?php foreach ($marketers as $m): ?>
                            <option value="<?= htmlspecialchars($m['name']) ?>"
                                <?= ($current_marketer_id == $m['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($m['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="md:col-span-2 flex flex-col sm:flex-row justify-between gap-4 mt-6">
                    <a href="list.php"
                        class="sm:w-1/2 w-full text-center bg-gray-300 text-gray-800 font-semibold py-3 rounded-xl hover:bg-gray-400 transition shadow-md flex items-center justify-center order-2 sm:order-1 transform hover:scale-[1.01]">
                        <i class="fas fa-arrow-<?= ($current_lang == 'ar') ? 'right' : 'left' ?> <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?>"></i> 
                        <?= $translations['back_to_list'] ?? 'Back' ?>
                    </a>
                    
                    <button type="submit"
                        class="sm:w-1/2 w-full bg-indigo-600 text-white font-bold py-3 rounded-xl hover:bg-indigo-700 transition shadow-lg transform hover:scale-[1.01] order-1 sm:order-2">
                        <i class="fas fa-sync-alt <?= ($current_lang == 'ar') ? 'ml-2' : 'mr-2' ?>"></i> 
                        <?= $translations['update_button'] ?? 'Update' ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const element = document.getElementById('nationality');
    const choices = new Choices(element, {
        searchEnabled: true,
        itemSelectText: '',
        noResultsText: "<?= $translations['search_no_results'] ?? 'No matches found' ?>",
        noChoicesText: "<?= $translations['search_no_choices'] ?? 'No choices' ?>",
        placeholder: true,
        placeholderValue: "<?= $translations['search_placeholder'] ?? 'Search...' ?>",
        searchPlaceholderValue: "<?= $translations['search_input_placeholder'] ?? 'Search...' ?>",
        shouldSort: false,
    });
});
</script>

<?php include('../includes/footer.php'); ?>