<?php
// AI Guessr – one-time setup page for the API key. The key is encrypted before it's saved.
require __DIR__ . '/secure.php';
$CONFIG = require __DIR__ . '/config.php';
header('Cache-Control: no-store');
header('X-Frame-Options: DENY');

$adminPw = (string)($CONFIG['admin_password'] ?? '');
$locked = $adminPw === '' || $adminPw === 'change-me';
$msg = '';
$ok = false;

function check_key_with_anthropic($key)
{
    if (!function_exists('curl_init')) return [true, 'Saved (could not test it: the PHP curl extension is missing).'];
    $ch = curl_init('https://api.anthropic.com/v1/models?limit=1');
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => ['x-api-key: ' . $key, 'anthropic-version: 2026-10-21'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);
    $raw = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($raw === false) return [true, 'Saved, but the server could not reach Anthropic to test it.'];
    if ($status === 401 || $status === 403) return [false, 'Anthropic rejected this key. Check that you copied all of it.'];
    return [true, 'Key works and is saved.'];
}

if (!$locked && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $pw = (string)($_POST['password'] ?? '');
    $key = trim((string)($_POST['api_key'] ?? ''));
    if (!hash_equals($adminPw, $pw)) {
        sleep(2); // slows down password guessing
        $msg = 'Wrong admin password.';
    } elseif (!preg_match('/^sk-ant-[A-Za-z0-9_\-]{20,}$/', $key)) {
        $msg = 'That doesn\'t look like an Anthropic API key (it should start with "sk-ant-").';
    } else {
        list($valid, $note) = check_key_with_anthropic($key);
        if (!$valid) {
            $msg = $note;
        } else {
            secure_protect_data();
            list($saved, $where) = secure_store_key($key);
            $ok = $saved;
            $msg = $saved ? $note : $where;
        }
    }
}

$info = secure_key_info();
list($secret, $secretWhere) = secure_get_secret(false);
$working = $info && secure_api_key() !== '';
$outside = $secretWhere && strpos($secretWhere, DATA_DIR) !== 0;
$h = function ($s) { 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">
  <title>AI Guessr Setup</title>
  <link href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@600;800&family=Nunito:wght@400;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
  <style>
    .setup { width: 100%; max-width: 480px; padding: 26px; display: flex; flex-direction: column; gap: 14px; }
    .note { padding: 10px 14px; border-radius: 12px; font-weight: 700; }
    .note.good { background: var(--good-soft); color: var(--good); }
    .note.bad { background: #ffe3e8; color: var(--brand-dark); }
    .note.info { background: var(--soft); color: var(--muted); }
    code { background: var(--soft); padding: 1px 6px; border-radius: 6px; }
  </style>
</head>
<body>
<section id="home" class="screen">
  <div class="logo" style="font-size:56px">AI<span>Guessr</span></div>
  <div class="card setup">
    <h2>API key setup</h2>

    <?php if ($working): ?>
      <div class="note good">✅ A key ending in <b>…<?= $h($info['hint'] ?? '') ?></b> is saved and encrypted (<?= $h($info['saved'] ?? '') ?>).</div>
      <div class="note info">
        Encryption secret is stored
        <?= $secretWhere === 'environment variable' ? 'in an environment variable' : ($outside ? 'outside the website folder ✓' : 'inside the <code>data</code> folder (blocked from the web, but less safe: your host doesn\'t let the game write outside its folder)') ?>.
      </div>
    <?php elseif ($info): ?>
      <div class="note bad">A key is saved but can't be decrypted (the secret file is missing). Enter the key again.</div>
    <?php else: ?>
      <div class="note info">No key yet. The game can't draw until you add one.</div>
    <?php endif; ?>

    <?php if ($msg): ?>
      <div class="note <?= $ok ? 'good' : 'bad' ?>"><?= $h($msg) ?></div>
    <?php endif; ?>

    <?php if ($locked): ?>
      <div class="note bad">Setup is locked. Open <code>config.php</code>, change <code>admin_password</code> from <code>change-me</code> to your own password, upload it again, then reload this page.</div>
    <?php else: ?>
      <form method="post" autocomplete="off" style="display:flex;flex-direction:column;gap:14px">
        <div>
          <label class="lbl" for="api_key"><?= $working ? 'Replace key' : 'Anthropic API key' ?></label>
          <input class="input" id="api_key" name="api_key" type="password" placeholder="sk-ant-..." required>
          <div class="hint">Get one at console.anthropic.com → API keys. It's encrypted before it's saved and is never shown again.</div>
        </div>
        <div>
          <label class="lbl" for="password">Admin password (from config.php)</label>
          <input class="input" id="password" name="password" type="password" required>
        </div>
        <button class="btn big" type="submit">Save key</button>
      </form>
    <?php endif; ?>
    <a href="./" class="btn secondary" style="text-align:center;text-decoration:none">← Back to the game</a>
  </div>
</section>
</body>
</html>
