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

/**
 * Get location information from IP address
 * @param string $ip IP address to check
 * @return array Location information
 */
function getLocation($ip) {
    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        error_log("Invalid IP address: $ip");
        return ['error' => 'Invalid IP address'];
    }

    // Use IPQS API if available, otherwise fallback to ip-api.com
    if (defined('IPQS_API_KEY') && !empty(IPQS_API_KEY)) {
        $url = "https://www.ipqualityscore.com/api/json/ip/" . IPQS_API_KEY . "/" . $ip;
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if (curl_errno($ch)) {
                throw new Exception(curl_error($ch));
            }
            
            curl_close($ch);
            
            if ($httpCode !== 200) {
                throw new Exception("API request failed with status code: $httpCode");
            }
            
            $data = json_decode($response, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception("Failed to parse API response");
            }
            
            return [
                'country' => $data['country'] ?? 'Unknown',
                'city' => $data['city'] ?? 'Unknown',
                'isp' => $data['isp'] ?? 'Unknown'
            ];
        } catch (Exception $e) {
            error_log("IPQS lookup failed: " . $e->getMessage());
            // Fall through to ip-api.com
        }
    }
    
    // Fallback to ip-api.com
    return get_location_info($ip);
}

/**
 * Get OS version from user agent
 * @param string $userAgent User agent string
 * @return string OS version
 */
function getOSVersion($userAgent) {
    $userAgent = filter_var($userAgent, FILTER_SANITIZE_STRING);
    
    if (empty($userAgent)) {
        return 'Unknown';
    }
    
    $os = 'Unknown';
    
    // Windows
    if (preg_match('/Windows NT (\d+\.\d+)/', $userAgent, $matches)) {
        $version = $matches[1];
        switch ($version) {
            case '10.0': $os = 'Windows 10'; break;
            case '6.3': $os = 'Windows 8.1'; break;
            case '6.2': $os = 'Windows 8'; break;
            case '6.1': $os = 'Windows 7'; break;
            default: $os = "Windows NT $version";
        }
    }
    // macOS
    elseif (preg_match('/Mac OS X (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'macOS ' . str_replace('_', '.', $matches[1]);
    }
    // Linux
    elseif (preg_match('/Linux/', $userAgent)) {
        $os = 'Linux';
    }
    // iOS
    elseif (preg_match('/iPhone OS (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'iOS ' . str_replace('_', '.', $matches[1]);
    }
    // Android
    elseif (preg_match('/Android (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'Android ' . str_replace('_', '.', $matches[1]);
    }
    
    return $os;
}

/**
 * Get browser name from user agent
 * @param string $userAgent User agent string
 * @return string Browser name
 */
function getBrowser($userAgent) {
    $userAgent = filter_var($userAgent, FILTER_SANITIZE_STRING);
    
    if (empty($userAgent)) {
        return 'Unknown';
    }
    
    $browser = 'Unknown';
    
    // Chrome
    if (preg_match('/Chrome\/(\d+\.\d+)/', $userAgent, $matches)) {
        $browser = 'Chrome ' . $matches[1];
    }
    // Firefox
    elseif (preg_match('/Firefox\/(\d+\.\d+)/', $userAgent, $matches)) {
        $browser = 'Firefox ' . $matches[1];
    }
    // Safari
    elseif (preg_match('/Version\/(\d+\.\d+).*Safari/', $userAgent, $matches)) {
        $browser = 'Safari ' . $matches[1];
    }
    // Edge
    elseif (preg_match('/Edg\/(\d+\.\d+)/', $userAgent, $matches)) {
        $browser = 'Edge ' . $matches[1];
    }
    // Opera
    elseif (preg_match('/OPR\/(\d+\.\d+)/', $userAgent, $matches)) {
        $browser = 'Opera ' . $matches[1];
    }
    // Internet Explorer
    elseif (preg_match('/MSIE (\d+\.\d+)/', $userAgent, $matches)) {
        $browser = 'Internet Explorer ' . $matches[1];
    }
    
    return $browser;
}

/**
 * Check if user is on mobile device
 * @param string $userAgent User agent string
 * @return bool True if mobile device
 */
function isMobile($userAgent) {
    $userAgent = filter_var($userAgent, FILTER_SANITIZE_STRING);
    
    if (empty($userAgent)) {
        return false;
    }
    
    $mobileKeywords = [
        'Mobile', 'Android', 'iPhone', 'iPad', 'Windows Phone',
        'webOS', 'BlackBerry', 'iPod', 'Opera Mini', 'IEMobile'
    ];
    
    foreach ($mobileKeywords as $keyword) {
        if (stripos($userAgent, $keyword) !== false) {
            return true;
        }
    }
    
    return false;
}

/**
 * Sanitize and validate input
 * @param mixed $input Input to sanitize
 * @param string $type Type of input (string, int, float, email, url)
 * @return mixed Sanitized input or false if invalid
 */
function sanitizeInput($input, $type = 'string') {
    if ($input === null) {
        return false;
    }
    
    switch ($type) {
        case 'string':
            return filter_var($input, FILTER_SANITIZE_STRING);
        case 'int':
            return filter_var($input, FILTER_VALIDATE_INT);
        case 'float':
            return filter_var($input, FILTER_VALIDATE_FLOAT);
        case 'email':
            return filter_var($input, FILTER_VALIDATE_EMAIL);
        case 'url':
            return filter_var($input, FILTER_VALIDATE_URL);
        default:
            return false;
    }
}

/**
 * Log error with timestamp and context
 * @param string $message Error message
 * @param array $context Additional context
 */
function logError($message, $context = []) {
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] $message";
    
    if (!empty($context)) {
        $logMessage .= " Context: " . json_encode($context);
    }
    
    error_log($logMessage);
}

/**
 * Get location information using ip-api.com
 * @param string $ip IP address to check
 * @return array Location information
 */
function get_location_info($ip) {
    try {
        // Add timeout to prevent hanging
        $ctx = stream_context_create([
            'http' => [
                'timeout' => 3 // 3 seconds timeout
            ]
        ]);
        
        $response = @file_get_contents("http://ip-api.com/json/{$ip}", false, $ctx);
        
        if ($response === false) {
            throw new Exception("Failed to fetch IP data");
        }
        
        // Decode JSON properly
        $data = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Invalid JSON response");
        }
        
        // Return data directly from JSON if possible
        if (isset($data['status']) && $data['status'] === 'success') {
            return [
                'country' => $data['country'] ?? 'Unknown',
                'region' => $data['regionName'] ?? 'Unknown',
                'city' => $data['city'] ?? 'Unknown',
                'isp' => $data['isp'] ?? 'Unknown',
                'timezone' => $data['timezone'] ?? 'UTC'
            ];
        }
        
        throw new Exception("API returned unsuccessful status");
        
    } catch (Exception $e) {
        error_log("Location info error for IP {$ip}: " . $e->getMessage());
        return [
            'country' => 'Unknown',
            'region' => 'Unknown',
            'city' => 'Unknown',
            'isp' => 'Unknown',
            'timezone' => 'UTC'
        ];
    }
}

function get_os_version($user_agent) {
    if (empty($user_agent)) {
        return 'Unknown OS Platform';
    }

    $os_array = [
        '/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.2/i'     =>  'Windows Server 2003/XP x64',
        '/windows nt 5.1/i'     =>  'Windows XP',
        '/windows xp/i'         =>  'Windows XP',
        '/windows nt 5.0/i'     =>  'Windows 2000',
        '/windows me/i'         =>  'Windows ME',
        '/win98/i'              =>  'Windows 98',
        '/win95/i'              =>  'Windows 95',
        '/win16/i'              =>  'Windows 3.11',
        '/macintosh|mac os x/i' =>  'Mac OS X',
        '/mac_powerpc/i'        =>  'Mac OS 9',
        '/linux/i'              =>  'Linux',
        '/ubuntu/i'             =>  'Ubuntu',
        '/iphone/i'             =>  'iPhone',
        '/ipod/i'               =>  'iPod',
        '/ipad/i'               =>  'iPad',
        '/android/i'            =>  'Android',
        '/blackberry/i'         =>  'BlackBerry',
        '/webos/i'              =>  'Mobile'
    ];

    foreach ($os_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            return $value;
        }
    }

    return 'Unknown OS Platform';
}

function get_browser_name($user_agent) {
    if (empty($user_agent)) {
        return 'Unknown';
    }

    // More specific checks first
    if (preg_match('/Opera|OPR\//', $user_agent)) return 'Opera';
    if (preg_match('/Edg\/|Edge\//', $user_agent)) return 'Edge';
    if (preg_match('/Chrome\//', $user_agent)) return 'Chrome';
    if (preg_match('/Firefox\//', $user_agent)) return 'Firefox';
    if (preg_match('/Safari\//', $user_agent) && !preg_match('/Chrome\//', $user_agent)) return 'Safari';
    if (preg_match('/MSIE|Trident\/7/', $user_agent)) return 'Internet Explorer';
    
    return 'Unknown';
}

function is_mobile() {
    if (!isset($_SERVER["HTTP_USER_AGENT"])) {
        return false;
    }
    
    $mobile_agents = [
        'Mobile', 'Android', 'Silk/', 'Kindle',
        'BlackBerry', 'Opera Mini', 'Opera Mobi'
    ];
    
    $user_agent = $_SERVER["HTTP_USER_AGENT"];
    
    foreach ($mobile_agents as $agent) {
        if (stripos($user_agent, $agent) !== false) {
            return true;
        }
    }
    
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $user_agent);
}

// Helper function to safely handle API failures
function is_valid_ip($ip) {
    return filter_var($ip, FILTER_VALIDATE_IP) !== false;
}


?>