<?php
require_once __DIR__ . '/includes/functions.php';

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$category = isset($_GET['category']) ? trim($_GET['category']) : '';
$page = get_page_num();
$total = count_games($q, $category);
$total_pages = max(1, (int)ceil($total / GAMES_PER_PAGE));
$page = min($page, $total_pages);
$offset = ($page - 1) * GAMES_PER_PAGE;
$games = search_games($q, GAMES_PER_PAGE, $offset, $category);
$categories = get_categories();

$page_title = ($q ? e($q) . ' - Play Online | ' : 'All Online Games - Play & Install | ') . SITE_NAME;
$page_description = 'Search and discover ' . count_games() . '+ online, mobile and multiplayer games. Find any game and get instant play or install links.';
$page_url = SITE_URL . '/games.php' . ($q ? '?q=' . urlencode($q) : '');

require __DIR__ . '/includes/header.php';
?>
<section class="container section">
  <h1 style="font-size:1.8rem;margin:0 0 6px">Search Any Online Game</h1>
  <p style="color:var(--text-dim);margin:0 0 24px">Type a game name below — <?= count_games() ?> games and counting.</p>

  <div class="games-toolbar">
    <form action="<?= SITE_URL ?>/games.php" method="get">
      <input type="text" name="q" placeholder="e.g. Free Fire, PUBG, Ludo King, Chess..." value="<?= e($q) ?>">
      <?php if ($category): ?><input type="hidden" name="category" value="<?= e($category) ?>"><?php endif; ?>
      <button class="btn btn-primary" type="submit">Search</button>
    </form>
    <select onchange="location.href=this.value">
      <option value="<?= SITE_URL ?>/games.php<?= $q ? '?q=' . urlencode($q) : '' ?>">All Categories</option>
      <?php foreach ($categories as $c):
        $params = $q ? ['q' => $q, 'category' => $c] : ['category' => $c]; ?>
      <option value="<?= SITE_URL ?>/games.php?<?= e(http_build_query($params)) ?>" <?= $category === $c ? 'selected' : '' ?>><?= e($c) ?></option>
      <?php endforeach; ?>
    </select>
  </div>

  <?php if ($games): ?>
  <div class="games-grid">
    <?php foreach ($games as $g): ?>
    <a class="game-card" href="<?= SITE_URL ?>/game-detail.php?slug=<?= e($g['slug']) ?>">
      <div class="game-thumb"><?= e(mb_substr($g['name'], 0, 2)) ?></div>
      <span class="cat"><?= e($g['category']) ?></span>
      <h3><?= e($g['name']) ?></h3>
      <p><?= e($g['description']) ?></p>
    </a>
    <?php endforeach; ?>
  </div>
  <?= paginate_links($page, $total_pages, SITE_URL . '/games.php', array_filter(['q' => $q, 'category' => $category])) ?>
  <?php else: ?>
  <div class="empty-state">
    <p>No games matched "<?= e($q) ?>". Try another name, or <a href="<?= SITE_URL ?>/games.php" style="color:var(--cyan)">browse all games</a>.</p>
  </div>
  <?php endif; ?>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
