<?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 {
//    logDebug("Checking token validity: $token with DriverID: $driver_id");

    // Choose correct table based on driverId
    $table = ($driver_id == 'passenger') ? "payment_tokens_passenger" : "payment_tokens";
//    logDebug("table is: " . $table);

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

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

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

        // Insert into Sefer Wallet
        $sql = "INSERT INTO `seferWallet` (
            `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()) {
    //        logDebug("Wallet data saved successfully.");

            // Mark token as used in the correct table
            $stmt = $con->prepare("UPDATE $table SET isUsed = TRUE WHERE id = :tokenID");
            $stmt->execute(array(':tokenID' => $tokenData['id']));

       //     logDebug("Token marked as used in $table.");
            printSuccess("Wallet data saved successfully");
        } else {
        //    logDebug("Failed to save wallet data.");
            printFailure("Failed to save wallet data");
        }
    } else {
     //   logDebug("Invalid or already used token: $token");
        printFailure("Invalid or already used token");
    }
} catch (Exception $e) {
  //  logDebug("Exception: " . $e->getMessage());
    printFailure("An error occurred: " . $e->getMessage());
}
?>