<?php
if (!defined('PAYMENT')) {
    http_response_code(404);
    die();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    require_once("lib/encdec_paytm.php"); // Include UPI verification library

    // Extract payment details from POST data
    $merchantId = $methodExtras["merchantId"];
    $apiKey = $methodExtras["apiKey"]; // Assuming the UPI gateway uses an API key for verification
    
    $transactionId = $_POST["transactionId"]; // Unique transaction ID from UPI
    $orderId = $_POST["orderId"]; // Order ID
    $paymentStatus = $_POST["status"]; // Status of the payment
    $paidAmount = $_POST["amount"]; // Amount paid

    // Validate input fields
    if (empty($transactionId) || empty($orderId) || empty($paymentStatus)) {
        errorExit("Invalid Data.");
    }

    // Call the UPI verification API
    $verificationResponse = verifyUPIPayment($transactionId, $apiKey, $merchantId);

    // If the payment verification is successful and the payment status is "SUCCESS"
    if ($verificationResponse['status'] == 'SUCCESS' && $paymentStatus == "SUCCESS") {
        // Fetch payment details using the order ID
        $paymentDetails = $conn->prepare("SELECT * FROM payments WHERE payment_extra=:order_id");
        $paymentDetails->execute([ "order_id" => $orderId ]);
        
        if ($paymentDetails->rowCount()) {
            $paymentDetails = $paymentDetails->fetch(PDO::FETCH_ASSOC);

            // Fetch the user associated with the payment
            $user = $conn->prepare("SELECT * FROM clients WHERE client_id=:id");
            $user->execute([ "id" => $paymentDetails["client_id"] ]);
            $user = $user->fetch(PDO::FETCH_ASSOC);

            // Check if this order ID has already been processed
            if (!countRow([ 'table' => 'payments', 'where' => [ 'client_id' => $user['client_id'], 'payment_method' => $methodId, 'payment_status' => 3, 'payment_delivery' => 2, 'payment_extra' => $orderId ] ])) {

                // Apply payment fee if applicable
                if ($paymentFee > 0) {
                    $fee = ($paidAmount * ($paymentFee / 100));
                    $paidAmount -= $fee;
                }

                // Apply bonus if applicable
                if ($paymentBonusStartAmount != 0 && $paidAmount > $paymentBonusStartAmount) {
                    $bonus = $paidAmount * ($paymentBonus / 100);
                    $paidAmount += $bonus;
                }

                // Convert the payment amount to the site's base currency if needed
                $paidAmount = from_to($currencies_array, $methodCurrency, $settings["site_base_currency"], $paidAmount);

                // Update payment record in the database
                $update = $conn->prepare('UPDATE payments SET 
                    client_balance=:balance, 
                    payment_status=:status, 
                    payment_delivery=:delivery WHERE payment_id=:id');
                $update->execute([
                    'balance' => $user["balance"],
                    'status' => 3,  // Payment confirmed
                    'delivery' => 2,  // Payment delivered
                    'id' => $paymentDetails['payment_id']
                ]);

                // Update user's balance
                $balance = $conn->prepare('UPDATE clients SET balance=:balance WHERE client_id=:id');
                $balance->execute([
                    "balance" => $user["balance"] + $paidAmount,
                    "id" => $user["client_id"]
                ]);

                // Redirect to the add funds page
                header("Location: " . site_url("addfunds"));
                exit;
            } else {
                errorExit("Order ID has already been used.");
            }
        } else {
            errorExit("Order ID not found.");
        }
    } else {
        errorExit("Payment verification failed.");
    }
} else {
    http_response_code(405);  // Method Not Allowed
    die();
}

// Helper function to handle error exits
function errorExit($message) {
    $response["success"] = false;
    $response["message"] = $message;
    echo json_encode($response);
    exit;
}
?>
