<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('users.manage');

require_once __DIR__ . '/../config/database.php';

$userId = (int)$_GET['id'];

/* Fetch user */
$stmt = $pdo->prepare("
    SELECT u.*, r.name AS role_name 
    FROM users u
    JOIN roles r ON u.role_id = r.id
    WHERE u.id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

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

/* Fetch roles */
$roles = $pdo->query("SELECT * FROM roles ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

/* Handle update */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $full_name = trim($_POST['full_name']);
    $email     = trim($_POST['email']);
    $role_id   = (int)$_POST['role_id'];
    $status    = $_POST['status'];

    $update = $pdo->prepare("
        UPDATE users 
        SET full_name = ?, email = ?, role_id = ?, status = ?
        WHERE id = ?
    ");

    $update->execute([$full_name, $email, $role_id, $status, $userId]);

    /* Audit */
    $audit = $pdo->prepare("
        INSERT INTO audit_logs (user_id, action)
        VALUES (?, ?)
    ");
    $audit->execute([
        $_SESSION['user_id'],
        "Edited user ID {$userId}"
    ]);

    header("Location: users.php");
    exit;
}
?>

<?php require_once '../includes/header.php'; ?>
<?php require_once '../includes/sidebar.php'; ?>

<div class="main-content">

<div class="page-header">
    <h2>Edit User</h2>
    <p class="page-subtitle">Update user details and access level.</p>
</div>

<div class="card-form">
<form method="POST">

    <label>Full Name</label>
    <input type="text" name="full_name" value="<?= htmlspecialchars($user['full_name']) ?>" required>

    <label>Email</label>
    <input type="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>

    <label>Role</label>
    <select name="role_id" required>
        <?php foreach ($roles as $role): ?>
            <option value="<?= $role['id'] ?>" 
                <?= $role['id'] == $user['role_id'] ? 'selected' : '' ?>>
                <?= strtoupper($role['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <label>Status</label>
    <select name="status">
        <option value="ACTIVE" <?= $user['status']=='ACTIVE'?'selected':'' ?>>ACTIVE</option>
        <option value="SUSPENDED" <?= $user['status']=='SUSPENDED'?'selected':'' ?>>SUSPENDED</option>
    </select>

    <br><br>

    <button type="submit" class="btn btn-primary">Save Changes</button>
    <a href="users.php" class="btn btn-light">Cancel</a>

</form>
</div>

</div>

<?php require_once '../includes/footer.php'; ?>
