<?php
declare(strict_types=1);
require_once __DIR__ . '/lib/bootstrap.php';
migrate();

$pdo = db();
$reqPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$reqPath = '/' . trim($reqPath, '/');
if ($reqPath !== '/') {
    $reqPath .= '/';
}

$page = max(1, (int)($_GET['page'] ?? 1));
if (preg_match('#/page/(\d+)/?$#', $reqPath, $pm)) {
    $page = max(1, (int)$pm[1]);
}

$search = trim((string)($_GET['s'] ?? $_GET['q'] ?? ''));
$catSlug = '';
$tagSlug = '';
if (preg_match('#^/category/([^/]+)/#', $reqPath, $cm)) {
    $catSlug = $cm[1];
} elseif (preg_match('#^/tag/([^/]+)/#', $reqPath, $tm)) {
    $tagSlug = $tm[1];
}

$perPage = 24;
$offset = ($page - 1) * $perPage;

$where = ["v.status = 'published'"];
$joins = 'LEFT JOIN categories c ON c.id = v.category_id';
$params = [];
$heading = 'Vídeos Recentes';
$subHeading = 'Todos os vídeos em streaming no BucetaNet';
$basePath = '/';

if ($catSlug !== '') {
    $cs = $pdo->prepare('SELECT id, name, slug FROM categories WHERE slug = ? LIMIT 1');
    $cs->execute([$catSlug]);
    $catRow = $cs->fetch();
    if ($catRow) {
        $where[] = 'v.category_id = ?';
        $params[] = (int)$catRow['id'];
        $heading = 'Categoria: ' . (string)$catRow['name'];
        $subHeading = 'Vídeos publicados na categoria ' . (string)$catRow['name'];
        $basePath = '/category/' . rawurlencode((string)$catRow['slug']) . '/';
    } else {
        $heading = 'Categoria: ' . $catSlug;
        $where[] = '1 = 0';
    }
} elseif ($tagSlug !== '') {
    $ts = $pdo->prepare('SELECT id, name, slug FROM tags WHERE slug = ? LIMIT 1');
    $ts->execute([$tagSlug]);
    $tagRow = $ts->fetch();
    if ($tagRow) {
        $joins .= ' INNER JOIN video_tags vt ON vt.video_id = v.id';
        $where[] = 'vt.tag_id = ?';
        $params[] = (int)$tagRow['id'];
        $heading = 'Tag: ' . (string)$tagRow['name'];
        $subHeading = 'Vídeos marcados com ' . (string)$tagRow['name'];
        $basePath = '/tag/' . rawurlencode((string)$tagRow['slug']) . '/';
    } else {
        $heading = 'Tag: ' . $tagSlug;
        $where[] = '1 = 0';
    }
}

if ($search !== '') {
    $where[] = '(v.title LIKE ? OR v.description LIKE ? OR v.slug LIKE ?)';
    $like = '%' . $search . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $heading = 'Busca: "' . $search . '"';
    $subHeading = 'Resultados encontrados no catálogo';
}

$whereSql = implode(' AND ', $where);
$cntStmt = $pdo->prepare("SELECT COUNT(*) FROM videos v $joins WHERE $whereSql");
$cntStmt->execute($params);
$totalRows = (int)$cntStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

$listStmt = $pdo->prepare(
    "SELECT v.id, v.title, v.slug, v.thumbnail_url, v.video_url, v.views, c.name AS category_name, c.slug AS category_slug
     FROM videos v $joins
     WHERE $whereSql
     ORDER BY v.featured DESC, (CASE WHEN COALESCE(v.video_url,'') != '' THEN 0 ELSE 1 END), v.id DESC
     LIMIT $perPage OFFSET $offset"
);
$listStmt->execute($params);
$videos = $listStmt->fetchAll();

$topCats = $pdo->query(
    'SELECT c.name, c.slug, COUNT(v.id) AS total
     FROM categories c
     INNER JOIN videos v ON v.category_id = c.id AND v.status = "published"
     GROUP BY c.id
     ORDER BY total DESC, c.name ASC
     LIMIT 12'
)->fetchAll();

$h = static fn(string $s): string => htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$pageUrl = static function (int $p) use ($basePath, $search): string {
    $u = $p <= 1 ? $basePath : $basePath . 'page/' . $p . '/';
    if ($search !== '') {
        $u .= '?s=' . rawurlencode($search);
    }
    return $u;
};
?><!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $h($heading) ?> — BucetaNet</title>
<style>
  *,*::before,*::after{box-sizing:border-box}
  body{margin:0;background:#141414;color:#e5e5e5;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;line-height:1.5}
  a{color:#e53935;text-decoration:none}
  a:hover{color:#ff5252}
  .site-header{background:#1b1b1b;border-bottom:1px solid #262626}
  .site-branding{max-width:1320px;margin:0 auto;padding:18px 24px;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:16px}
  .brand-name{display:block;color:#e53935;font-size:30px;font-weight:800;line-height:1;letter-spacing:.015em}
  .site-description{margin:6px 0 0;color:#999;font-size:12px}
  .header-search{display:flex;gap:8px;flex:1;max-width:420px;min-width:240px}
  .header-search input{flex:1;background:#101010;border:1px solid #333;color:#fff;padding:10px 14px;border-radius:5px;font-size:14px}
  .header-search input:focus{outline:none;border-color:#e53935}
  .header-search button{background:#e53935;color:#fff;border:0;padding:10px 16px;border-radius:5px;font-weight:700;cursor:pointer}
  .header-search button:hover{background:#c62828}
  .main-navigation{background:#121212;border-top:1px solid #292929;border-bottom:1px solid #080808}
  .nav-inner{max-width:1320px;margin:0 auto;padding:0 24px;display:flex;gap:4px;overflow-x:auto}
  .nav-inner a{color:#ddd;padding:12px 15px;font-size:13px;font-weight:600;white-space:nowrap;border-bottom:2px solid transparent}
  .nav-inner a:hover,.nav-inner a.active{color:#fff;border-bottom-color:#e53935;background:#191919}
  .page-wrap{max-width:1320px;margin:0 auto;padding:22px 24px 48px}
  .section-head{display:flex;flex-wrap:wrap;align-items:flex-end;justify-content:space-between;gap:12px;margin-bottom:18px;padding-bottom:12px;border-bottom:2px solid #e53935}
  .section-head h1{margin:0;font-size:22px;color:#f5f5f5}
  .section-meta{font-size:13px;color:#999}
  .videos-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:18px}
  .video-card{background:#1b1b1b;border:1px solid #2a2a2a;border-radius:6px;overflow:hidden;transition:transform .16s ease,border-color .16s ease,box-shadow .16s ease}
  .video-card:hover{transform:translateY(-3px);border-color:#e53935;box-shadow:0 10px 24px rgba(0,0,0,.35)}
  .video-card a{display:block;color:#f2f2f2}
  .thumb-wrap{position:relative;aspect-ratio:16/9;background:#222;overflow:hidden}
  .thumb-wrap img{display:block;width:100%;height:100%;object-fit:cover}
  .cat-pill{position:absolute;left:8px;bottom:8px;background:rgba(15,15,15,.85);color:#fff;font-size:11px;font-weight:600;padding:3px 8px;border-radius:4px;border-left:2px solid #e53935}
  .card-title{padding:11px 12px 13px;font-size:13px;font-weight:600;line-height:1.38;min-height:58px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
  .empty-box{background:#1b1b1b;border:1px solid #2b2b2b;border-radius:6px;padding:36px;text-align:center;color:#aaa}
  .pagination{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px;margin-top:28px}
  .pagination a,.pagination span{padding:9px 14px;border-radius:5px;background:#1b1b1b;border:1px solid #2d2d2d;color:#ddd;font-size:13px;font-weight:600}
  .pagination a:hover{border-color:#e53935;color:#fff}
  .pagination .current{background:#e53935;border-color:#e53935;color:#fff}
  .site-footer{background:#111;border-top:1px solid #242424;padding:24px;text-align:center;color:#777;font-size:13px}
  @media(max-width:991px){.videos-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}}
  @media(max-width:640px){.videos-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.site-branding{padding:14px 16px}.brand-name{font-size:24px}.page-wrap{padding:16px 14px 36px}}
</style>
</head>
<body>
<header class="site-header">
  <div class="site-branding">
    <div>
      <a href="/"><span class="brand-name">BucetaNet</span></a>
      <p class="site-description">Videos Porno Gratis – Porno Amador</p>
    </div>
    <form class="header-search" method="get" action="/">
      <input type="search" name="s" value="<?= $h($search) ?>" placeholder="Buscar vídeos, atrizes, categorias...">
      <button type="submit">Buscar</button>
    </form>
  </div>
  <nav class="main-navigation">
    <div class="nav-inner">
      <a href="/" class="<?= ($catSlug === '' && $tagSlug === '' && $search === '') ? 'active' : '' ?>">Início</a>
      <?php foreach ($topCats as $tc): ?>
        <a href="/category/<?= $h((string)$tc['slug']) ?>/" class="<?= $catSlug === $tc['slug'] ? 'active' : '' ?>">
          <?= $h((string)$tc['name']) ?>
        </a>
      <?php endforeach; ?>
    </div>
  </nav>
</header>

<main class="page-wrap">
  <div class="section-head">
    <div>
      <h1><?= $h($heading) ?></h1>
      <div class="section-meta"><?= $h($subHeading) ?></div>
    </div>
    <div class="section-meta">
      <?= number_format($totalRows, 0, ',', '.') ?> vídeos &bull; Página <?= $page ?> de <?= $totalPages ?>
    </div>
  </div>

  <?php if (!$videos): ?>
    <div class="empty-box">
      <p>Nenhum vídeo encontrado.</p>
      <p><a href="/">Voltar para a página inicial</a></p>
    </div>
  <?php else: ?>
    <div class="videos-grid">
      <?php foreach ($videos as $v): ?>
        <article class="video-card">
          <a href="/<?= $h((string)$v['slug']) ?>/" title="<?= $h((string)$v['title']) ?>">
            <div class="thumb-wrap">
              <?php if (!empty($v['thumbnail_url'])): ?>
                <img loading="lazy" src="<?= $h((string)$v['thumbnail_url']) ?>" alt="<?= $h((string)$v['title']) ?>">
              <?php endif; ?>
              <?php if (!empty($v['category_name'])): ?>
                <span class="cat-pill"><?= $h((string)$v['category_name']) ?></span>
              <?php endif; ?>
            </div>
            <div class="card-title"><?= $h((string)$v['title']) ?></div>
          </a>
        </article>
      <?php endforeach; ?>
    </div>

    <?php if ($totalPages > 1): ?>
      <nav class="pagination" aria-label="Paginação">
        <?php if ($page > 1): ?>
          <a href="<?= $h($pageUrl($page - 1)) ?>">&laquo; Anterior</a>
        <?php endif; ?>
        <?php
        $start = max(1, $page - 3);
        $end = min($totalPages, $page + 3);
        if ($start > 1) {
            echo '<a href="' . $h($pageUrl(1)) . '">1</a>';
            if ($start > 2) echo '<span>...</span>';
        }
        for ($i = $start; $i <= $end; $i++) {
            if ($i === $page) {
                echo '<span class="current">' . $i . '</span>';
            } else {
                echo '<a href="' . $h($pageUrl($i)) . '">' . $i . '</a>';
            }
        }
        if ($end < $totalPages) {
            if ($end < $totalPages - 1) echo '<span>...</span>';
            echo '<a href="' . $h($pageUrl($totalPages)) . '">' . $totalPages . '</a>';
        }
        ?>
        <?php if ($page < $totalPages): ?>
          <a href="<?= $h($pageUrl($page + 1)) ?>">Próxima &raquo;</a>
        <?php endif; ?>
      </nav>
    <?php endif; ?>
  <?php endif; ?>
</main>

<footer class="site-footer">
  BucetaNet &copy; <?= date('Y') ?> &bull; <?= number_format($totalRows, 0, ',', '.') ?> vídeos disponíveis
</footer>
</body>
</html>
