<?php
// Automatically detect protocol (http or https)
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || 
             $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

// Automatically detect domain name and path
$domain = $_SERVER['HTTP_HOST']; // example: sathee.shop

// Final webhook URL
$webhookUrl = $protocol . $domain . "/admin/AXEN/webhook.php";

echo $webhookUrl; // Output: https://sathee.shop/admin/HBConnect4in1/webhook.php
?>

<?php
session_start();
include('../includes/config.php');

// ✅ Unique Order ID
$Order_ID = "allcscseva.shop" . rand(10000,99999);

// ✅ Check POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ✅ Sanitize inputs
    $customer_mobile = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $amount = isset($_POST['amount']) ? trim($_POST['amount']) : '';

    if(empty($customer_mobile) || empty($amount)){
        die("❌ Mobile ya Amount missing hai!");
    }

    // ✅ API Endpoint
    $url = 'https://pay.allwebfast.in/api/create-order';

    // ✅ Data to send
    $data = array(
        "customer_mobile" => $customer_mobile,
        "user_token" => "4f4f2d5860edb2ee76ba899d3b63bd02", // apna token yaha
        "amount" => $amount,
        "order_id" => $Order_ID,
        "redirect_url" => $webhookUrl,
    );

    // ✅ Save session (fraud protection ke liye)
    $_SESSION['order_id'] = $Order_ID;
    $_SESSION['customer_mobile'] = $customer_mobile;

    // ✅ cURL se request bhejo (file_get_contents kaafi baar block hota hai)
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        die("❌ API Request Failed: " . $error);
    }

    // ✅ Decode JSON
    $result = json_decode($response, true);

    echo "<pre>";
    echo "📩 API RAW RESPONSE:\n";
    print_r($response);
    echo "\n\n📦 Parsed Response:\n";
    print_r($result);
    echo "</pre>";

    // ✅ Check status
    if (isset($result['status']) && $result['status'] === true && isset($result['result']['payment_url'])) {
        // ✅ Redirect to payment page
        header("Location: " . $result['result']['payment_url']);
        exit();
    } else {
        die("❌ API Error: " . ($result['message'] ?? "Unknown Error"));
    }
}
?>

<html>
<head>
    <title>Gateway Check Out Page</title>
</head>
<body>
    <center><h1>Please do not refresh this page...</h1></center>
</body>
</html>
