<?php
date_default_timezone_set('Asia/Shanghai');
/**
 * 验证页（入口）
 *  - 第一次访问：显示表单
 *  - 提交密钥：动态密钥 = 当前服务器时间的 MMDDHHmm（接受 ±1 分钟宽容）
 *  - 实时显示服务器时间（精确到秒）
 *  - 正确则跳转到 generate.php
 */

// 不缓存
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

// 站点标题（验证页 / 生成页 / 假条页统一显示）
const SITE_TITLE = '条成器';

// 删除宝塔/Nginx 注入的 HTTP_Path cookie（避免泄露服务器文件系统路径）
// 这一行必须在任何输出之前，且必须放在 session_start() 之前
if (isset($_COOKIE['HTTP_Path'])) {
    setcookie('HTTP_Path', '', time() - 42000, '/', '', false, false);
    unset($_COOKIE['HTTP_Path']);
}

// 短 session 有效期：仅用于本次跳转，生成假条后会被销毁
ini_set('session.gc_maxlifetime', '60');
session_set_cookie_params([
    'lifetime' => 0,
    'path'     => '/',
    'domain'   => '',
    'secure'   => false,
    'httponly' => true,
    'samesite' => 'Lax',
]);
session_start();

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $key = trim($_POST['key'] ?? '');

    // 彩蛋：输入"青岛农业大学" → 弹窗"验证成功" + 跳转至青岛农业大学官网（不设置 session）
    if ($key === '青岛农业大学') {
        ?><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证成功</title>
<style>
html,body{margin:0;padding:0;height:100%;background:#fbf6ec;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;display:flex;align-items:center;justify-content:center;color:#4a3f30;}
.box{text-align:center;padding:24px;}
.box p{margin:8px 0;font-size:15px;color:#6b5d48;}
</style>
</head>
<body>
<div class="box"><p>正在跳转至青岛农业大学官网…</p></div>
<script>
alert('验证成功');
window.location.replace('https://www.qau.edu.cn/');
</script>
</body>
</html><?php
        exit;
    }

    // 动态密钥：当前分钟 ±1 分钟都接受（避免边界卡顿）
    $nowKey    = date('mdHi');
    $prevKey   = date('mdHi', strtotime('-1 minute'));
    $nextKey   = date('mdHi', strtotime('+1 minute'));
    if (in_array($key, [$nowKey, $prevKey, $nextKey], true)) {
        $_SESSION['jt_authed'] = true;
        header('Location: generate.php');
        exit;
    }
    $err = '密钥不正确，请重新输入';
}

// 取消"已验证则直接跳转"逻辑：每次访问首页都显示认证表单（强制按次算）
// （POST 验证成功后通过 302 跳转到 generate.php，不依赖这里）

// 把当前服务器时间传给前端，JS 用它做实时校准
$serverNowYmd = date('Y-m-d');
$serverNowHis = date('H:i:s');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>访问验证 - <?= htmlspecialchars(SITE_TITLE) ?></title>
<style>
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; height: 100%; }
body {
    font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
    background: #f0ebe0;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 24px 16px;
    color: #4a3f30;
    -webkit-font-smoothing: antialiased;
}
.card {
    width: 100%;
    max-width: 420px;
    background: #fbf6ec;
    border-radius: 18px;
    box-shadow: 0 8px 30px rgba(80, 60, 30, 0.08);
    padding: 32px 28px;
}
.title {
    font-size: 26px;
    font-weight: 700;
    color: #4a3f30;
    margin: 0 0 18px;
    letter-spacing: 0.5px;
}
.question {
    font-size: 15px;
    color: #6b5d48;
    margin: 0 0 14px;
    line-height: 1.5;
}
.now {
    font-size: 13px;
    color: #8b7d68;
    margin: 0 0 22px;
    font-variant-numeric: tabular-nums;
}
.now strong { color: #4a3f30; font-weight: 600; }
.label {
    display: block;
    font-size: 14px;
    color: #4a3f30;
    margin: 0 0 10px;
    font-weight: 500;
}
.input {
    width: 100%;
    height: 48px;
    border: 1px solid #d8cfbb;
    border-radius: 10px;
    background: #fff;
    padding: 0 14px;
    font-size: 15px;
    color: #4a3f30;
    outline: none;
    transition: border-color 0.15s, box-shadow 0.15s;
    font-variant-numeric: tabular-nums;
    letter-spacing: 1px;
}
.input:focus { border-color: #8b7d68; box-shadow: 0 0 0 3px rgba(139,125,104,0.15); }

/* 密钥输入框：视觉效果与 password 一致（原点遮罩），但实际是 text，
   这样中文 IME 能正常工作，不会被浏览器强制切英文/数字键盘 */
.key-input {
    -webkit-text-security: disc;
    -moz-text-security: disc;
    text-security: disc;
}
.btn {
    width: 100%;
    height: 50px;
    margin-top: 22px;
    border: none;
    border-radius: 12px;
    background: #4a4035;
    color: #fbf6ec;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    letter-spacing: 1px;
    transition: background 0.15s, transform 0.05s;
}
.btn:active { background: #3a3127; transform: translateY(1px); }
.err {
    color: #b34a3a;
    background: #f9e6e0;
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 13px;
    margin-bottom: 12px;
    border: 1px solid #ecc7bd;
}
.footer {
    margin-top: 28px;
    font-size: 12px;
    color: #a09480;
}
</style>
</head>
<body>
<div class="card">
    <h1 class="title">访问验证</h1>
    <p class="question">学校的全名是什么？</p>
    <p class="now">当前时间：<strong><span id="server-clock"><?= htmlspecialchars("$serverNowYmd $serverNowHis") ?></span></strong></p>
    <?php if ($err): ?><div class="err"><?= htmlspecialchars($err) ?></div><?php endif; ?>
    <form method="post" autocomplete="off">
        <label class="label" for="key">请输入密钥</label>
        <input class="input key-input" type="text" id="key" name="key" placeholder="青岛农业大学" autocomplete="off" lang="zh-CN" required>
        <button class="btn" type="submit">验证并进入</button>
    </form>
</div>
<div class="footer"><?= htmlspecialchars(SITE_TITLE) ?></div>

<script>
// 兜底删除 HTTP_Path cookie（Nginx/宝塔面板注入的，会泄露服务器路径）
// 必须在 PHP 的 Set-Cookie 之后再删一次，确保浏览器最终没有这个 cookie
(function () {
    var name = 'HTTP_Path';
    // 多种 path/domain 组合都试一遍，确保能删掉
    var paths = ['/', '/generated', ''];
    var domains = ['', window.location.hostname, '.' + window.location.hostname];
    paths.forEach(function (p) {
        domains.forEach(function (d) {
            document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0'
                + (p ? '; path=' + p : '')
                + (d ? '; domain=' + d : '');
        });
    });
})();

// 实时显示服务器时间（精确到秒）
(function () {
    // 服务器当前时间（PHP 渲染时传入）
    var serverYmd = <?= json_encode($serverNowYmd) ?>;
    var serverHis = <?= json_encode($serverNowHis) ?>;

    // 把服务器时间解析成 UTC 时间戳（避免本地时区干扰）
    var serverLocalStr = serverYmd + ' ' + serverHis;
    var serverTs = new Date(serverLocalStr.replace(/-/g, '/')).getTime();
    var clientTsAtRender = Date.now();
    var drift = serverTs - clientTsAtRender;

    var clockEl = document.getElementById('server-clock');

    function pad(n) { return n < 10 ? '0' + n : '' + n; }

    function tick() {
        var now = new Date(Date.now() + drift);
        var y = now.getFullYear();
        var mo = pad(now.getMonth() + 1);
        var dd = pad(now.getDate());
        var hh = pad(now.getHours());
        var mi = pad(now.getMinutes());
        var ss = pad(now.getSeconds());
        if (clockEl) clockEl.textContent = y + '-' + mo + '-' + dd + ' ' + hh + ':' + mi + ':' + ss;
    }

    tick();
    setInterval(tick, 1000);
})();
</script>
</body>
</html>
