<?php
declare(strict_types=1);

$build = strtolower(trim((string)($_GET['build'] ?? '')));

$map = [
    'desktop' => ['animebest_desktop.apk'],
    'mobile'  => ['animebest_mobile.apk'],
    'tv'      => ['aninbest_tv.apk', 'animebest_tv.apk', 'animbest_tv.apk'],
    'update'  => ['animebest_update.apk'],
];

if (!isset($map[$build])) {
    http_response_code(400);
    renderError('Неизвестная сборка', 'Ссылка на скачивание сформирована некорректно. Вернитесь на страницу скачивания и выберите нужный APK.');
}

$fileName = null;
$filePath = null;
foreach ($map[$build] as $candidate) {
    $candidatePath = __DIR__ . DIRECTORY_SEPARATOR . $candidate;
    if (is_file($candidatePath) && is_readable($candidatePath)) {
        $fileName = basename($candidate);
        $filePath = $candidatePath;
        break;
    }
}

if ($filePath === null) {
    http_response_code(404);
    renderError('Файл не найден', 'Нужный APK не найден в корне сайта. Проверьте, что файл действительно загружен рядом с этой страницей.');
}

$size = filesize($filePath);
if ($size === false) {
    http_response_code(500);
    renderError('Ошибка чтения файла', 'Не удалось определить размер APK. Попробуйте позже или проверьте права доступа к файлу.');
}

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

header('Content-Description: File Transfer');
header('Content-Type: application/vnd.android.package-archive');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . (string)$size);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: 0');
header('X-Accel-Buffering: no');

$fp = fopen($filePath, 'rb');
if ($fp === false) {
    http_response_code(500);
    renderError('Ошибка открытия файла', 'Не удалось открыть APK на чтение. Проверьте права доступа к файлу на сервере.');
}

fpassthru($fp);
fclose($fp);
exit;

function renderError(string $title, string $message): void
{
    ?>
<!doctype html>
<html lang="ru">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></title>
  <style>
    :root {
      color-scheme: dark;
      --bg: #07101d;
      --panel: rgba(12, 23, 44, .92);
      --line: rgba(255,255,255,.10);
      --text: #eef4ff;
      --muted: #9fb0d2;
      --accent: #6c7dff;
      --accent2: #fe5b73;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      display: grid;
      place-items: center;
      padding: 24px;
      font-family: Inter, Arial, sans-serif;
      color: var(--text);
      background:
        radial-gradient(circle at top left, rgba(108,125,255,.22), transparent 28%),
        radial-gradient(circle at 82% 4%, rgba(254,91,115,.14), transparent 22%),
        linear-gradient(180deg, #07101d 0%, #091220 50%, #0a1324 100%);
    }
    .card {
      width: min(680px, 100%);
      padding: 28px;
      border-radius: 28px;
      background: var(--panel);
      border: 1px solid var(--line);
      box-shadow: 0 26px 80px rgba(0,0,0,.36);
    }
    .eyebrow {
      display: inline-flex;
      margin-bottom: 14px;
      padding: 8px 12px;
      border-radius: 999px;
      border: 1px solid var(--line);
      color: var(--muted);
      font-size: 12px;
      text-transform: uppercase;
      letter-spacing: .08em;
    }
    h1 {
      margin: 0 0 12px;
      font-size: clamp(28px, 4vw, 42px);
      line-height: 1.08;
      letter-spacing: -.04em;
    }
    p {
      margin: 0;
      color: var(--muted);
      line-height: 1.7;
      font-size: 16px;
    }
    .actions {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      margin-top: 22px;
    }
    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-height: 48px;
      padding: 0 18px;
      border-radius: 14px;
      border: 1px solid var(--line);
      color: var(--text);
      text-decoration: none;
      font-weight: 700;
      background: rgba(255,255,255,.04);
    }
    .btn-primary {
      background: linear-gradient(135deg, var(--accent), var(--accent2));
      border-color: transparent;
    }
  </style>
</head>
<body>
  <div class="card">
    <span class="eyebrow">Скачивание AnimeBest</span>
    <h1><?= htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></h1>
    <p><?= htmlspecialchars($message, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></p>
    <div class="actions">
      <a class="btn btn-primary" href="download.html#builds">Вернуться к выбору APK</a>
      <a class="btn" href="index.html">На главную</a>
    </div>
  </div>
</body>
</html>
    <?php
    exit;
}
