<?php
require_once __DIR__ . '/../partials/header.php';

// Require admin role
if (!is_admin()) {
    header('Location: ../index.php');
    exit();
}

$user_id = $_GET['id'] ?? null;

if (!$user_id) {
    header('Location: users.php?error=No user specified');
    exit();
}

try {
    $pdo = db();
    $stmt = $pdo->prepare("SELECT id, name, email, role FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        header('Location: users.php?error=User not found');
        exit();
    }
} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    header('Location: users.php?error=A database error occurred.');
    exit();
}

$pageTitle = 'Edit User';
$errors = [];
$roles = ['user', 'admin'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = trim($_POST['role'] ?? '');

    if (empty($name)) $errors[] = 'Name is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'A valid email is required.';
    if (!in_array($role, $roles)) $errors[] = 'Invalid role selected.';

    // Prevent admin from changing their own role
    if ($user['id'] == get_user_id() && $role !== 'admin') {
        $errors[] = 'You cannot change your own role from admin.';
    }


    if (empty($errors)) {
        try {
            $pdo = db();
            $stmt = $pdo->prepare('UPDATE users SET name = ?, email = ?, role = ? WHERE id = ?');
            $stmt->execute([$name, $email, $role, $user_id]);

            header("Location: users.php?success=User updated successfully");
            exit;
        } catch (PDOException $e) {
            if ($e->errorInfo[1] == 1062) {
                $errors[] = 'This email address is already in use by another user.';
            } else {
                $errors[] = "Database error: " . $e->getMessage();
            }
        }
    }
}
?>
    <header class="py-5 text-center container-fluid">
        <div class="row py-lg-5">
            <div class="col-lg-6 col-md-8 mx-auto">
                <h1 class="display-4 fw-bold">Edit User</h1>
                <p class="lead text-muted">Update user details.</p>
            </div>
        </div>
    </header>

    <main class="container">
        <div class="row justify-content-center">
            <div class="col-lg-6">
                <div class="card shadow-sm mb-5">
                    <div class="card-body p-4">
                        <?php if (!empty($errors)) : ?>
                            <div class="alert alert-danger">
                                <ul class="mb-0">
                                    <?php foreach ($errors as $error) : ?>
                                        <li><?php echo htmlspecialchars($error); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>

                        <form action="edit_user.php?id=<?php echo $user_id; ?>" method="POST" novalidate>
                            <div class="form-floating mb-3">
                                <input type="text" class="form-control" id="name" name="name" placeholder="Full Name" required value="<?php echo htmlspecialchars($user['name']); ?>">
                                <label for="name">Name</label>
                            </div>

                            <div class="form-floating mb-3">
                                <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com" required value="<?php echo htmlspecialchars($user['email']); ?>">
                                <label for="email">Email</label>
                            </div>

                            <div class="form-floating mb-3">
                                <select class="form-select" id="role" name="role" required>
                                    <?php foreach ($roles as $r) : ?>
                                        <option value="<?php echo $r; ?>" <?php echo ($user['role'] === $r) ? 'selected' : ''; ?>><?php echo ucfirst($r); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <label for="role">Role</label>
                            </div>

                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary btn-lg">Save Changes</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </main>
<?php require_once __DIR__ . '/../partials/footer.php'; ?>
