<?php
/**
 * 木漏茶室论坛 · 单一入口
 */

require __DIR__ . '/inc/bootstrap.php';
require __DIR__ . '/inc/view.php';

// 页面 HTML 走协商缓存，避免手机浏览器继续显示升级前的桌面视口。
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET' && !headers_sent()) {
    header('Cache-Control: no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
}

// 安装完成后的一次性自动登录（成功一次后凭据立即失效）
if (isset($_GET['install_login'])) {
    $installGo = ($_GET['go'] ?? '') === 'admin' ? 'admin' : 'home';
    if (install_login_consume((string) $_GET['install_login'], $installGo)) {
        redirect(page_url($installGo));
    }
    redirect(page_url('home'));
}

$routes = [
    'home'          => 'home.php',
    'post'          => 'post.php',
    'review'        => 'review.php',
    'compose'       => 'compose.php',
    'login'         => 'login.php',
    'register'      => 'register.php',
    'forgot'        => 'forgot.php',
    'logout'        => 'logout.php',
    'profile'       => 'profile.php',
    'ip_history'    => 'ip_history.php',
    'user'          => 'user.php',
    'users'         => 'users.php',
    'platform_users'=> 'platform_users.php',
    'comments'      => 'comments.php',
    'messages'      => 'messages.php',
    'friends'       => 'friends.php',
    'notifications' => 'notifications.php',
    'verify'        => 'verify.php',
    'verify_email'  => 'verify_email.php',
    'tag'           => 'tag.php',
    'search'        => 'search.php',
    'followers'     => 'followers.php',
    'extensions'    => 'extensions.php',
    'ext_manage'    => 'ext_manage.php',
    'plugin_mall'    => 'plugin_mall.php',
    'official_notify'=> 'official_notify.php',
    'gallery'       => 'gallery.php',
    'netdisk'       => 'netdisk.php',
    'chat'          => 'chat.php',
    'links'         => 'links.php',
    'link_out'      => 'link_out.php',
    'ext_out'       => 'ext_out.php',
    'source'        => 'source.php',
    'source_author' => 'source_author.php',
    'install_guide' => 'install_guide.php',
    'tutorial'      => 'tutorial.php',
    'security_guard'=> 'security_guard.php',
    'deploy'        => 'deploy.php',
    'world'         => 'world.php',
    'announcements' => 'announcements.php',
    'announcement'  => 'announcement.php',
    'admin'         => 'admin.php',
    'blackroom'     => 'blackroom.php',
    'plugin_manager'=> 'plugin_manager.php',
];

$page = strtolower(preg_replace('/[^a-z_]/', '', $_GET['page'] ?? 'home'));
if (!isset($routes[$page])) {
    $page = 'home';
}
$GLOBALS['PAGE'] = $page;
if (($page !== 'admin') && (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET')) { analytics_track_view(); }

// ---------- 退出代登录（前台入口，代登录普通用户也能使用） ----------
if (($page === 'home' || $page === 'profile') && strtolower((string) ($_GET['act'] ?? '')) === 'stop_impersonate' && impersonating()) {
    unset($_SESSION['imp_uid']);
    flash('已退出代登录，恢复管理员身份');
    redirect(page_url('home'));
}

// ---------- 注册邮箱验证门槛（管理员与允许页面不受影响） ----------
$verifyGateUser = current_user();
if (setting('email_verify_required', '0') === '1' && $verifyGateUser && !is_admin($verifyGateUser)
    && (int) ($verifyGateUser['email_verified'] ?? 0) !== 1
    && !in_array($page, ['verify_email', 'profile', 'logout', 'login'], true)
    && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    flash('请先完成邮箱验证，再使用论坛功能', 'err');
    redirect(page_url('verify_email'));
}

// ---------- 维护模式 ----------
if (setting('maintenance') === '1') {
    $adminView = is_admin(current_user());
    $allowed = ['login', 'admin'];
    if (!$adminView && !in_array($page, $allowed, true)) {
        http_response_code(503);
        $siteName = setting('site_name', '木漏茶室');
        $maintVideo = trim((string) setting('maintenance_video', ''));
        $maintVideoUrl = $maintVideo !== '' ? upload_url($maintVideo) : '';
        ?>
<!DOCTYPE html>
<html lang="<?= e(km_html_lang()) ?>" data-theme="<?= e(setting('theme_mode', 'light')) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>维护中 · <?= e($siteName) ?></title>
<link rel="stylesheet" href="<?= e(asset('css/app.css')) ?>">
</head>
<body class="maint-body<?= $maintVideoUrl !== '' ? ' has-video' : '' ?>">
<div class="maint-card<?= $maintVideoUrl !== '' ? ' has-video' : '' ?>">
  <?php if ($maintVideoUrl !== ''): ?>
  <video class="maint-video" id="maintVideo" autoplay muted loop playsinline webkit-playsinline preload="auto">
    <source src="<?= e($maintVideoUrl) ?>">
  </video>
  <span class="maint-video-shade" aria-hidden="true"></span>
  <button class="maint-sound is-muted" id="maintSound" type="button" aria-pressed="false" aria-label="开启视频声音" title="开启视频声音">
    <svg class="maint-ico maint-ico-on" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M6 9H3.5v6H6l4.5 3.5V5.5L6 9z"/><path d="M14 8.5c1.7 1.8 1.7 5.2 0 7"/><path d="M17 6c3 3.2 3 8.8 0 12"/></svg>
    <svg class="maint-ico maint-ico-off" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M6 9H3.5v6H6l4.5 3.5V5.5L6 9z"/><path d="M15 9.5l5 5M20 9.5l-5 5"/></svg>
  </button>
  <?php endif; ?>
  <div class="maint-content">
    <div class="maint-copy">
      <div class="maint-snow">❄</div>
      <h1><?= e($siteName) ?></h1>
      <p><?= nl2br(e(setting('maintenance_text', '茶室正在进行清扫，稍后再来。'))) ?></p>
      <a class="<?= $maintVideoUrl !== '' ? 'btn-ghost maint-login ghost-light' : 'btn-primary maint-login' ?>" href="<?= e(page_url('login')) ?>">管理员登录</a>
    </div>
  </div>
</div>
<?php if ($maintVideoUrl !== ''): ?>
<script>
(function () {
  var video = document.getElementById('maintVideo');
  var btn = document.getElementById('maintSound');
  if (!video || !btn) return;
  video.muted = true;
  video.loop = true;
  video.volume = 1;
  function sync() {
    var muted = !!video.muted;
    btn.classList.toggle('is-muted', muted);
    btn.setAttribute('aria-pressed', muted ? 'false' : 'true');
    var label = muted ? '开启视频声音' : '关闭视频声音';
    btn.setAttribute('aria-label', label);
    btn.setAttribute('title', label);
  }
  btn.addEventListener('click', function () {
    var muteNow = !video.muted;
    video.muted = muteNow;
    if (!muteNow) {
      video.volume = 1;
      var playing = video.play();
      if (playing && playing.catch) {
        playing.catch(function () { video.muted = true; sync(); });
      }
    }
    sync();
  });
  video.addEventListener('volumechange', sync);
  var boot = video.play();
  if (boot && boot.catch) boot.catch(function () {});
  sync();
})();
</script>
<?php endif; ?>
</body>
</html>
        <?php
        exit;
    }
}

require __DIR__ . '/pages/' . $routes[$page];
