<?php
function fetchApiData($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);   
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError || $httpCode !== 200) {
        return null;
    }

    return json_decode($response, true);
}

function getClientIP() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipaddress = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    } else {
        $ipaddress = 'UNKNOWN';
    }
    return trim($ipaddress);
}

$shagitz_ipaddress = isset($_GET['ip']) ? trim($_GET['ip']) : getClientIP();

if (!filter_var($shagitz_ipaddress, FILTER_VALIDATE_IP)) {
    $data = null;
} else {
    $apiUrl = "http://ipwho.is/{$shagitz_ipaddress}";
    $data = fetchApiData($apiUrl);
}

$shagitz_continent   = $data['continent'] ?? 'N/A';
$shagitz_country     = $data['country'] ?? 'N/A';
$shagitz_countryCode = $data['country_code'] ?? 'N/A';
$shagitz_flag        = $data['flag']['emoji'] ?? 'N/A';
$shagitz_regionName  = $data['region'] ?? 'N/A';
$shagitz_city        = $data['city'] ?? 'N/A';
$shagitz_callcode    = $data['calling_code'] ?? 'N/A';
$shagitz_latitude    = $data['latitude'] ?? 'N/A';
$shagitz_longitude   = $data['longitude'] ?? 'N/A';
$shagitz_timezone    = $data['timezone']['id'] ?? 'N/A';
$shagitz_isp         = 'ZIP : '.($data['postal'] ?? 'N/A');
$shagitz_as          = (isset($data['connection']['asn'], $data['connection']['org'])) 
    ? 'AS - '.$data['connection']['asn'].' | '.$data['connection']['org'] 
    : 'N/A';

date_default_timezone_set('Asia/Jakarta');
$jamasuk = date('l, d-m-Y h:i:s');
$yearNow = date('Y');
?>
