<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';

require_admin_login();

$id = (int) get_value('id', 0);
if ($id <= 0) {
    set_flash('error', 'المعرف غير صحيح.');
    redirect_to(admin_url('admins/index.php'));
}

$stmt = $conn->prepare("
    SELECT id, full_name, username, email, phone, role, status
    FROM admins
    WHERE id = ?
    LIMIT 1
");
$stmt->bind_param('i', $id);
$stmt->execute();
$admin = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$admin) {
    set_flash('error', 'الأدمن غير موجود.');
    redirect_to(admin_url('admins/index.php'));
}

$page_title = 'تعديل الأدمن';
$errors = [];

$full_name = $admin['full_name'];
$username  = $admin['username'];
$email     = (string)$admin['email'];
$phone     = (string)$admin['phone'];
$role      = $admin['role'];
$status    = (int)$admin['status'];

if (is_post()) {
    $full_name = trim((string) post('full_name'));
    $username  = trim((string) post('username'));
    $email     = trim((string) post('email'));
    $phone     = trim((string) post('phone'));
    $password  = (string) post('password');
    $role      = trim((string) post('role', 'staff'));
    $status    = (int) post('status', 1);

    if ($full_name === '') {
        $errors[] = 'يرجى إدخال الاسم الكامل.';
    }

    if ($username === '') {
        $errors[] = 'يرجى إدخال اسم المستخدم.';
    } elseif (mb_strlen($username) < 3) {
        $errors[] = 'اسم المستخدم يجب أن يكون 3 أحرف أو أكثر.';
    }

    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'صيغة الإيميل غير صحيحة.';
    }

    if ($password !== '' && mb_strlen($password) < 6) {
        $errors[] = 'كلمة المرور الجديدة يجب أن تكون 6 أحرف أو أكثر.';
    }

    $allowed_roles = ['super_admin', 'admin', 'staff'];
    if (!in_array($role, $allowed_roles, true)) {
        $role = 'staff';
    }

    $status = $status === 1 ? 1 : 0;

    if (empty($errors)) {
        $stmt = $conn->prepare("SELECT id FROM admins WHERE username = ? AND id != ? LIMIT 1");
        $stmt->bind_param('si', $username, $id);
        $stmt->execute();
        $exists = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($exists) {
            $errors[] = 'اسم المستخدم مستخدم مسبقاً.';
        }
    }

    if (empty($errors) && $email !== '') {
        $stmt = $conn->prepare("SELECT id FROM admins WHERE email = ? AND id != ? LIMIT 1");
        $stmt->bind_param('si', $email, $id);
        $stmt->execute();
        $exists = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($exists) {
            $errors[] = 'الإيميل مستخدم مسبقاً.';
        }
    }

    if (empty($errors)) {
        if ($password !== '') {
            $password_hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $conn->prepare("
                UPDATE admins
                SET full_name = ?, username = ?, email = ?, phone = ?, password_hash = ?, role = ?, status = ?
                WHERE id = ?
            ");
            $stmt->bind_param(
                'ssssssii',
                $full_name,
                $username,
                $email,
                $phone,
                $password_hash,
                $role,
                $status,
                $id
            );
        } else {
            $stmt = $conn->prepare("
                UPDATE admins
                SET full_name = ?, username = ?, email = ?, phone = ?, role = ?, status = ?
                WHERE id = ?
            ");
            $stmt->bind_param(
                'sssssii',
                $full_name,
                $username,
                $email,
                $phone,
                $role,
                $status,
                $id
            );
        }

        if ($stmt->execute()) {
            $stmt->close();

            if ($id === current_admin_id()) {
                $_SESSION['admin_name'] = $full_name;
                $_SESSION['admin_username'] = $username;
                $_SESSION['admin_role'] = $role;
            }

            set_flash('success', 'تم تحديث بيانات الأدمن بنجاح.');
            redirect_to(admin_url('admins/index.php'));
        } else {
            $errors[] = 'حدث خطأ أثناء تحديث البيانات.';
            $stmt->close();
        }
    }
}

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<div class="topbar">
    <div>
        <h1>تعديل الأدمن</h1>
        <div class="topbar-meta">تحديث بيانات حساب الإدارة</div>
    </div>
    <div class="page-actions" style="margin-bottom:0;">
        <a href="<?= admin_url('admins/view.php?id=' . $id) ?>" class="btn btn-light">
            <i class="fa-solid fa-eye"></i>
            عرض
        </a>
        <a href="<?= admin_url('admins/index.php') ?>" class="btn btn-light">
            <i class="fa-solid fa-arrow-right"></i>
            رجوع
        </a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="flash error">
        <?php foreach ($errors as $error): ?>
            <div style="margin-bottom:6px;"><?= e($error) ?></div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<div class="card">
    <form method="post">
        <div class="form-grid">
            <div class="form-group">
                <label for="full_name">الاسم الكامل</label>
                <input type="text" id="full_name" name="full_name" value="<?= e($full_name) ?>" required>
            </div>

            <div class="form-group">
                <label for="username">اسم المستخدم</label>
                <input type="text" id="username" name="username" value="<?= e($username) ?>" required>
            </div>

            <div class="form-group">
                <label for="email">الإيميل</label>
                <input type="email" id="email" name="email" value="<?= e($email) ?>">
            </div>

            <div class="form-group">
                <label for="phone">الهاتف</label>
                <input type="text" id="phone" name="phone" value="<?= e($phone) ?>">
            </div>

            <div class="form-group">
                <label for="password">كلمة المرور الجديدة</label>
                <input type="password" id="password" name="password">
                <small style="color:#6b7280; margin-top:6px;">اتركها فارغة إذا ما تريد تغيّرها.</small>
            </div>

            <div class="form-group">
                <label for="role">الصلاحية</label>
                <select id="role" name="role" required>
                    <option value="super_admin" <?= $role === 'super_admin' ? 'selected' : '' ?>>Super Admin</option>
                    <option value="admin" <?= $role === 'admin' ? 'selected' : '' ?>>Admin</option>
                    <option value="staff" <?= $role === 'staff' ? 'selected' : '' ?>>Staff</option>
                </select>
            </div>

            <div class="form-group">
                <label for="status">الحالة</label>
                <select id="status" name="status">
                    <option value="1" <?= $status === 1 ? 'selected' : '' ?>>Active</option>
                    <option value="0" <?= $status === 0 ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
        </div>

        <div style="margin-top:20px; display:flex; gap:10px; flex-wrap:wrap;">
            <button type="submit" class="btn btn-primary">
                <i class="fa-solid fa-floppy-disk"></i>
                حفظ التعديلات
            </button>

            <a href="<?= admin_url('admins/index.php') ?>" class="btn btn-light">
                إلغاء
            </a>
        </div>
    </form>
</div>

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