<?php
// Listado de cámaras online con filtros por género, edad, país, tag y búsqueda.
// Recibe todas las direcciones del listado (/women/tag-milf/...), ver inc/listing.php.

declare(strict_types=1);

require __DIR__ . '/inc/bootstrap.php';

$path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
if ($path === '/index.php') {
    $path = '/';
}
$filters = parse_listing_request($path, $_GET);

if ($filters === null) {
    http_response_code(404);
    $pageTitle = 'Not found';
    require __DIR__ . '/inc/header.php';
    echo '<p class="empty">This page doesn’t exist. <a href="/">Back to home</a></p>';
    require __DIR__ . '/inc/footer.php';
    exit;
}

// Una sola dirección por combinación de filtros: otro orden, mayúsculas, sin barra final o
// parámetros antiguos (?tag=milf) redirigen a la canónica.
$canonicalPath = listing_url(array_merge($filters, ['q' => '', 'p' => 1]));
if ($path !== $canonicalPath || array_intersect_key($_GET, array_flip(LISTING_FILTERS))) {
    header('Location: ' . listing_url($filters), true, 301);
    exit;
}

['source' => $source, 'g' => $gender, 'tag' => $tag, 'country' => $country, 'age' => $age, 'new' => $onlyNew, 'hd' => $onlyHd, 'q' => $search, 'p' => $page] = $filters;
$link = fn(array $changes): string => listing_url(array_merge($filters, $changes));
$perPage = (int) config('site.per_page');

$where  = ['r.is_online = 1'];
$params = [];

if (isset(SOURCES[$source])) {
    $where[] = 'r.source = ?';
    $params[] = $source;
}
if (isset(GENDERS[$gender])) {
    $where[] = 'r.gender = ?';
    $params[] = $gender;
}
if (isset(AGE_RANGES[$age])) {
    $where[] = 'r.age BETWEEN ? AND ?';
    array_push($params, ...AGE_RANGES[$age]);
}
if ($country === OTHER_COUNTRY) {
    $where[] = "r.country = ''";
} elseif ($country !== '') {
    $where[] = 'r.country = ?';
    $params[] = $country;
}
if ($onlyNew !== '') {
    $where[] = 'r.is_new = 1';
}
if ($onlyHd !== '') {
    $where[] = 'r.is_hd = 1';
}
if ($tag !== '') {
    $where[] = 'EXISTS (SELECT 1 FROM room_tags rt JOIN tags t ON t.id = rt.tag_id WHERE rt.room_id = r.id AND t.name = ?)';
    $params[] = $tag;
}
if ($search !== '') {
    $like = '%' . addcslashes($search, '%_\\') . '%';
    $where[] = '(r.username LIKE ? OR r.display_name LIKE ? OR EXISTS (SELECT 1 FROM room_tags rt JOIN tags t ON t.id = rt.tag_id WHERE rt.room_id = r.id AND t.name = ?))';
    array_push($params, $like, $like, mb_strtolower(ltrim($search, '#')));
}
$whereSql = implode(' AND ', $where);

$countStmt = db()->prepare("SELECT COUNT(*) FROM rooms r WHERE $whereSql");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();
$pages = max(1, (int) ceil($total / $perPage));
$page  = min($page, $pages);

$stmt = db()->prepare("
    SELECT r.source, r.username, r.display_name, r.gender, r.age, r.country, r.room_subject, r.current_show,
           r.is_new, r.is_hd, r.num_users, r.image_url_360x270, r.image_url
    FROM rooms r
    WHERE $whereSql
    ORDER BY r.num_users DESC
    LIMIT $perPage OFFSET " . (($page - 1) * $perPage));
$stmt->execute($params);
$rooms = $stmt->fetchAll();

// Tags y ubicaciones más frecuentes, de todas las plataformas o de la filtrada. Son iguales para
// el resto de filtros, así que se guardan en caché (ver cached()): una entrada por plataforma.
$sourceSql = isset(SOURCES[$source]) ? 'AND r.source = ' . db()->quote($source) : '';
$cacheSuffix = isset(SOURCES[$source]) ? "_$source" : '';

$topTags = cached("top_tags$cacheSuffix", fn(): array => $sourceSql !== ''
    ? db()->query("
        SELECT t.name, COUNT(*) AS total
        FROM room_tags rt
        JOIN tags t ON t.id = rt.tag_id
        JOIN rooms r ON r.id = rt.room_id AND r.is_online = 1 $sourceSql
        WHERE rt.is_online = 1
        GROUP BY t.id
        ORDER BY total DESC
        LIMIT 30
    ")->fetchAll()
    : top_tags_all_sources(30));

$topCountries = cached("top_countries$cacheSuffix", function () use ($sourceSql): array {
    $countries = db()->query("
        SELECT country, COUNT(*) AS total
        FROM rooms r
        WHERE is_online = 1 AND country <> '' $sourceSql
        GROUP BY country
        ORDER BY total DESC
        LIMIT 40
    ")->fetchAll();

    // Las salas sin país se agrupan al final como "Rest of the world".
    $other = (int) db()->query("SELECT COUNT(*) FROM rooms r WHERE is_online = 1 AND country = '' $sourceSql")->fetchColumn();
    if ($other > 0) {
        $countries[] = ['country' => OTHER_COUNTRY, 'total' => $other];
    }
    return $countries;
});

$canonical = config('site.url') . $canonicalPath;
$titleParts = array_filter([
    SOURCES[$source] ?? '',
    GENDERS[$gender] ?? '',
    $tag !== '' ? "#$tag" : '',
    $country !== '' ? country_name($country) : '',
    $age !== '' ? 'Age ' . age_range_label($age) : '',
    $onlyNew !== '' ? 'New' : '',
    $onlyHd !== '' ? 'HD' : '',
]);
$pageTitle = $titleParts ? implode(' · ', $titleParts) : null;
require __DIR__ . '/inc/header.php';
?>

<nav class="age-filter">
    <?php if (count(active_sources()) > 1): // con una sola plataforma activa el selector sobra ?>
    <span>Platform:</span>
    <a href="<?= e($link(['source' => null, 'p' => null])) ?>" class="<?= !isset(SOURCES[$source]) ? 'active' : '' ?>">All</a>
    <?php foreach (active_sources() as $key => $name): ?>
        <a href="<?= e($link(['source' => $key, 'p' => null])) ?>" class="<?= $source === $key ? 'active' : '' ?>"><?= e($name) ?></a>
    <?php endforeach; ?>
    <span class="filter-sep">Age:</span>
    <?php else: ?>
    <span>Age:</span>
    <?php endif; ?>
    <a href="<?= e($link(['age' => null, 'p' => null])) ?>" class="<?= !isset(AGE_RANGES[$age]) ? 'active' : '' ?>">All</a>
    <?php foreach (array_keys(AGE_RANGES) as $key): ?>
        <a href="<?= e($link(['age' => $key, 'p' => null])) ?>" class="<?= $age === (string) $key ? 'active' : '' ?>"><?= e(age_range_label((string) $key)) ?></a>
    <?php endforeach; ?>
    <span class="filter-sep">Show only:</span>
    <a href="<?= e($link(['new' => $onlyNew !== '' ? null : '1', 'p' => null])) ?>" class="<?= $onlyNew !== '' ? 'active' : '' ?>">New</a>
    <a href="<?= e($link(['hd' => $onlyHd !== '' ? null : '1', 'p' => null])) ?>" class="<?= $onlyHd !== '' ? 'active' : '' ?>">HD</a>
</nav>

<section class="tags">
    <?php foreach ($topTags as $t): ?>
        <a href="<?= e($link(['tag' => $t['name'], 'p' => null, 'q' => null])) ?>" class="<?= $tag === $t['name'] ? 'active' : '' ?>">#<?= e($t['name']) ?></a>
    <?php endforeach; ?>
</section>

<p class="summary">
    <?= number_format($total) ?><?php if ($onlyNew !== ''): ?> <strong>new</strong> <a href="<?= e($link(['new' => null, 'p' => null])) ?>">✕</a><?php endif; ?>
    <?php if ($onlyHd !== ''): ?><strong>HD</strong> <a href="<?= e($link(['hd' => null, 'p' => null])) ?>">✕</a><?php endif; ?>
    live cams
    <?php if ($tag !== ''): ?> tagged <strong>#<?= e($tag) ?></strong> <a href="<?= e($link(['tag' => null, 'p' => null])) ?>">✕</a><?php endif; ?>
    <?php if (isset(AGE_RANGES[$age])): ?> aged <strong><?= e(age_range_label($age)) ?></strong> <a href="<?= e($link(['age' => null, 'p' => null])) ?>">✕</a><?php endif; ?>
    <?php if (isset(SOURCES[$source])): ?> on <strong><?= e(SOURCES[$source]) ?></strong> <a href="<?= e($link(['source' => null, 'p' => null])) ?>">✕</a><?php endif; ?>
    <?php if ($country !== ''): ?> from <strong><?= e(country_name($country)) ?></strong> <a href="<?= e($link(['country' => null, 'p' => null])) ?>">✕</a><?php endif; ?>
    <?php if ($search !== ''): ?> for “<?= e($search) ?>”<?php endif; ?>
</p>

<?php if (!$rooms): ?>
    <p class="empty">No cams match your filters. Try a different one.</p>
<?php else: ?>
<section class="grid">
    <?php foreach ($rooms as $room): ?>
        <a class="card" href="<?= e(click_url($room['username'], 'room', $room['source'])) ?>" target="_blank" rel="noopener nofollow">
            <div class="<?= thumb_class($room['current_show']) ?>">
                <img src="<?= e($room['image_url_360x270'] ?: $room['image_url']) ?>" alt="<?= e($room['username']) ?>" loading="lazy" width="360" height="270">
                <?php if ($room['is_new']): ?><span class="badge new">New</span><?php endif; ?>
                <?php if ($room['is_hd']): ?><span class="badge hd">HD</span><?php endif; ?>
                <?= show_overlay($room['current_show']) ?>
                <?= viewers_badge((int) $room['num_users']) ?>
                <?= source_badge($room['source']) ?>
            </div>
            <div class="info">
                <div class="name">
                    <strong><?= e($room['username']) ?></strong>
                    <span><?= $room['age'] ? (int) $room['age'] : '' ?><?= gender_icon($room['gender']) ?> <?= e($room['country']) ?></span>
                </div>
                <p class="subject"><?= e(mb_strimwidth((string) $room['room_subject'], 0, 90, '…')) ?></p>
            </div>
        </a>
    <?php endforeach; ?>
</section>
<?php endif; ?>

<?php if ($pages > 1): ?>
<nav class="pagination">
    <?php if ($page > 1): ?><a href="<?= e($link(['p' => $page - 1])) ?>">« Previous</a><?php endif; ?>
    <span>Page <?= $page ?> of <?= $pages ?></span>
    <?php if ($page < $pages): ?><a href="<?= e($link(['p' => $page + 1])) ?>">Next »</a><?php endif; ?>
</nav>
<?php endif; ?>

<?php if ($topCountries): ?>
<h2 class="section-title wide">Locations</h2>
<section class="tags">
    <?php foreach ($topCountries as $c): ?>
        <a href="<?= e($link(['country' => $c['country'], 'p' => null])) ?>" class="<?= $country === $c['country'] ? 'active' : '' ?>"><?= e(country_name($c['country'])) ?> <span class="count"><?= (int) $c['total'] ?></span></a>
    <?php endforeach; ?>
</section>
<?php endif; ?>

<?php require __DIR__ . '/inc/footer.php'; ?>
