<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    $utr = trim($_GET['utr'] ?? '');
    $transactionId = trim($_GET['TransactionId'] ?? '');
    $redirectUrl = trim($_GET['redirect_url'] ?? '');

    if (empty($utr) || empty($transactionId) || empty($redirectUrl)) {
        header('Content-Type: application/json');
        echo json_encode([
            "status" => "error",
            "message" => "Missing required parameters."
        ]);
        exit;
    }

    // ✅ Ensure redirect URL is absolute
    if (strpos($redirectUrl, 'http') !== 0) {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        $baseUrl = $protocol . "://" . $host . "/";
        $redirectUrl = $baseUrl . ltrim($redirectUrl, './');
    }

    // ✅ Build verification URL
    $verifyUrl = "https://checkout.flexrecharge.online/api2/verify.php"
        . "?redirect_url=" . urlencode($redirectUrl)
        . "&TransactionId=" . urlencode($transactionId)
        . "&utr=" . urlencode($utr);

    // ✅ cURL call
    $ch = curl_init($verifyUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        echo json_encode(["status" => "error", "message" => "Connection error: " . $error]);
        exit;
    }

    curl_close($ch);
    header('Content-Type: application/json');
    echo $response;
    exit;

} else {
    header("HTTP/1.1 405 Method Not Allowed");
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Method Not Allowed"]);
}
?>
