<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();

$db = getDB();

$id = (int)($_GET['id'] ?? 0);

$stmt = $db->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute([$id]);

$user = $stmt->fetch();

if (!$user) {
    die("User not found");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name   = sanitize($_POST['name']);
    $email  = sanitizeEmail($_POST['email']);
    $mobile = sanitize($_POST['mobile']);
    $status = (int)$_POST['status'];

    $update = $db->prepare("UPDATE users 
    SET name=?, email=?, mobile=?, status=? 
    WHERE id=?");

    $update->execute([
        $name,
        $email,
        $mobile,
        $status,
        $id
    ]);

    setAdminFlash('success', 'User updated successfully');

 header("Location: " . SITE_URL . "/admin/users.php");
    exit;
}

adminHead('Edit User');
adminSidebar('users');
?>

<div class="adm-main">

<?php adminTopbar('Edit User'); ?>

<div class="adm-content">

<div class="adm-card" style="max-width:700px;">

<form method="POST">

<div style="margin-bottom:15px;">
<label class="lbl">Full Name</label>
<input type="text" 
       name="name" 
       class="form-ctrl" 
       value="<?= htmlspecialchars($user['name']) ?>" 
       required>
</div>

<div style="margin-bottom:15px;">
<label class="lbl">Email</label>
<input type="email" 
       name="email" 
       class="form-ctrl" 
       value="<?= htmlspecialchars($user['email']) ?>" 
       required>
</div>

<div style="margin-bottom:15px;">
<label class="lbl">Mobile</label>
<input type="text" 
       name="mobile" 
       class="form-ctrl" 
       value="<?= htmlspecialchars($user['mobile']) ?>" 
       required>
</div>

<div style="margin-bottom:20px;">
<label class="lbl">Status</label>

<select name="status" class="form-ctrl">

<option value="1" <?= $user['status']==1 ? 'selected' : '' ?>>
    Active
</option>

<option value="0" <?= $user['status']==0 ? 'selected' : '' ?>>
    Inactive
</option>

</select>
</div>

<button type="submit" class="btn-gold">
    Update User
</button>

<a href="<?= SITE_URL ?>/admin/users.php"
   style="
   margin-left:10px;
   text-decoration:none;
   padding:10px 16px;
   background:#eee;
   border-radius:8px;
   color:#333;
   font-weight:600;">
   Cancel
</a>

</form>

</div>
</div>
</div>

<?php adminFoot(); ?>