<?php
require_once("../config/function.php");
$main_site_data = main_site_data();

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get raw POST body
    $input = file_get_contents('php://input');

    // Parse JSON if content-type is application/json
    $data = $_POST;
    if (!empty($input)) {
        $json = json_decode($input, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            $data = array_merge($data, $json);
        }
    }

    // Extract required parameters
    $utr = trim($data['utr'] ?? '');
    $transactionId = trim($data['TransactionId'] ?? '');
    $redirectUrl = trim($data['redirect_url'] ?? '');

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

    // Build the verification URL
    $verifyUrl = "https://" . paymentapi("gateway_Url") . "/api2/verify.php?redirect_url="
        . urlencode($redirectUrl)
        . "&TransactionId=" . urlencode($transactionId)
        . "&utr=" . urlencode($utr);

    // Function to call API via cURL
    function call_payment_api($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); // 15s timeout
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // optional, avoid SSL issues
        $response = curl_exec($ch);

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

        curl_close($ch);
        return $response;
    }

    // Call the verification API
    $response = call_payment_api($verifyUrl);

    // Output JSON response
    header('Content-Type: application/json');
    echo $response;

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