<?php

// Include the database connection file
require_once __DIR__ . '/../../connect.php';

// Get the request parameters
$driverID = filterRequest("driverID");
$paymentID = filterRequest("paymentID");
$amount = filterRequest("amount");
$paymentMethod = filterRequest("paymentMethod");
$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) {
    // Add payment to the driver's wallet table
    $sql = "INSERT INTO `driverWallet` (
        `driverID`,
        `paymentID`,
        `amount`,
        `paymentMethod`
    ) VALUES (
        :driverID,
        :paymentID,
        :amount,
        :paymentMethod
    );";

    $stmt = $con->prepare($sql);
    $stmt->execute(array(
        ':driverID' => $driverID,
        ':paymentID' => $paymentID,
        ':amount' => $amount,
        ':paymentMethod' => $paymentMethod
    ));

    if ($stmt->rowCount() > 0) {
        // Print a success message
        jsonSuccess(null, "Record saved 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");
}
