<?php

// Fetch the current user's data
$username = $_SESSION['username'];
$user = $db->getUserByUsername($username);

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_account'])) {
    $new_username = $_POST['username'];
    $new_password = $_POST['password'];

    $new_username = htmlspecialchars($new_username);
    $new_password = htmlspecialchars($new_password);

    $update_data = [
        'username' => $new_username,
        'password' => $new_password 
    ];

    // Update the user's credentials using their ID to ensure correct row update
    $update_result = $db->update('users', $update_data, ['id' => $user['id']]); 

    if ($update_result) {
        // Update session username if the username was changed
        $_SESSION['username'] = $new_username;
        $success_message = "Account updated successfully!";
    } else {
        $error_message = "Failed to update account. Please try again.";
    }
}
?>

<h5 class="card-title">Account Management</h5>
<?php if (isset($success_message)): ?>
    <div class="alert alert-success"><?php echo $success_message; ?></div>
<?php elseif (isset($error_message)): ?>
    <div class="alert alert-danger"><?php echo $error_message; ?></div>
<?php endif; ?>

<form action="" method="POST">
    <div class="mb-3">
        <label for="username" class="form-label">Username</label>
        <input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($user['username']); ?>" required>
    </div>
    <div class="mb-3">
        <label for="password" class="form-label">Password</label>
        <input type="password" class="form-control" name="password" value="<?php echo htmlspecialchars($user['password']); ?>" required>
    </div>
    <button name="update_account" type="submit" class="btn btn-primary">Update Account</button>
</form>
