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

// Generate a unique order ID
$orderId = md5(RAND_STRING(5) . time());

// UPI intent parameters
$merchantId = $methodExtras["merchantId"];
$upiId = $methodExtras["upiId"]; // UPI ID (e.g., merchant@upi)
$txnAmount = number_format($paymentAmount, 2, '.', ''); // Format amount with 2 decimal places
$callbackUrl = site_url("payment/" . $methodCallback); // Callback URL for payment verification

// Insert the payment record into the database
$insert = $conn->prepare("INSERT INTO payments SET
          client_id=:client_id, payment_amount=:amount, payment_method=:method,
          payment_mode=:mode, payment_create_date=:date,
          payment_ip=:ip,
          payment_extra=:extra"
);
$insert->execute([ 
    "client_id" => $user["client_id"],
    "amount" => $paymentAmount,
    "method" => $method["methodId"],
    "mode" => "Automatic",
    "date" => date("Y.m.d H:i:s"),
    "ip" => GetIP(),
    "extra" => $orderId
]);

// Construct UPI Intent URL with parameters
$upiIntentLink = "upi://pay?pa=" . urlencode($upiId) . 
                 "&pn=" . urlencode($merchantId) .  // Merchant name
                 "&mc=&tid=" . urlencode($orderId) .  // Transaction ID
                 "&tr=" . urlencode($orderId) .  // Transaction reference ID
                 "&tn=" . urlencode("Add funds to account") .  // Transaction note
                 "&am=" . urlencode($txnAmount) .  // Amount
                 "&cu=INR&url=" . urlencode($callbackUrl);  // Currency (INR) and callback URL

// Generate HTML for the "Initiate Payment" button
$redirectForm = '<div style="text-align: center;">
    <h3>Click to Pay</h3>
    <a href="' . $upiIntentLink . '" style="display: inline-block; margin-top: 10px; padding: 10px 20px; background-color: #007bff; color: #fff; text-decoration: none; border-radius: 5px;">Initiate Payment</a>
</div>';

$response["success"] = true;
$response["message"] = "Your payment has been initiated. Tap the button to complete the payment.";
$response["content"] = $redirectForm;
?>
