<?php
session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($id <= 0) {
    die("Invalid user ID.");
}

$error = '';

try {
    $stmt = $db->prepare("
        SELECT id, full_name, username, email, role, status
        FROM users
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        die("User not found.");
    }
} catch (PDOException $e) {
    die("Query error: " . $e->getMessage());
}

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

    if ($full_name === '' || $username === '' || $email === '' || $role === '' || $status === '') {
        $error = "All fields are required.";
    } else {
        try {
            $checkStmt = $db->prepare("
                SELECT id
                FROM users
                WHERE (username = :username OR email = :email)
                  AND id != :id
                LIMIT 1
            ");
            $checkStmt->bindParam(':username', $username);
            $checkStmt->bindParam(':email', $email);
            $checkStmt->bindParam(':id', $id, PDO::PARAM_INT);
            $checkStmt->execute();

            if ($checkStmt->fetch(PDO::FETCH_ASSOC)) {
                $error = "Username or email already exists.";
            } else {
                $updateStmt = $db->prepare("
                    UPDATE users
                    SET full_name = :full_name,
                        username = :username,
                        email = :email,
                        role = :role,
                        status = :status
                    WHERE id = :id
                ");
                $updateStmt->bindParam(':full_name', $full_name);
                $updateStmt->bindParam(':username', $username);
                $updateStmt->bindParam(':email', $email);
                $updateStmt->bindParam(':role', $role);
                $updateStmt->bindParam(':status', $status);
                $updateStmt->bindParam(':id', $id, PDO::PARAM_INT);
                $updateStmt->execute();

                header("Location: users.php?updated=1");
                exit;
            }
        } catch (PDOException $e) {
            $error = "Update failed: " . $e->getMessage();
        }
    }

    $user['full_name'] = $full_name;
    $user['username']  = $username;
    $user['email']     = $email;
    $user['role']      = $role;
    $user['status']    = $status;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit User</title>
    <link rel="stylesheet" href="assets/css/app.css">
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="hero">
            <div class="hero-top">
                <div>
                    <h1>Edit User</h1>
                    <p>Admin can update user information here.</p>
                </div>
                <div class="welcome-badge">Admin</div>
            </div>
        </div>

        <div class="card">
            <?php if ($error !== ''): ?>
                <div class="badge danger" style="display:block; margin-bottom:12px;">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <form method="POST" style="display:grid; gap:14px; max-width:600px;">
                <div>
                    <label>Full Name</label><br>
                    <input type="text" name="full_name" required
                           value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>">
                </div>

                <div>
                    <label>Username</label><br>
                    <input type="text" name="username" required
                           value="<?php echo htmlspecialchars($user['username'] ?? ''); ?>">
                </div>

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

                <div>
                    <label>Role</label><br>
                    <select name="role" required>
                        <option value="admin" <?php echo (($user['role'] ?? '') === 'admin') ? 'selected' : ''; ?>>Admin</option>
                        <option value="user" <?php echo (($user['role'] ?? '') === 'user') ? 'selected' : ''; ?>>User</option>
                    </select>
                </div>

                <div>
                    <label>Status</label><br>
                    <select name="status" required>
                        <option value="active" <?php echo (($user['status'] ?? '') === 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo (($user['status'] ?? '') === 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div style="display:flex; gap:8px; flex-wrap:wrap;">
                    <button type="submit" class="btn btn-primary">Update User</button>
                    <a href="users.php" class="btn btn-secondary">Back</a>
                </div>
            </form>
        </div>
    </main>
</div>
</body>
</html>