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

header('Content-Type: application/json');

// ✅ TheMonkeyPay Configuration
$themonkey_token = "e8d2a2f1ac98d41d3b7422fd11ab98fa";
$themonkey_api_url = "themonkeypay.in";

// ✅ Backup Gateway Configuration
$backup_token = $flexsecure_upikey;
$backup_api_url = "server.responsecheck.site";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = $_POST['order_id'] ?? '';
    
    if (empty($order_id)) {
        echo json_encode(['status' => 'error', 'message' => 'Order ID required']);
        exit;
    }

    // ✅ Check which gateway was used
    $gateway_used = $_SESSION['gateway_used'] ?? 'themonkeypay';

    // ✅ Prepare API call based on gateway
    if ($gateway_used === 'themonkeypay') {
        $url = "https://{$themonkey_api_url}/api/check-order-status";
        $postData = [
            "user_token" => $themonkey_token,
            "order_id" => $order_id
        ];
    } else {
        $url = "https://{$backup_api_url}/api/check-order-status";
        $postData = [
            "user_token" => $backup_token,
            "order_id" => $order_id
        ];
    }

    // ✅ Call API
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo json_encode(['status' => 'error', 'message' => 'Connection failed']);
        curl_close($ch);
        exit;
    }
    curl_close($ch);

    $responseData = json_decode($response, true);

    // ✅ Check payment status
    if ($gateway_used === 'themonkeypay') {
        // TheMonkeyPay response format
        if (isset($responseData['status']) && $responseData['status'] === 'COMPLETED') {
            echo json_encode(['status' => 'success', 'data' => $responseData]);
        } else {
            echo json_encode(['status' => 'pending']);
        }
    } else {
        // Backup gateway response format
        if (isset($responseData['result']['txnStatus']) && 
            strtoupper($responseData['result']['txnStatus']) === 'COMPLETED') {
            echo json_encode(['status' => 'success', 'data' => $responseData]);
        } else {
            echo json_encode(['status' => 'pending']);
        }
    }

} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>