<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('games');
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    if ($action === 'reset_game') {
        $gameId = trim((string)($_POST['game_id'] ?? ''));
        if (isset(ugfx_games_catalog()[$gameId])) {
            ugfx_game_reset($gameId);
            ugfx_admin_log('game_reset', ['game' => $gameId]);
            $message = 'Game leaderboard reset.';
        }
    } elseif ($action === 'reset_all') {
        ugfx_game_reset(null);
        ugfx_admin_log('game_reset_all');
        $message = 'All game leaderboards reset.';
    } elseif ($action === 'save_settings') {
        $gameId = trim((string)($_POST['game_id'] ?? ''));
        if (isset(ugfx_games_catalog()[$gameId])) {
            ugfx_game_update_settings($gameId, [
                'online' => !empty($_POST['online']),
                'featured' => !empty($_POST['featured']),
                'leaderboard_enabled' => !empty($_POST['leaderboard_enabled']),
                'maintenance_note' => (string)($_POST['maintenance_note'] ?? ''),
            ]);
            ugfx_admin_log('game_settings', ['game' => $gameId]);
            $message = 'Game settings updated.';
        }
    } elseif ($action === 'online_all') {
        ugfx_game_bulk_online(true);
        ugfx_admin_log('game_online_all');
        $message = 'All games taken online.';
    } elseif ($action === 'offline_all') {
        ugfx_game_bulk_online(false);
        ugfx_admin_log('game_offline_all');
        $message = 'All games taken offline.';
    } elseif ($action === 'engine_online' || $action === 'engine_offline') {
        $engine = trim((string)($_POST['engine'] ?? ''));
        if (in_array($engine, ['reaction','memory','pattern','runner','quiz','burst','card','dice','mahjong'], true)) {
            ugfx_game_bulk_engine($engine, $action === 'engine_online');
            ugfx_admin_log('game_engine_toggle', ['engine' => $engine, 'online' => $action === 'engine_online']);
            $message = ucfirst($engine) . ' games updated.';
        }
    } elseif ($action === 'delete_score') {
        $gameId = trim((string)($_POST['game_id'] ?? ''));
        $submittedAt = (string)($_POST['submitted_at'] ?? '');
        $name = (string)($_POST['name'] ?? '');
        if (ugfx_game_delete_score($gameId, $submittedAt, $name)) {
            ugfx_admin_log('game_delete_score', ['game' => $gameId, 'name' => $name, 'submitted_at' => $submittedAt]);
            $message = 'Score entry removed.';
        }
    }
}
$games = ugfx_games_catalog();
$stats = ugfx_game_stats();
$meta = ugfx_game_meta();
$scores = ugfx_game_scores();
$onlineCount = count(array_filter($stats, fn($row) => !empty($row['online'])));
$featuredCount = count(array_filter($stats, fn($row) => !empty($row['featured'])));
$totalScores = array_sum(array_map(fn($row) => (int)($row['plays'] ?? 0), $stats));
$engineOrder = ['reaction','memory','pattern','runner','quiz','burst','card','dice','mahjong'];
$engineStats = [];
foreach ($engineOrder as $engine) {
    $engineRows = array_filter($games, fn($g) => ($g['type'] ?? '') === $engine);
    $engineStats[$engine] = [
        'total' => count($engineRows),
        'online' => count(array_filter($engineRows, fn($g) => !empty($stats[$g['id']]['online'] ?? false))),
    ];
}
$adminTitle = 'Games | UGFX Admin';
include __DIR__ . '/includes/admin_header.php';
?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="row g-4 mb-4">
  <div class="col-md-3"><div class="ugfx-card p-4 h-100"><div class="ugfx-micro-label">ARCADE</div><h3 class="mb-1"><?= count($games) ?></h3><div class="text-secondary">Total games installed</div></div></div>
  <div class="col-md-3"><div class="ugfx-card p-4 h-100"><div class="ugfx-micro-label">ONLINE</div><h3 class="mb-1"><?= $onlineCount ?></h3><div class="text-secondary">Games visible to visitors</div></div></div>
  <div class="col-md-3"><div class="ugfx-card p-4 h-100"><div class="ugfx-micro-label">FEATURED</div><h3 class="mb-1"><?= $featuredCount ?></h3><div class="text-secondary">Spotlight games in rotation</div></div></div>
  <div class="col-md-3"><div class="ugfx-card p-4 h-100"><div class="ugfx-micro-label">SCORES</div><h3 class="mb-1"><?= $totalScores ?></h3><div class="text-secondary">Saved runs across all games</div></div></div>
</div>

<div class="ugfx-card p-4 mb-4">
  <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap">
    <div>
      <div class="ugfx-micro-label">ARCADE CONTROL ROOM</div>
      <h3>Big arcade controls</h3>
      <p class="text-secondary mb-0">Take everything online or offline, reset all scores, then manage each individual game below. This page is now built for a full event-ready arcade, not just three test games.</p>
    </div>
    <div class="text-secondary small">Last reset: <?= htmlspecialchars((string)($meta['last_reset_at'] ?? 'Never')) ?><?= !empty($meta['last_reset_by']) ? ' · by ' . htmlspecialchars((string)$meta['last_reset_by']) : '' ?></div>
  </div>
  <div class="d-flex gap-2 flex-wrap mt-3">
    <form method="post"><input type="hidden" name="action" value="online_all"><button class="btn ugfx-btn-primary">Take all online</button></form>
    <form method="post"><input type="hidden" name="action" value="offline_all"><button class="btn ugfx-btn-outline">Take all offline</button></form>
    <form method="post" onsubmit="return confirm('Reset every saved score across every game?');"><input type="hidden" name="action" value="reset_all"><button class="btn btn-outline-danger">Reset all leaderboards</button></form>
    <a class="btn ugfx-btn-outline" href="../games.php" target="_blank">Open public arcade</a>
  </div>
  <div class="row g-3 mt-1">
    <?php foreach ($engineOrder as $engine): ?>
      <div class="col-lg-4 col-md-6">
        <div class="border rounded-4 p-3 h-100">
          <div class="d-flex justify-content-between align-items-center mb-2">
            <div>
              <div class="ugfx-micro-label"><?= htmlspecialchars(strtoupper($engine)) ?></div>
              <div class="fw-semibold"><?= (int)($engineStats[$engine]['online'] ?? 0) ?> / <?= (int)($engineStats[$engine]['total'] ?? 0) ?> online</div>
            </div>
            <div class="text-secondary small">Engine lane</div>
          </div>
          <div class="d-flex gap-2 flex-wrap">
            <form method="post"><input type="hidden" name="action" value="engine_online"><input type="hidden" name="engine" value="<?= htmlspecialchars($engine) ?>"><button class="btn btn-sm ugfx-btn-primary">All online</button></form>
            <form method="post"><input type="hidden" name="action" value="engine_offline"><input type="hidden" name="engine" value="<?= htmlspecialchars($engine) ?>"><button class="btn btn-sm ugfx-btn-outline">All offline</button></form>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>

<div class="ugfx-card p-4 mb-4">
  <div class="row g-3 align-items-center mb-3"><div class="col-md-6"><input class="form-control" id="gameAdminFilter" type="search" placeholder="Filter 200+ games by title, type, or difficulty"></div><div class="col-md-6 text-secondary small">Use the filter to jump around the larger premium arcade catalog faster.</div></div>
  <div class="table-responsive">
    <table class="table ugfx-table align-middle">
      <thead><tr data-game-row="<?= htmlspecialchars(strtolower($game['name'] . " " . $game['type'] . " " . $game['difficulty'])) ?>"><th>Game</th><th>Type</th><th>Status</th><th>Top</th><th>Scores</th><th>Flags</th></tr></thead>
      <tbody>
      <?php foreach ($games as $id => $game): $stat = $stats[$id] ?? []; ?>
        <tr data-game-row="<?= htmlspecialchars(strtolower($game['name'] . " " . $game['type'] . " " . $game['difficulty'])) ?>">
          <td><div class="fw-semibold"><?= htmlspecialchars($game['name']) ?></div><div class="text-secondary small"><?= htmlspecialchars($game['tagline']) ?></div></td>
          <td><?= htmlspecialchars(ucfirst($game['type'])) ?></td>
          <td><?= !empty($stat['online']) ? '<span class="badge text-bg-success">Online</span>' : '<span class="badge text-bg-secondary">Offline</span>' ?></td>
          <td><?= (int)($stat['top_score'] ?? 0) ?> <?= htmlspecialchars($game['unit']) ?><div class="text-secondary small"><?= htmlspecialchars((string)($stat['top_name'] ?? '—')) ?></div></td>
          <td><?= (int)($stat['plays'] ?? 0) ?></td>
          <td>
            <?= !empty($stat['featured']) ? '<span class="badge text-bg-warning me-1">Featured</span>' : '' ?>
            <?= !empty($stat['leaderboard_enabled']) ? '<span class="badge text-bg-info">Leaderboard</span>' : '<span class="badge text-bg-dark">Board off</span>' ?>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="row g-4">
<?php foreach ($games as $id => $game): $stat = $stats[$id] ?? []; $settings = ugfx_game_settings($id); $rows = $scores[$id] ?? []; ?>
  <div class="col-xxl-6" data-game-card="<?= htmlspecialchars(strtolower($game['name'] . " " . $game['type'] . " " . $game['difficulty'])) ?>">
    <div class="ugfx-card p-4 h-100">
      <div class="d-flex justify-content-between align-items-start gap-3 flex-wrap mb-3">
        <div>
          <div class="ugfx-micro-label"><?= htmlspecialchars(strtoupper($game['difficulty'])) ?> · <?= htmlspecialchars(strtoupper($game['type'])) ?></div>
          <h3 class="mb-1"><?= htmlspecialchars($game['name']) ?></h3>
          <div class="text-secondary small"><?= htmlspecialchars($game['description']) ?></div>
        </div>
        <div class="text-end">
          <div class="fw-semibold"><?= (int)($stat['top_score'] ?? 0) ?> <?= htmlspecialchars($game['unit']) ?></div>
          <div class="text-secondary small">Top by <?= htmlspecialchars((string)($stat['top_name'] ?? '—')) ?></div>
        </div>
      </div>

      <form method="post" class="row g-3 align-items-start mb-4">
        <input type="hidden" name="action" value="save_settings">
        <input type="hidden" name="game_id" value="<?= htmlspecialchars($id) ?>">
        <div class="col-sm-4">
          <div class="form-check form-switch mb-2"><input class="form-check-input" type="checkbox" id="online-<?= htmlspecialchars($id) ?>" name="online" <?= !empty($settings['online']) ? 'checked' : '' ?>><label class="form-check-label" for="online-<?= htmlspecialchars($id) ?>">Online</label></div>
          <div class="form-check form-switch mb-2"><input class="form-check-input" type="checkbox" id="featured-<?= htmlspecialchars($id) ?>" name="featured" <?= !empty($settings['featured']) ? 'checked' : '' ?>><label class="form-check-label" for="featured-<?= htmlspecialchars($id) ?>">Featured</label></div>
          <div class="form-check form-switch"><input class="form-check-input" type="checkbox" id="board-<?= htmlspecialchars($id) ?>" name="leaderboard_enabled" <?= !empty($settings['leaderboard_enabled']) ? 'checked' : '' ?>><label class="form-check-label" for="board-<?= htmlspecialchars($id) ?>">Leaderboard on</label></div>
        </div>
        <div class="col-sm-8">
          <label class="form-label">Offline / maintenance note</label>
          <input class="form-control" type="text" name="maintenance_note" maxlength="160" value="<?= htmlspecialchars((string)($settings['maintenance_note'] ?? '')) ?>" placeholder="Shown if someone tries to play while the game is offline">
        </div>
        <div class="col-12 d-flex gap-2 flex-wrap">
          <button class="btn ugfx-btn-primary">Save settings</button>
        </div>
      </form>

      <form method="post" class="mb-4" onsubmit="return confirm('Reset <?= htmlspecialchars(addslashes($game['name'])) ?> scores?');">
        <input type="hidden" name="action" value="reset_game">
        <input type="hidden" name="game_id" value="<?= htmlspecialchars($id) ?>">
        <button class="btn btn-outline-danger">Reset leaderboard</button>
      </form>

      <div class="table-responsive">
        <table class="table ugfx-table align-middle mb-0">
          <thead><tr data-game-row="<?= htmlspecialchars(strtolower($game['name'] . " " . $game['type'] . " " . $game['difficulty'])) ?>"><th>#</th><th>Player</th><th>Score</th><th></th></tr></thead>
          <tbody>
          <?php if ($rows): foreach (array_slice($rows, 0, 8) as $index => $row): ?>
            <tr data-game-row="<?= htmlspecialchars(strtolower($game['name'] . " " . $game['type'] . " " . $game['difficulty'])) ?>">
              <td><?= $index + 1 ?></td>
              <td><div class="fw-semibold"><?= htmlspecialchars((string)($row['name'] ?? 'Guest')) ?></div><div class="text-secondary small"><?= htmlspecialchars((string)($row['submitted_at'] ?? '')) ?></div></td>
              <td><?= (int)($row['score'] ?? 0) ?></td>
              <td>
                <form method="post" onsubmit="return confirm('Delete this score entry?');">
                  <input type="hidden" name="action" value="delete_score">
                  <input type="hidden" name="game_id" value="<?= htmlspecialchars($id) ?>">
                  <input type="hidden" name="submitted_at" value="<?= htmlspecialchars((string)($row['submitted_at'] ?? '')) ?>">
                  <input type="hidden" name="name" value="<?= htmlspecialchars((string)($row['name'] ?? '')) ?>">
                  <button class="btn btn-sm btn-outline-danger">Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr data-game-row="<?= htmlspecialchars(strtolower($game['name'] . " " . $game['type'] . " " . $game['difficulty'])) ?>"><td colspan="4" class="text-secondary">No saved scores yet for this game.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
<?php endforeach; ?>
</div>
<script>
(() => {
  const filter = document.getElementById('gameAdminFilter');
  if (!filter) return;
  const rows = Array.from(document.querySelectorAll('[data-game-row]'));
  const cards = Array.from(document.querySelectorAll('[data-game-card]'));
  filter.addEventListener('input', () => {
    const q = filter.value.trim().toLowerCase();
    rows.forEach(row => row.style.display = !q || row.dataset.gameRow.includes(q) ? '' : 'none');
    cards.forEach(card => card.style.display = !q || card.dataset.gameCard.includes(q) ? '' : 'none');
  });
})();
</script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
