<?php

include "../../connect.php";
///ride/payment/add.php
$amount         = filterRequest("amount");
$payment_method = filterRequest("payment_method");
$passengerID    = filterRequest("passengerID");
$rideId         = filterRequest("rideId");
$driverID       = filterRequest("driverID");
$token          = filterRequest("token");

try {
    $con->beginTransaction();

    // ✅ تحقق من التوكن مع قفل السجل (FOR UPDATE) لمنع ثغرة السباق (Race Condition)
    $stmt = $con->prepare("SELECT * FROM payment_tokens WHERE token = :token AND isUsed = FALSE FOR UPDATE");
    $stmt->execute([ ':token' => $token ]);
    $tokenData = $stmt->fetch();

    if ($tokenData) {
        // ✅ إدخال الدفع بمفتاح قصير وخفيف
        $sql = "INSERT INTO payments (id, amount, payment_method, passengerID, rideId, driverID)
                VALUES (UUID_SHORT(), :amount, :payment_method, :passengerID, :rideId, :driverID)";
        $stmtInsert = $con->prepare($sql);
        $stmtInsert->execute([
            ':amount'         => $amount,
            ':payment_method' => $payment_method,
            ':passengerID'    => $passengerID,
            ':rideId'         => $rideId,
            ':driverID'       => $driverID
        ]);

        if ($stmtInsert->rowCount() > 0) {
            // ✅ تحديث حالة التوكن
            $stmtUpdate = $con->prepare("UPDATE payment_tokens SET isUsed = TRUE WHERE id = :tokenID");
            $stmtUpdate->execute([ ':tokenID' => $tokenData['id'] ]);
            
            $con->commit();
            printSuccess("Payment record created successfully");
        } else {
            $con->rollBack();
            printFailure("Failed to save record");
        }
    } else {
        $con->rollBack();
        printFailure("Invalid or already used token");
    }
} catch (Exception $e) {
    if ($con->inTransaction()) {
        $con->rollBack();
    }
    printFailure("An error occurred: " . $e->getMessage());
}