<?php

// Function to sanitize user input
include("config.php");
session_start();

if (isset($_POST['upigate'])) {

$amount=$_POST['amount'];
$planid=$_POST['planid'];

$order_id='cxr'.time().rand(11111,99999);
setcookie('order_id_cookie', $order_id, time() + 3600, '/'); // Expires in 1 hour (adjust the expiration time as needed)
setcookie('planid_cookie', $planid, time() + 3600, '/'); // Expires in 1 hour (adjust the expiration time as needed)

$currentDomain = $_SERVER["SERVER_NAME"];
$callbackurl = "https://" . $currentDomain . "/auth/lib/callback";

$data = array(
    'customer_mobile' => '1234567890',
    'user_token' => $token,
    'amount' => $amount,
    'order_id' => $order_id,
    'redirect_url' => $callbackurl,
    'remark1' => 'test1',
    'remark2' => 'test2',
    'origin_domain' => $currentDomain,
);

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://' . $currentDomain . '/api/create-order',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => http_build_query($data),
));
$response = curl_exec($curl);
$curlErr = curl_error($curl);
curl_close($curl);

$jsonResponse = json_decode($response, true);

if (!empty($jsonResponse['status']) && isset($jsonResponse['result']['payment_url'])) {
    $paymentUrl = $jsonResponse['result']['payment_url'];
    header('Location: ' . $paymentUrl);
    exit;
} else {
    $apiMsg = $jsonResponse['message'] ?? ($curlErr ?: 'Unknown error');
    echo 'Failed to create order: ' . htmlspecialchars($apiMsg);
}

}
