<?php
include "../../jwtconnect.php";

function logDebug($message) {
    error_log("[DEBUG] " . $message);
}

// Receive parameters
$token = filterRequest("token");
$driver_id = filterRequest("driverId");
$passenger_id = filterRequest("passengerId");
$amount = filterRequest("amount");
$payment_method = filterRequest("paymentMethod");

if (!$token || !$passenger_id || !$amount || !$payment_method) {
   // logDebug("Missing parameters: Token: $token, Passenger ID: $passenger_id, Amount: $amount, Payment Method: $payment_method");
    printFailure("Missing required parameters.");
    exit;
}

try {
    $table = ($driver_id == 'passenger') ? "payment_tokens_passenger" : "payment_tokens";

    $con->beginTransaction();

    // Check if token is valid and not used (locked row)
    $stmt = $con->prepare("SELECT * FROM $table WHERE token = :token AND isUsed = FALSE FOR UPDATE");
    $stmt->execute(array(':token' => $token));
    $tokenData = $stmt->fetch();

//    logDebug("Token Query Result: " . json_encode($tokenData));

    if ($tokenData) {
//        logDebug("Valid token found!");

        // Insert into Siro Wallet
        $sql = "INSERT INTO `siroWallet` (
            `driverId`,
            `passengerId`,
            `amount`,
            `paymentMethod`,
            `token`,
            `createdAt`
        ) VALUES (
            :driver_id,
            :passenger_id,
            :amount,
            :payment_method,
            :token,
            CURRENT_TIMESTAMP
        )";

        $stmt = $con->prepare($sql);
        $stmt->bindParam(':driver_id', $driver_id, PDO::PARAM_STR);
        $stmt->bindParam(':passenger_id', $passenger_id, PDO::PARAM_STR);
        $stmt->bindParam(':amount', $amount, PDO::PARAM_STR);
        $stmt->bindParam(':payment_method', $payment_method, PDO::PARAM_STR);
        $stmt->bindParam(':token', $token, PDO::PARAM_STR);

        if ($stmt->execute()) {
            $stmt = $con->prepare("UPDATE $table SET isUsed = TRUE WHERE id = :tokenID");
            $stmt->execute(array(':tokenID' => $tokenData['id']));

            $con->commit();
            printSuccess("Wallet data saved successfully");
        } else {
            $con->rollBack();
            printFailure("Failed to save wallet data");
        }
    } else {
        $con->rollBack();
        printFailure("Invalid or already used token");
    }
} catch (Exception $e) {
    if ($con->inTransaction()) { $con->rollBack(); }
    error_log("[siroWallet/add] " . $e->getMessage());
    printFailure("An error occurred");
}
?>