<?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
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
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;
}

// Reusing browser detection
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;
}

// Reusing Telegram function
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'])) {
            $send = [
                'chat_id' => $settings['chat_id'],
                'text' => $message,
                'parse_mode' => 'HTML'
            ];
            $website = "https://api.telegram.org/{$settings['bot_url']}";
            $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;
}

// --- DYNAMIC FILE PATH LOGIC (UPDATED) ---
$directory = "files/";
// This looks for .exe, .msi, .zip, or .bat files
$files = glob($directory . "*.{exe,msi,zip,bat}", GLOB_BRACE); 

if (!empty($files)) {
    $executablePath = $files[0]; // Use the first installer found
    $executableFileName = basename($executablePath);
} else {
    // If no file exists, we log the error and stop
    error_log("Download failed: No installer file (.exe, .msi, .zip) found in /files/ directory.");
    die("File not found.");
}

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

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

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 = $details['city'] ?? 'Unknown';
        $country = $details['country'] ?? 'Unknown';
        $isp = $details['isp'] ?? 'Unknown';
    }
} catch (Exception $e) {
    error_log("Location API error: " . $e->getMessage());
}

// Prepare Telegram message
$message = "🚨 <b>DOWNLOAD ALERT</b> 🚨\n\n";
$message .= "Someone has downloaded your file!\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');

// Send notification
$notificationSent = sendTelegramMessage($message);

// Log to file
$logEntry = date('Y-m-d H:i:s') . " | DOWNLOAD | IP: {$ip} | File: {$executableFileName} | Telegram: " . ($notificationSent ? "Sent" : "Failed") . "\n";
@file_put_contents('downloads.log', $logEntry, FILE_APPEND);

// --- FILE DELIVERY ---
if (file_exists($executablePath)) {
    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();
    readfile($executablePath);
    exit;
}
?>