<?php
declare(strict_types=1);
require __DIR__ . '/config.php';

session_start();

$notice = null;
$error = null;

// ------------------------------------------------------------------ logout
if (isset($_GET['logout'])) {
    $_SESSION = [];
    session_destroy();
    header('Location: index.php');
    exit;
}

$needsSetup = !password_is_set();
$authed = !$needsSetup && !empty($_SESSION['authed']);
$post = ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST';

// --------------------------------------------------------- first-run setup
if ($needsSetup && $post && isset($_POST['new_password'])) {
    $pw = (string) $_POST['new_password'];
    if (mb_strlen($pw) < MIN_PASSWORD_LEN) {
        $error = '密码太短，至少 ' . MIN_PASSWORD_LEN . ' 位。';
    } elseif ($pw !== (string) ($_POST['confirm_password'] ?? '')) {
        $error = '两次输入的密码不一样。';
    } elseif (!set_password($pw)) {
        $error = '写入失败 —— 检查 data/ 目录是否可写（权限 755）。';
    } else {
        session_regenerate_id(true);
        $_SESSION['authed'] = true;
        $_SESSION['csrf'] = bin2hex(random_bytes(16));
        header('Location: index.php');
        exit;
    }
}

// ------------------------------------------------------------------- login
if (!$needsSetup && !$authed && $post && isset($_POST['password'])) {
    $attempts = (int) ($_SESSION['attempts'] ?? 0);
    $lockedUntil = (int) ($_SESSION['locked_until'] ?? 0);

    if ($lockedUntil > time()) {
        $error = '尝试次数过多，请等 ' . ($lockedUntil - time()) . ' 秒后再试。';
    } elseif (check_password((string) $_POST['password'])) {
        session_regenerate_id(true);
        $_SESSION['authed'] = true;
        $_SESSION['attempts'] = 0;
        $_SESSION['csrf'] = bin2hex(random_bytes(16));
        header('Location: index.php');
        exit;
    } else {
        $attempts++;
        $_SESSION['attempts'] = $attempts;
        if ($attempts >= MAX_ATTEMPTS) {
            $_SESSION['locked_until'] = time() + LOCKOUT_SECONDS;
            $_SESSION['attempts'] = 0;
            $error = '密码错误次数过多，已锁定 ' . LOCKOUT_SECONDS . ' 秒。';
        } else {
            $error = '密码错误。剩余尝试次数：' . (MAX_ATTEMPTS - $attempts);
        }
    }
}

// --------------------------------------------------------------- save link
if ($authed && $post && isset($_POST['link'])) {
    if (!hash_equals((string) ($_SESSION['csrf'] ?? ''), (string) ($_POST['csrf'] ?? ''))) {
        $error = '会话已过期，请重新提交。';
    } else {
        $url = trim((string) $_POST['link']);
        // Only http(s) — a javascript: or data: URL here would be an XSS hole,
        // since this string lands in an href on the public page.
        $ok = filter_var($url, FILTER_VALIDATE_URL) !== false
            && preg_match('~^https?://~i', $url) === 1;
        if (!$ok) {
            $error = '链接格式不对，必须是完整的 http:// 或 https:// 地址。';
        } elseif (save_link($url)) {
            $notice = '已保存，前台立即生效。';
        } else {
            $error = '写入失败 —— 检查 data/ 目录是否可写（权限 755，文件 644）。';
        }
    }
}

$current = load_link();
$csrf = (string) ($_SESSION['csrf'] ?? '');
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Landing 后台 — 换链接</title>
<style>
  :root { color-scheme: dark; }
  * { box-sizing: border-box; }
  body {
    margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
    padding: 24px; background: #12123a; color: #f2f2f7;
    font: 15px/1.6 system-ui, "Segoe UI", -apple-system, sans-serif;
  }
  .card {
    width: 100%; max-width: 560px; padding: 32px; border-radius: 14px;
    background: #1c1c54; box-shadow: 0 18px 50px rgba(0,0,0,.45);
  }
  h1 { margin: 0 0 4px; font-size: 21px; }
  .sub { margin: 0 0 24px; color: #a3a3d0; font-size: 13px; }
  label { display: block; margin: 14px 0 7px; font-size: 13px; color: #c9c9ea; }
  label:first-of-type { margin-top: 0; }
  input[type=text], input[type=password] {
    width: 100%; padding: 12px 14px; border: 1px solid #3a3a7d; border-radius: 8px;
    background: #14143f; color: #fff; font-size: 15px; font-family: inherit;
  }
  input:focus { outline: 2px solid #ff5a2b; outline-offset: 1px; border-color: transparent; }
  button {
    margin-top: 18px; width: 100%; padding: 13px; border: 0; border-radius: 8px;
    background: linear-gradient(180deg, #ff5a2b, #ff2400); color: #fff;
    font-size: 16px; font-weight: 700; font-family: inherit; cursor: pointer;
  }
  button:hover { filter: brightness(1.08); }
  .msg { margin: 0 0 18px; padding: 11px 14px; border-radius: 8px; font-size: 14px; }
  .ok  { background: #14401f; color: #8ff0a4; }
  .bad { background: #4a1620; color: #ffb3b3; }
  .current {
    margin: 0 0 22px; padding: 14px; border-radius: 8px; background: #14143f;
    border: 1px solid #2c2c66;
  }
  .current b { display: block; margin-bottom: 6px; font-size: 12px; color: #a3a3d0; font-weight: 600; }
  .current a { color: #ffb27a; word-break: break-all; }
  .meta { margin-top: 8px; font-size: 12px; color: #7d7db0; }
  .hint { margin: 10px 0 0; font-size: 12px; line-height: 1.7; color: #7d7db0; }
  .foot { margin-top: 22px; font-size: 12px; color: #7d7db0; }
  .foot a { color: #a3a3d0; }
</style>
</head>
<body>
<div class="card">

<?php if ($needsSetup): ?>
  <h1>第一次使用 — 设置密码</h1>
  <p class="sub">这个后台还没有密码。现在设一个，只有你知道。</p>
  <?php if ($error): ?><p class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES) ?></p><?php endif; ?>
  <form method="post" autocomplete="off">
    <label for="new_password">新密码（至少 <?= MIN_PASSWORD_LEN ?> 位）</label>
    <input type="password" id="new_password" name="new_password" required autofocus>
    <label for="confirm_password">再输一次</label>
    <input type="password" id="confirm_password" name="confirm_password" required>
    <button type="submit">设置并登录</button>
  </form>
  <p class="hint">密码只存哈希，存在 <code>data/auth.json</code>。忘了就删掉那个文件，回到这一步重设。</p>

<?php elseif (!$authed): ?>
  <h1>后台登录</h1>
  <p class="sub">Sweet Bonanza landing — 链接管理</p>
  <?php if ($error): ?><p class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES) ?></p><?php endif; ?>
  <form method="post" autocomplete="off">
    <label for="password">密码</label>
    <input type="password" id="password" name="password" required autofocus>
    <button type="submit">登录</button>
  </form>

<?php else: ?>
  <h1>换链接</h1>
  <p class="sub">改完保存，落地页的按钮立刻指向新地址，不用重新上传任何文件。</p>

  <?php if ($notice): ?><p class="msg ok"><?= htmlspecialchars($notice, ENT_QUOTES) ?></p><?php endif; ?>
  <?php if ($error): ?><p class="msg bad"><?= htmlspecialchars($error, ENT_QUOTES) ?></p><?php endif; ?>

  <div class="current">
    <b>当前生效的链接</b>
    <a href="<?= htmlspecialchars($current['link'], ENT_QUOTES) ?>" target="_blank" rel="noopener">
      <?= htmlspecialchars($current['link'], ENT_QUOTES) ?>
    </a>
    <?php if (!empty($current['updated'])): ?>
      <div class="meta">最后修改：<?= htmlspecialchars($current['updated'], ENT_QUOTES) ?></div>
    <?php endif; ?>
  </div>

  <form method="post" autocomplete="off">
    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES) ?>">
    <label for="link">新链接（必须 http:// 或 https:// 开头）</label>
    <input type="text" id="link" name="link" required
           value="<?= htmlspecialchars($current['link'], ENT_QUOTES) ?>"
           placeholder="https://your-offer-link.com/abc">
    <button type="submit">保存</button>
  </form>
  <p class="hint">访客地址栏上的参数（<code>?st=</code>、<code>s1</code>…<code>s5</code> 这些）会自动拼到这个链接后面，分包统计不会丢。</p>

  <p class="foot">
    <a href="../index.html" target="_blank">预览落地页</a> ·
    <a href="?logout=1">退出登录</a>
  </p>
<?php endif; ?>

</div>
</body>
</html>
