<?php
/**
 * 子汐课程表 · APK 下载重定向（物理文件，伪静态 /download 指向此处）
 *
 * 逻辑：读取 app_version 表中 active=1、version_code 最大的一条，
 *   - 有 download_url → 302 跳转到 APK 直链；
 *   - 无发布记录 / URL 异常 / 数据库不可用 → 渲染友好的回落提示页（不 404、不白屏）。
 * 不改动任何接口契约，仅作展示层重定向。
 */

declare(strict_types=1);
header('Content-Type: text/html; charset=utf-8');

$url = '';
$versionName = '';

try {
    require __DIR__ . '/api/db.php';
    $row = db()->query(
        'SELECT version_name, download_url FROM app_version
         WHERE active = 1 ORDER BY version_code DESC, id DESC LIMIT 1'
    )->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $versionName = (string) $row['version_name'];
        $candidate   = trim((string) $row['download_url']);
        if (preg_match('#^https?://#i', $candidate)) {
            $url = $candidate;
        }
    }
} catch (Throwable $e) {
    // 数据库不可用时静默回落，页面给出提示
    $url = '';
}

if ($url !== '') {
    header('Cache-Control: no-store');
    header('Location: ' . $url, true, 302);
    exit;
}

$hint = $versionName !== ''
    ? 'v' . htmlspecialchars($versionName, ENT_QUOTES) . ' 的下载链接暂不可用'
    : '服务器暂未发布任何版本';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>下载暂不可用 · 子汐课程表</title>
  <link rel="stylesheet" href="assets/site.css?v=20260923">
</head>
<body>
  <main class="wrap" style="min-height:70vh;display:flex;align-items:center;justify-content:center">
    <div style="text-align:center;max-width:26em">
      <p class="sec-eyebrow">DOWNLOAD</p>
      <h1 class="sec-title" style="font-size:26px"><?= $hint ?></h1>
      <p class="sec-lede" style="margin-bottom:26px">请稍后重试，或联系作者（QQ 1220483277）。也可以先访问在线课表工具查看与编辑课表。</p>
      <p>
        <a class="btn-primary" href="index.html">返回官网首页</a>&nbsp;
        <a class="btn-ghost" href="webapp.html">在线课表</a>
      </p>
      <p style="margin-top:34px;font-size:12px">
        <a class="icp-link" href="https://beian.miit.gov.cn/" target="_blank" rel="noopener nofollow">陇ICP备2026007822号-1</a>
      </p>
    </div>
  </main>
</body>
</html>
