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

$orderId = md5(RAND_STRING(5) . time());
$uuid = uuid();
$description = "Balance recharge (" . $user["username"] . ")";

// === Step 1: Request QR from KHQR API ===
$khqrPayload = [
    "bakongAccountID"      => "leoung_khunny@aclb",
    "accName"              => "CHHAYSMM",
    "accountInformation"   => "34670417145214",
    "currency"             => $methodCurrency,
    "amount"               => $paymentAmount,
    "address"              => "PhnomPenh"
];

$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));

$apiResponse = curl_exec($ch);
curl_close($ch);

$apiData = json_decode($apiResponse, true);
$qrImage = $apiData['qrImage'] ?? null;
$paymentMd5 = $apiData['md5'] ?? $orderId;

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

// === Step 2: Save Payment in 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_status='Pending',
        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" => $paymentMd5 // save the actual md5 from API
]);

// === Step 3: Show QR ===
$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($paymentMd5) . '</p>
</div>';

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