<?php
include("include/conn.php");

$query = "SELECT * FROM settings WHERE user_id = '1' LIMIT 1"; // Assuming user_id is 1 for simplicity
$result = mysqli_query($conn, $query);
$settings = mysqli_fetch_assoc($result);

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST']; // Gets the current domain or IP

// Construct the base URL dynamically
$url = $settings["api_url"];
$orderid = 'BYEXT'.rand(10000000, 999999999);
$token = $settings["api_token"];

// Data to be sent in the POST request
$data = array(
    'customer_mobile' => '9751548452',
    'user_token' => $token,
    'amount' => $settings["amount"],
    'order_id' => $orderid,
    'redirect_url' => $protocol . $host . '/checkexttxn.php?orderid='.$orderid,
    'remark1' => 'hello',
    'remark2' => 'hello1',
);

// echo json_encode($data);
// exit;

$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session and store the response
$response = curl_exec($ch);

// Check for cURL errors
if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);


// Decode the JSON response
$jsonResponse = json_decode($response, true);

// Check if decoding was successful
if ($jsonResponse !== null) {
    // Redirect the user to the payment URL
    $paymentUrl = $jsonResponse['result']['payment_url'];
    header('Location: ' . $paymentUrl);
    exit;
} else {
    echo "Failed to make payment ! try again later";
}
?>
