<?php
if (!defined('ADDFUNDS')) {
    http_response_code(404);
    die();
}
 
 
// বিকাশ API কনফিগারেশন
$bkash_username = htmlspecialchars($methodExtras["username"]);
$bkash_password = htmlspecialchars($methodExtras["password"]);
$bkash_app_key = htmlspecialchars($methodExtras["app_key"]);
$bkash_app_secret = htmlspecialchars($methodExtras["app_secret_key"]);
 
 
$paymentAmount = $paymentAmount; // আপনার পেমেন্ট পরিমাণ
$orderId = md5(RAND_STRING(5) . time()); // অর্ডার আইডি তৈরি

// পেমেন্ট ডেটাবেসে ইনসার্ট
$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 1: Generate Access Token
$tokenRequestPayload = json_encode([
    'app_key' => $bkash_app_key,
    'app_secret' => $bkash_app_secret
]);

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://pay.bka.sh/token/grant", // লাইভ URL
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $tokenRequestPayload,
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json"
    ],
]);

$tokenResponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    errorExit("Token Request Error: " . $err);
}

$tokenResult = json_decode($tokenResponse, true);
if (!isset($tokenResult["id_token"])) {
    errorExit("Failed to generate access token.");
}

$accessToken = $tokenResult["id_token"];

// Step 2: Initiate Payment
$paymentRequestPayload = json_encode([
    "amount" => $paymentAmount,
    "currency" => "BDT",
    "intent" => "sale",
    "merchantInvoiceNumber" => $orderId,
    "payerReference" => $user["client_id"],
    "callbackURL" => site_url("payment/bkash_callback.php") // কলব্যাক URL
]);

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://pay.bka.sh/checkout/create", // লাইভ URL
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $paymentRequestPayload,
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "Authorization: Bearer $accessToken"
    ],
]);

$paymentResponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    errorExit("Payment Request Error: " . $err);
}

$paymentResult = json_decode($paymentResponse, true);
if (isset($paymentResult["statusCode"]) && $paymentResult["statusCode"] == "0000") {
    $paymentUrl = $paymentResult["bkashURL"];
    $redirectForm .= '<form method="GET" action=" ' . $paymentUrl . '" name="bkashCheckoutForm">';
    $redirectForm .= '</form>
    <script type="text/javascript">
    document.bkashCheckoutForm.submit();
    </script>';
} else {
    errorExit("Payment Failed: " . $paymentResult["statusMessage"]);
}

$response["success"] = true;
$response["message"] = "Your payment has been initiated and you will now be redirected to the payment gateway.";
$response["content"] = $redirectForm;
?>