<?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');

// التحقق من معرف الطالب
$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'] ?? '');
    $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 !== '' && !preg_match('/^[0-9+\-\s]+$/', $phone)) {
        $error = $translations['error_phone_invalid'] ?? "Invalid phone";
    } elseif ($guardian_phone !== '' && !preg_match('/^[0-9+\-\s]+$/', $guardian_phone)) {
        $error = $translations['error_guardian_phone_invalid'] ?? "Invalid guardian phone";
    } 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 = ?, email = ?, gender = ?, birth_date = ?, 
                address = ?, address_details = ?, study_system = ?, marketing_source = ?, marketer_id = ?
                WHERE id = ?
            ");
            $updated = $stmt->execute([
                $full_name, $phone ?: null, $guardian_phone ?: null, $national_id ?: null,
                $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();
        }
    }
    
    if ($error !== '') {
        $student = array_merge($student, [
            'full_name' => $full_name, 'phone' => $phone, 'guardian_phone' => $guardian_phone,
            'national_id' => $national_id, 'email' => $email, 'gender' => $gender,
            'birth_date' => $birth_date, 'address' => $address, 'address_details' => $address_details,
            'study_system' => $study_system, 'marketing_source' => $marketing_source_name, 'marketer_id' => $marketer_id,
        ]);
    }
}
?>

<?php include('../includes/header.php'); ?>
<?php include('../includes/navbar.php'); ?>

<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">

<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' ?></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="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="form-group">
                    <label for="gender" class="block mb-1 font-medium text-gray-700 dark:text-gray-300"><?= $translations['label_gender'] ?? 'Gender' ?></label>
                    <select id="gender" name="gender"
                        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="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' ?></label>
                    <input type="text" id="phone" name="phone"
                        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' ?></label>
                    <select id="address" name="address"
                        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' ?></label>
                    <select id="study_system" name="study_system"
                        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>

<?php include('../includes/footer.php'); ?>