<?php
declare(strict_types=1);
require __DIR__ . '/db.php';

$perPage = 24;
$slug = isset($_GET['p']) ? (string)$_GET['p'] : null;
$q = trim(mb_substr((string)($_GET['q'] ?? ''), 0, 50));
$page = max(1, (int)($_GET['hal'] ?? 1));
$noindex = false;
$canonical = null;
$ogImage = null;
$post = null;

if ($slug !== null) {
    $st = db()->prepare('SELECT * FROM posts WHERE slug = ?');
    $st->execute([$slug]);
    $post = $st->fetch() ?: null;
    if ($post) {
        $title = post_title($post);
        $desc = 'Bukti pembayaran ' . $title . ' kepada member ' . $post['user_id'] . ' pada ' . tanggal($post['won_at']) . '.';
        $canonical = $cfg['base_url'] . post_url($post);
        $ogImage = $cfg['base_url'] . '/' . $post['image'];
        $st = db()->prepare('SELECT * FROM posts WHERE id <> ? ORDER BY won_at DESC, id DESC LIMIT 4');
        $st->execute([$post['id']]);
        $others = $st->fetchAll();
    } else {
        http_response_code(404);
        $noindex = true;
        $title = 'Bukti tidak ditemukan - ' . $cfg['brand'];
        $desc = $cfg['description'];
        $others = db()->query('SELECT * FROM posts ORDER BY won_at DESC, id DESC LIMIT 4')->fetchAll();
    }
} else {
    $noindex = $q !== ''; // search result pages stay out of Google
    [$where, $args] = search_filter($q);
    $total = count_posts($q);
    $pages = max(1, (int)ceil($total / $perPage));
    $page = min($page, $pages);
    $st = db()->prepare("SELECT * FROM posts $where ORDER BY won_at DESC, id DESC LIMIT $perPage OFFSET " . (($page - 1) * $perPage));
    $st->execute($args);
    $posts = $st->fetchAll();
    $hero = $q === '' && $page === 1;
    if ($hero) {
        $s = stats();
        $menu = db()->query('SELECT label, keyword FROM menu_items ORDER BY sort, id')->fetchAll();
        if (!$menu) { // nothing set in admin yet: show the most posted games
            $menu = db()->query('SELECT game AS label, game AS keyword FROM posts GROUP BY game ORDER BY COUNT(*) DESC LIMIT 8')->fetchAll();
        }
    }

    $title = $q !== '' ? 'Cari "' . $q . '" - ' . $cfg['brand'] : $cfg['title'] . ($page > 1 ? " - Halaman $page" : '');
    $desc = $cfg['description'];
    if ($q === '') {
        $canonical = $cfg['base_url'] . '/' . ($page > 1 ? "?hal=$page" : '');
    }
}

function page_url(int $n, string $q): string
{
    $params = array_filter(['q' => $q, 'hal' => $n > 1 ? $n : null], fn($v) => $v !== null && $v !== '');
    return '/' . ($params ? '?' . http_build_query($params) : '');
}

// 1 … 4 5 [6] 7 8 … 20
function page_numbers(int $page, int $pages): array
{
    $keep = array_unique(array_filter([1, $page - 2, $page - 1, $page, $page + 1, $page + 2, $pages], fn($n) => $n >= 1 && $n <= $pages));
    sort($keep);
    $out = [];
    foreach ($keep as $i => $n) {
        if ($i > 0 && $n - $keep[$i - 1] > 1) $out[] = null;
        $out[] = $n;
    }
    return $out;
}

function card(array $p, bool $eager): string
{
    $t = e(post_title($p));
    return '<a class="card" href="' . e(post_url($p)) . '">'
        . '<span class="card-media"><img src="/' . e($p['image']) . '" width="' . (int)$p['img_w'] . '" height="' . (int)$p['img_h'] . '" alt="' . $t . '" loading="' . ($eager ? 'eager' : 'lazy') . '">'
        . '<span class="amount">' . e(rupiah((int)$p['amount'])) . '</span></span>'
        . '<span class="card-body"><span class="card-title">Jackpot ' . e($p['game']) . ' <span class="paid">' . icon('badge', 14) . 'Lunas</span></span>'
        . '<span class="meta"><span>' . icon('calendar', 14) . '<time datetime="' . e($p['won_at']) . '">' . e(tanggal($p['won_at'])) . '</time></span>'
        . '<span>' . icon('user', 14) . e($p['user_id']) . '</span></span></span></a>';
}

?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($title) ?></title>
<meta name="description" content="<?= e($desc) ?>">
<?php if ($noindex): ?><meta name="robots" content="noindex,follow">
<?php endif ?>
<?php if ($canonical): ?><link rel="canonical" href="<?= e($canonical) ?>">
<meta property="og:url" content="<?= e($canonical) ?>">
<?php endif ?>
<meta property="og:title" content="<?= e($title) ?>">
<meta property="og:description" content="<?= e($desc) ?>">
<?php if ($ogImage): ?><meta property="og:image" content="<?= e($ogImage) ?>">
<?php endif ?>
<meta name="theme-color" content="<?= e($cfg['colors']['bg']) ?>">
<?php if ($cfg['favicon_url'] !== ''): ?><link rel="icon" href="<?= e($cfg['favicon_url']) ?>">
<?php endif ?>
<?= fonts() ?>
<link rel="stylesheet" href="/style.css">
<?= theme_style() ?>
<?php if (!$noindex): // structured data for Google; JSON_HEX_TAG keeps "</script>" in any text from closing the tag
    $site = ['@type' => 'WebSite', 'name' => $cfg['brand'], 'url' => $cfg['base_url'] . '/'];
    $graph = [$site];
    if ($post) {
        $graph[] = ['@type' => 'ImageObject', 'name' => $title, 'description' => $desc, 'contentUrl' => $ogImage, 'url' => $canonical,
            'uploadDate' => $post['won_at'], 'width' => (int)$post['img_w'], 'height' => (int)$post['img_h']];
        $graph[] = ['@type' => 'BreadcrumbList', 'itemListElement' => [
            ['@type' => 'ListItem', 'position' => 1, 'name' => 'Beranda', 'item' => $cfg['base_url'] . '/'],
            ['@type' => 'ListItem', 'position' => 2, 'name' => $title, 'item' => $canonical],
        ]];
    } ?>
<script type="application/ld+json"><?= json_encode(['@context' => 'https://schema.org', '@graph' => $graph], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) ?></script>
<?php endif ?>
</head>
<body>
<a class="skip" href="#main">Lewati ke konten</a>
<header class="top">
  <div class="wrap top-inner">
    <a class="logo" href="/" aria-label="<?= e($cfg['brand']) ?> - beranda"><?= logo(40) ?></a>
    <form class="search" action="/" method="get" role="search">
      <label class="sr-only" for="q">Cari bukti</label>
      <?= icon('search', 18) ?>
      <input id="q" name="q" type="search" placeholder="Cari permainan atau nominal" value="<?= e($q) ?>" maxlength="50">
    </form>
    <?php if ($cfg['cta_url'] !== ''): ?><a class="btn btn-sm top-cta" href="<?= e($cfg['cta_url']) ?>" rel="nofollow"><?= e($cfg['cta_text']) ?></a><?php endif ?>
  </div>
</header>

<main id="main">
<?php if ($slug !== null): ?>
  <div class="wrap">
    <nav class="crumbs" aria-label="Breadcrumb"><a href="/"><?= icon('home', 14) ?> Beranda</a><?= icon('right', 14) ?><span aria-current="page"><?= $post ? 'Detail bukti' : 'Tidak ditemukan' ?></span></nav>
  <?php if ($post): ?>
    <article class="detail">
      <a class="detail-media" href="/<?= e($post['image']) ?>" target="_blank" rel="noopener" data-lightbox aria-label="Perbesar gambar bukti">
        <img src="/<?= e($post['image']) ?>" width="<?= (int)$post['img_w'] ?>" height="<?= (int)$post['img_h'] ?>" alt="<?= e($title) ?>">
      </a>
      <div class="detail-info">
        <span class="verified"><?= icon('badge', 16) ?> Dibayar lunas</span>
        <h1><?= e($title) ?></h1>
        <p class="big-amount"><?= e(rupiah((int)$post['amount'])) ?></p>
        <dl class="facts">
          <div><dt>Permainan</dt><dd><?= e($post['game']) ?></dd></div>
          <div><dt>User ID</dt><dd><?= e($post['user_id']) ?></dd></div>
          <div><dt>Tanggal</dt><dd><time datetime="<?= e($post['won_at']) ?>"><?= e(tanggal($post['won_at'])) ?></time></dd></div>
        </dl>
        <?php if ($post['note'] !== ''): ?><p class="note"><?= nl2br(e($post['note'])) ?></p><?php endif ?>
        <?php if ($cfg['cta_url'] !== ''): ?><a class="btn btn-block" href="<?= e($cfg['cta_url']) ?>" rel="nofollow"><?= e($cfg['cta_text']) ?> <?= icon('right', 18) ?></a><?php endif ?>
        <div class="share">
          <span class="muted">Bagikan</span>
          <a class="share-btn share-wa" href="https://wa.me/?text=<?= rawurlencode($title . ' ' . $canonical) ?>" target="_blank" rel="noopener nofollow" aria-label="Bagikan ke WhatsApp"><?= icon('chat') ?></a>
          <a class="share-btn share-tg" href="https://t.me/share/url?url=<?= rawurlencode($canonical) ?>&amp;text=<?= rawurlencode($title) ?>" target="_blank" rel="noopener nofollow" aria-label="Bagikan ke Telegram"><?= icon('send') ?></a>
          <button type="button" class="share-btn" data-copy="<?= e($canonical) ?>" aria-label="Salin link"><?= icon('copy') ?></button>
          <span class="copied muted" role="status"></span>
        </div>
      </div>
    </article>
    <dialog id="lightbox" class="lightbox" aria-label="Gambar bukti">
      <form method="dialog"><button class="lightbox-close" aria-label="Tutup"><?= icon('x', 22) ?></button></form>
      <img src="/<?= e($post['image']) ?>" width="<?= (int)$post['img_w'] ?>" height="<?= (int)$post['img_h'] ?>" alt="<?= e($title) ?>" loading="lazy">
    </dialog>
  <?php else: ?>
    <div class="empty">
      <?= icon('alert', 40) ?>
      <h1>Bukti tidak ditemukan</h1>
      <p class="muted">Halaman ini sudah dihapus atau alamatnya salah.</p>
      <a class="btn" href="/">Lihat semua bukti</a>
    </div>
  <?php endif ?>
  <?php if ($others): ?>
    <h2 class="section-title">Bukti lainnya</h2>
    <div class="grid"><?php foreach ($others as $o) echo card($o, false) ?></div>
  <?php endif ?>
  </div>
<?php else: ?>
  <?php if ($hero): ?>
  <section class="hero">
    <div class="wrap">
      <span class="eyebrow"><?= icon('shield', 16) ?> Semua kemenangan dibayar lunas</span>
      <h1><?= e($cfg['heading']) ?></h1>
      <p class="lead"><?= e($cfg['description']) ?></p>
      <div class="stats">
        <div class="stat"><span class="stat-icon"><?= icon('image', 20) ?></span><span><strong><?= number_format((int)$s['n'], 0, ',', '.') ?></strong><small>Total bukti</small></span></div>
        <div class="stat"><span class="stat-icon"><?= icon('money', 20) ?></span><span><strong><?= e(rupiah_short((int)$s['total'])) ?></strong><small>Total dibayar</small></span></div>
        <div class="stat"><span class="stat-icon"><?= icon('calendar', 20) ?></span><span><strong><?= e(rupiah_short((int)$s['month'])) ?></strong><small>Bulan ini</small></span></div>
        <div class="stat"><span class="stat-icon"><?= icon('clock', 20) ?></span><span><strong><?= $s['last'] ? e(date('d/m/Y', strtotime($s['last']))) : '-' ?></strong><small>Bukti terbaru</small></span></div>
      </div>
      <?php if ($menu): ?>
      <nav class="chips" aria-label="Filter permainan">
        <?php foreach ($menu as $m): ?><a class="chip" href="<?= e(page_url(1, $m['keyword'])) ?>"><?= e($m['label']) ?> <span><?= count_posts($m['keyword']) ?></span></a><?php endforeach ?>
      </nav>
      <?php endif ?>
    </div>
  </section>
  <?php endif ?>
  <div class="wrap">
    <div class="list-head">
      <h2 class="section-title"><?= $q !== '' ? 'Hasil pencarian "' . e($q) . '"' : ($hero ? 'Bukti terbaru' : e($cfg['heading'])) ?></h2>
      <span class="muted"><?= number_format($total, 0, ',', '.') ?> bukti<?= $pages > 1 ? " · halaman $page dari $pages" : '' ?></span>
    </div>
    <?php if ($q !== ''): ?><p><a href="/"><?= icon('left', 14) ?> Kembali ke semua bukti</a></p><?php endif ?>
    <?php if (!$posts): ?>
    <div class="empty"><?= icon('search', 40) ?><p class="muted"><?= $q !== '' ? 'Tidak ada bukti yang cocok. Coba kata lain.' : 'Belum ada bukti.' ?></p></div>
    <?php endif ?>
    <div class="grid"><?php foreach ($posts as $i => $p) echo card($p, $i < 4) ?></div>
    <?php if ($pages > 1): ?>
    <nav class="pager" aria-label="Halaman">
      <?php if ($page > 1): ?><a href="<?= e(page_url($page - 1, $q)) ?>" rel="prev" aria-label="Halaman sebelumnya"><?= icon('left') ?></a><?php endif ?>
      <?php foreach (page_numbers($page, $pages) as $n): ?>
        <?php if ($n === null): ?><span class="gap">…</span>
        <?php elseif ($n === $page): ?><span class="current" aria-current="page"><?= $n ?></span>
        <?php else: ?><a href="<?= e(page_url($n, $q)) ?>"><?= $n ?></a><?php endif ?>
      <?php endforeach ?>
      <?php if ($page < $pages): ?><a href="<?= e(page_url($page + 1, $q)) ?>" rel="next" aria-label="Halaman berikutnya"><?= icon('right') ?></a><?php endif ?>
    </nav>
    <?php endif ?>
    <?php $article = format_article($cfg['article'] ?? ''); ?>
    <?php if ($hero && $article !== ''): ?>
    <section class="article"><?= $article ?></section>
    <?php endif ?>
  </div>
<?php endif ?>
</main>

<footer class="foot">
  <div class="wrap foot-inner">
    <a class="logo" href="/"><?= logo(30) ?></a>
    <p class="muted"><?= e($cfg['description']) ?></p>
    <p class="copy">&copy; <?= date('Y') ?> <?= e($cfg['brand']) ?>. All rights reserved.</p>
  </div>
</footer>
<?php $contacts = array_filter([
    ['url' => $cfg['contact_wa'] ?? '', 'label' => 'WhatsApp', 'icon' => 'chat', 'cls' => 'fc-wa'],
    ['url' => $cfg['contact_tg'] ?? '', 'label' => 'Telegram', 'icon' => 'send', 'cls' => 'fc-tg'],
    ['url' => $cfg['contact_chat'] ?? '', 'label' => 'Livechat', 'icon' => 'headset', 'cls' => 'fc-chat'],
], fn($c) => $c['url'] !== ''); ?>
<?php if ($contacts): ?>
<nav class="float-contact" aria-label="Hubungi kami">
  <?php foreach ($contacts as $c): ?><a class="fc <?= $c['cls'] ?>" href="<?= e($c['url']) ?>" target="_blank" rel="noopener nofollow" aria-label="<?= $c['label'] ?>"><?= icon($c['icon'], 24) ?><span class="fc-label"><?= $c['label'] ?></span></a><?php endforeach ?>
</nav>
<?php endif ?>
<?php if ($post): ?>
<script>
(function () {
  // Lightbox: open the proof image in a <dialog>; without JS the link opens the image itself.
  var box = document.getElementById('lightbox');
  document.querySelector('[data-lightbox]').addEventListener('click', function (ev) {
    if (!box.showModal) return;
    ev.preventDefault();
    box.showModal();
  });
  box.addEventListener('click', function (ev) { if (ev.target === box) box.close(); });

  // Copy link.
  var btn = document.querySelector('[data-copy]'), msg = document.querySelector('.copied');
  btn.addEventListener('click', function () {
    navigator.clipboard.writeText(btn.dataset.copy).then(function () {
      msg.textContent = 'Link tersalin';
      setTimeout(function () { msg.textContent = ''; }, 2000);
    }, function () { msg.textContent = btn.dataset.copy; });
  });
})();
</script>
<?php endif ?>
</body>
</html>
