<?php
include "../../jwtconnect.php";
//addPassengersWallet.php
$passenger_id = filterRequest("passenger_id");
$balance = filterRequest("balance");
$token = filterRequest("token");


try {
    $con->beginTransaction();

    // Retrieve token details from the database securely and lock the row
    $stmt = $con->prepare("SELECT * FROM payment_tokens_passenger WHERE token = :token AND isUsed = FALSE FOR UPDATE");
    $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)";
        $stmtInsert = $con->prepare($sql);
        $stmtInsert->execute([':passenger_id' => $passenger_id, ':balance' => $balance]);

        if ($stmtInsert->rowCount() > 0) {
            // Mark the token as used
            $updateTokenStmt = $con->prepare("UPDATE payment_tokens_passenger SET isUsed = TRUE WHERE id = :tokenID");
            $updateTokenStmt->execute([':tokenID' => $tokenData['id']]);
            
            $con->commit();
            printSuccess("Wallet record created successfully");
        } else {
            $con->rollBack();
            printFailure("Failed to create wallet record");
        }
    } else {
        $con->rollBack();
        printFailure("Invalid or already used token");
    }
} catch (Exception $e) {
    if ($con->inTransaction()) {
        $con->rollBack();
    }
    printFailure("Database error: " . $e->getMessage());
}
?>