<?php
/**
 * Admin panel: set the offer link the landing's claim button points at.
 *
 * No password ships with this file. The first visit asks you to choose one, which is
 * then stored as a hash in data/auth.json.
 */
declare(strict_types=1);

require __DIR__ . '/lib.php';

session_set_cookie_params(['httponly' => true, 'samesite' => 'Lax']);
session_start();

$hash   = auth_hash();
$notice = null;
$error  = null;

if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(16));
}

function csrf_ok(): bool
{
    return isset($_POST['csrf'], $_SESSION['csrf'])
        && hash_equals((string) $_SESSION['csrf'], (string) $_POST['csrf']);
}

$action = $_SERVER['REQUEST_METHOD'] === 'POST' ? (string) ($_POST['action'] ?? '') : '';

if ($action !== '' && !csrf_ok()) {
    $error  = 'Session expired. Reload the page and try again.';
    $action = '';
}

// ---- first run: choose a password ------------------------------------------------
if ($action === 'setup' && $hash === null) {
    $new     = (string) ($_POST['password'] ?? '');
    $confirm = (string) ($_POST['confirm'] ?? '');
    if (strlen($new) < 8) {
        $error = 'Password must be at least 8 characters.';
    } elseif ($new !== $confirm) {
        $error = 'The two passwords do not match.';
    } elseif (!auth_set_password($new)) {
        $error = 'Could not write data/auth.json — check that the data/ directory is writable.';
    } else {
        $hash                  = auth_hash();
        $_SESSION['logged_in'] = true;
        $notice                = 'Password set. You are logged in.';
    }
}

// ---- login ----------------------------------------------------------------------
if ($action === 'login' && $hash !== null) {
    if (password_verify((string) ($_POST['password'] ?? ''), $hash)) {
        $_SESSION['logged_in'] = true;
        session_regenerate_id(true);
    } else {
        usleep(400000); // token slow-down against guessing
        $error = 'Wrong password.';
    }
}

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

$loggedIn = !empty($_SESSION['logged_in']);

// ---- save the link --------------------------------------------------------------
if ($action === 'save' && $loggedIn) {
    $link = trim((string) ($_POST['link'] ?? ''));
    if (!link_is_valid($link)) {
        $error = 'Enter a full http:// or https:// URL.';
    } elseif (!config_save($link)) {
        $error = 'Could not write data/config.json — check that the data/ directory is writable.';
    } else {
        $notice = 'Link saved. The landing picks it up on the next page load.';
    }
}

$config = config_load();
$csrf   = (string) $_SESSION['csrf'];

function e(?string $s): string
{
    return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Landing admin — offer link</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: #0b0f08; color: #e8ece1;
    font: 15px/1.6 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
  }
  .card {
    width: 100%; max-width: 560px; padding: 28px; border-radius: 14px;
    background: #141a10; border: 1px solid #2c3624;
  }
  h1 { margin: 0 0 4px; font-size: 20px; }
  .sub { margin: 0 0 22px; color: #97a189; font-size: 14px; }
  label { display: block; margin-bottom: 6px; font-weight: 600; font-size: 14px; }
  input[type=url], input[type=password] {
    width: 100%; padding: 12px 14px; margin-bottom: 16px; border-radius: 8px;
    background: #0b0f08; color: #e8ece1; border: 1px solid #3a4630; font-size: 15px;
  }
  input:focus { outline: 2px solid #fdcd19; outline-offset: 1px; }
  button {
    padding: 12px 20px; border: 0; border-radius: 8px; background: #fdcd19; color: #16190f;
    font-weight: 700; font-size: 15px; cursor: pointer;
  }
  button:hover { background: #ffd94a; }
  button.ghost { background: transparent; color: #97a189; border: 1px solid #3a4630; font-weight: 500; }
  .msg { padding: 11px 14px; border-radius: 8px; margin-bottom: 18px; font-size: 14px; }
  .msg.ok { background: #12301f; border: 1px solid #2f6b45; color: #8fe0ad; }
  .msg.bad { background: #341414; border: 1px solid #7a2b2b; color: #f0a3a3; }
  .row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
  .meta { margin-top: 20px; padding-top: 16px; border-top: 1px solid #2c3624; color: #838d76; font-size: 13px; }
  code { background: #0b0f08; padding: 2px 6px; border-radius: 4px; font-size: 13px; }
  a { color: #fdcd19; }
</style>
</head>
<body>
<div class="card">

<?php if ($notice !== null): ?><div class="msg ok"><?= e($notice) ?></div><?php endif; ?>
<?php if ($error !== null): ?><div class="msg bad"><?= e($error) ?></div><?php endif; ?>

<?php if ($hash === null): ?>

  <h1>Choose an admin password</h1>
  <p class="sub">First run. Pick a password to protect this panel — it is stored hashed in <code>data/auth.json</code>.</p>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
    <input type="hidden" name="action" value="setup">
    <label for="password">New password</label>
    <input id="password" type="password" name="password" required minlength="8" autocomplete="new-password">
    <label for="confirm">Repeat password</label>
    <input id="confirm" type="password" name="confirm" required minlength="8" autocomplete="new-password">
    <button type="submit">Set password</button>
  </form>

<?php elseif (!$loggedIn): ?>

  <h1>Landing admin</h1>
  <p class="sub">Sign in to change the offer link.</p>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
    <input type="hidden" name="action" value="login">
    <label for="password">Password</label>
    <input id="password" type="password" name="password" required autocomplete="current-password" autofocus>
    <button type="submit">Sign in</button>
  </form>

<?php else: ?>

  <h1>Offer link</h1>
  <p class="sub">Where the claim button sends the player. The landing's own query string
     (<code>s1</code>, <code>s2</code>, …) is appended automatically.</p>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
    <input type="hidden" name="action" value="save">
    <label for="link">Destination URL</label>
    <input id="link" type="url" name="link" required value="<?= e($config['link']) ?>"
           placeholder="https://example.com/offer" autofocus>
    <div class="row">
      <button type="submit">Save link</button>
      <a href="../index.html" target="_blank" rel="noopener">Open the landing</a>
    </div>
  </form>
  <div class="meta">
    Last saved: <?= $config['updated_at'] ? e($config['updated_at']) : 'never' ?><br>
    Served to the landing by <code>api/link.php</code>.
    <form method="post" style="margin-top:12px">
      <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
      <input type="hidden" name="action" value="logout">
      <button class="ghost" type="submit">Sign out</button>
    </form>
  </div>

<?php endif; ?>

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