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

// Ensure RAND_STRING is defined
function RAND_STRING($length = 5) {
    return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
}

// Generate the order ID and UUID
$orderId = md5(RAND_STRING(5) . time());
$description = "Balance recharge (" . $user["username"] . ")";
$uuid = uuid();  // Ensure uuid() function is defined elsewhere or use another method

$callback_url = site_url("payment/" . $methodCallback);

// === Step 1: Call your KHQR API ===
$khqrPayload = [
    "bakongAccountID"      => "leoung_khunny@aclb",
    "accName"              => "CHHAYSMM",
    "accountInformation"   => "34670417145214",
    "currency"             => $methodCurrency,  // assuming "USD"
    "amount"               => $paymentAmount,   // dynamic from form/user input
    "address"              => "PhnomPenh"
];

// Set up cURL for API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://khqr-nang.bruhstore.online/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($khqrPayload));

// Execute the cURL request
$apiResponse = curl_exec($ch);
curl_close($ch);

// Handle the API response and check for errors
if ($apiResponse === false) {
    $response["success"] = false;
    $response["message"] = "Failed to connect to KHQR API.";
    exit(json_encode($response));
}

$apiData = json_decode($apiResponse, true);

// Check if the JSON response is valid
if (json_last_error() !== JSON_ERROR_NONE) {
    $response["success"] = false;
    $response["message"] = "Invalid JSON response from KHQR API.";
    exit(json_encode($response));
}

$qrImage = $apiData['qrImage'] ?? null;

if (!$qrImage) {
    $response["success"] = false;
    $response["message"] = "Failed to generate KHQR code.";
    exit(json_encode($response));
}

// === Step 2: Save to DB ===
$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" => $methodId,
    "mode" => "Automatic",
    "date" => date("Y.m.d H:i:s"),
    "ip" => GetIP(),
    "extra" => $orderId
]);

// === Step 3: Show QR Code and Add Polling Script ===
$redirectForm = '<div style="text-align:center;">
    <p>Scan this KHQR code with your Bakong app to complete the payment:</p>
    <img src="' . htmlspecialchars($qrImage) . '" style="max-width:300px;" />
    <p><strong>Order ID:</strong> ' . htmlspecialchars($orderId) . '</p>
    <p id="payment-status">Waiting for payment...</p>
</div>

<script>
// Function to check payment status
function checkPayment() {
    fetch("/check_khqr_payment.php?order_id=" + encodeURIComponent("' . $orderId . '"))
        .then(response => response.json())
        .then(data => {
            if (data.verified) {
                document.getElementById('payment-status').innerHTML = "<b style=\'color:green;\'>✅ Payment received!</b>";
                // Optionally reload or redirect after success
                // setTimeout(() => window.location.href = \'/dashboard\', 3000); 
            } else {
                // Poll again in 5 seconds if not verified
                setTimeout(checkPayment, 5000);
            }
        })
        .catch(error => {
            console.error("Error checking payment:", error);
            // Optionally handle error (retry, alert user, etc.)
        });
}

// Start checking after 5 seconds
setTimeout(checkPayment, 5000);
</script>';

$response["success"] = true;
$response["message"] = "Please scan the QR code to complete your payment.";
$response["content"] = $redirectForm;

echo json_encode($response);
?>
