<?php

require_once __DIR__ . '/../../connect.php';

$amount = filterRequest("amount");
$payment_method = filterRequest("payment_method");
$passengerID = filterRequest("passengerID");
$rideId = filterRequest("rideId");
$driverID = filterRequest("driverID");
$token = filterRequest("token");


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

$tokenData = $stmt->fetch();

if ($tokenData) {

$sql = "INSERT INTO `payments` (`id`,`amount`, `payment_method`, `passengerID`, `rideId`, `driverID`) 
        VALUES ( SHA2(UUID(), 256),'$amount', '$payment_method', '$passengerID', '$rideId', '$driverID')";
$stmt = $con->prepare($sql);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    // Print a success message
    jsonSuccess(null, "Payment record created successfully");
    // Mark the token as used in the database
        $stmt = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE id = :tokenID");
        $stmt->execute(array(
            ':tokenID' => $tokenData['id']
        ));
    } else {
        // Print a failure message
        jsonError("Failed to save record");
    }
} else {
    jsonError("Invalid or already used token");
}