<?php

declare(strict_types=1);

/**
 * STAR MERCHANT console panel (SPEC §15.6). Included by the Doors page
 * with $doorAdmin (DoorAdminContext) and $csrfField; the wrapper already
 * authenticated the sysop and checks CSRF on every POST.
 */

require_once __DIR__ . '/universe.php';

use Doors\StarMerchant\Universe;

$u = new Universe($doorAdmin->kv());
$u->ensureTables();

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    switch ((string)($_POST['sm'] ?? '')) {
        case 'settings':
            $u->setCfg('sectors', max(100, min(5000, (int)($_POST['sectors'] ?? 1000))));
            $u->setCfg('turns', max(25, min(2000, (int)($_POST['turns'] ?? 250))));
            $u->setCfg('combat', isset($_POST['combat']) ? 1 : 0);
            $doorAdmin->log('Star Merchant settings changed');
            echo '<div class="flash ok">Saved. Sector count applies at the next universe reset.</div>';
            break;
        case 'reset':
            if ((string)($_POST['confirm'] ?? '') === 'RESET') {
                $t0 = microtime(true);
                $u->generate();
                $doorAdmin->log(sprintf('Star Merchant universe reset (%.2fs)', microtime(true) - $t0));
                echo '<div class="flash ok">A fresh galaxy condensed in ' . sprintf('%.2f', microtime(true) - $t0) . 's. Every ship and planet is gone.</div>';
            } else {
                echo '<div class="flash bad">Type RESET in the box to confirm; this erases every player.</div>';
            }
            break;
    }
}

$players = $u->players()->rows([], 'id ASC');
$ladder = [];
foreach ($players as $p) {
    $ladder[] = ['handle' => (string)$p['handle'], 'worth' => $u->netWorth($p),
        'kills' => (int)$p['kills'], 'deaths' => (int)$p['deaths'], 'turns' => (int)$p['turns']];
}
usort($ladder, fn(array $a, array $b) => $b['worth'] <=> $a['worth']);
?>

<div class="cols">
<div>
  <div class="card">
    <h2>Settings</h2>
    <form method="post">
      <?= $csrfField ?>
      <input type="hidden" name="sm" value="settings">
      <label>Sectors (at next reset) <input type="number" name="sectors" min="100" max="5000"
        value="<?= $u->cfg('sectors', 1000) ?>"></label>
      <label>Turns per day <input type="number" name="turns" min="25" max="2000"
        value="<?= $u->cfg('turns', 250) ?>"></label>
      <label class="radio"><input type="checkbox" name="combat" <?= $u->cfg('combat', 1) === 1 ? 'checked' : '' ?>>
        combat allowed outside Charter Space</label>
      <button class="btn small">Save</button>
    </form>
  </div>
  <div class="card">
    <h2>Reset universe</h2>
    <p class="hint">Regenerates every sector, port, and warp, and it erases every
    player, planet, and beacon. The galaxy currently spans
    <strong><?= h((string)($doorAdmin->kv()->get('gen_sectors') ?? 'no')) ?></strong> sectors.</p>
    <form method="post" onsubmit="return confirm('Really erase the whole galaxy and every player in it?');">
      <?= $csrfField ?>
      <input type="hidden" name="sm" value="reset">
      <input type="text" name="confirm" placeholder="type RESET" size="10">
      <button class="btn small danger">Reset universe</button>
    </form>
  </div>
</div>
<div>
  <div class="card">
    <h2>Top merchants</h2>
    <table class="list">
      <tr><th>#</th><th>Handle</th><th>Net worth</th><th>Kills</th><th>Pods</th><th>Turns left</th></tr>
      <?php if ($ladder === []): ?><tr><td colspan="6" class="hint">Nobody has flown yet.</td></tr><?php endif; ?>
      <?php foreach (array_slice($ladder, 0, 15) as $i => $r): ?>
      <tr>
        <td><?= $i + 1 ?></td>
        <td><?= h($r['handle']) ?></td>
        <td><?= number_format($r['worth']) ?></td>
        <td><?= $r['kills'] ?></td>
        <td><?= $r['deaths'] ?></td>
        <td><?= $r['turns'] ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
  <div class="card">
    <h2>Recent game log</h2>
    <table class="list">
      <?php foreach ($u->slog()->rows([], 'id DESC', 12) as $e): ?>
      <tr>
        <td class="hint nowrap"><?= h(admin_stamp((string)$e['at'], 'm-d H:i')) ?></td>
        <td><?= h((string)$e['body']) ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>
</div>
