<?php
require_once __DIR__ . '/config.php';

$visitor_ip = $_SERVER['REMOTE_ADDR'] ?? '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

// GeoIP via ipinfo.io
$geo = [];
$ch  = curl_init("https://ipinfo.io/{$visitor_ip}/json");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 4]);
$raw = curl_exec($ch);
curl_close($ch);
if ($raw) $geo = json_decode($raw, true) ?: [];

$ip  = $geo['ip']      ?? $visitor_ip;
$isp = $geo['org']     ?? 'Unknown ISP';
$cn  = $geo['country'] ?? 'XX';
$ct  = $geo['city']    ?? '';
$st  = $geo['region']  ?? '';

$date = date("d M, Y");
$time = date("g:i a");
$date = trim("{$date}, Time : {$time}");

function getOS() {
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $map = [
        '/windows nt 10/i'      => 'Windows 10',
        '/windows nt 6.3/i'     => 'Windows 8.1',
        '/windows nt 6.2/i'     => 'Windows 8',
        '/windows nt 6.1/i'     => 'Windows 7',
        '/windows nt 6.0/i'     => 'Windows Vista',
        '/windows nt 5.1/i'     => 'Windows XP',
        '/macintosh|mac os x/i' => 'Mac OS X',
        '/linux/i'              => 'Linux',
        '/ubuntu/i'             => 'Ubuntu',
        '/iphone/i'             => 'iPhone',
        '/ipad/i'               => 'iPad',
        '/android/i'            => 'Android',
    ];
    foreach ($map as $r => $v) if (preg_match($r, $ua)) return $v;
    return 'Unknown OS';
}

function getBrowser() {
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $map = [
        '/msie/i'    => 'Internet Explorer',
        '/firefox/i' => 'Firefox',
        '/chrome/i'  => 'Chrome',
        '/safari/i'  => 'Safari',
        '/opera/i'   => 'Opera',
        '/mobile/i'  => 'Mobile Browser',
    ];
    foreach ($map as $r => $v) if (preg_match($r, $ua)) return $v;
    return 'Unknown Browser';
}

$os = getOS();
$br = getBrowser();
