<?php
require_once __DIR__ . '/../../connect.php';
$passenger_id = filterRequest("passenger_id");
$balance = filterRequest("balance");
$token = filterRequest("token");


// Retrieve token details from the database
$stmt = $con->prepare("SELECT * FROM payment_tokens_passenger WHERE token = :token AND isUsed = FALSE");
$stmt->execute([':token' => $token]);

$tokenData = $stmt->fetch();

if ($tokenData) {
    // Insert into passengerWallet securely using prepared statements
    $sql = "INSERT INTO `passengerWallet` (`passenger_id`, `balance`) VALUES (:passenger_id, :balance)";
    $stmt = $con->prepare($sql);
    $stmt->execute([':passenger_id' => $passenger_id, ':balance' => $balance]);

    if ($stmt->rowCount() > 0) {
        // Mark the token as used
        $updateTokenStmt = $con->prepare("UPDATE payment_tokens_passenger SET isUsed = TRUE WHERE token = :token");
        $updateTokenStmt->execute([':token' => $token]);
        
        jsonSuccess(null, "Wallet record created successfully");
    } else {
        jsonError("Failed to create wallet record");
    }
} else {
    jsonError("Invalid or already used token");
}
?>