<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Bootstrap dan session
|--------------------------------------------------------------------------
*/

$bootstrapFile = __DIR__ . '/bootstrap.php';

if (is_file($bootstrapFile)) {
    require_once $bootstrapFile;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name('USERSESSID');
    session_start();
}

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/*
|--------------------------------------------------------------------------
| Informasi halaman
|--------------------------------------------------------------------------
*/

$siteName = isset($siteName)
    ? (string) $siteName
    : 'Platform Online';

$pageTitle = 'Game Populer';
$activeMenu = 'popular';

$isLoggedIn = !empty($_SESSION['user_id']);

$username = isset($_SESSION['username'])
    ? (string) $_SESSION['username']
    : 'Pengunjung';

/*
|--------------------------------------------------------------------------
| Pengaturan launch
|--------------------------------------------------------------------------
| play.php harus menerima:
|
|   api      = nexus / sgx
|   provider = kode provider
|   game     = kode game
|   type     = tipe game
|--------------------------------------------------------------------------
*/

$playEndpoint = 'play.php';

/*
|--------------------------------------------------------------------------
| Koneksi database PDO
|--------------------------------------------------------------------------
*/

$databaseFile = __DIR__ . '/config/database.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    if (!is_file($databaseFile)) {
        http_response_code(500);

        exit(
            'File koneksi database tidak ditemukan: ' .
            e($databaseFile)
        );
    }

    require_once $databaseFile;
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);

    exit(
        'Koneksi PDO $pdo tidak tersedia dari config/database.php.'
    );
}

$pdo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

$pdo->setAttribute(
    PDO::ATTR_DEFAULT_FETCH_MODE,
    PDO::FETCH_ASSOC
);

/*
|--------------------------------------------------------------------------
| Helper database
|--------------------------------------------------------------------------
*/

function popularTableExists(PDO $pdo, $table)
{
    $statement = $pdo->prepare(
        'SELECT COUNT(*)
         FROM information_schema.TABLES
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = :table_name'
    );

    $statement->execute([
        ':table_name' => (string) $table,
    ]);

    return (int) $statement->fetchColumn() > 0;
}

function popularTableColumns(PDO $pdo, $table)
{
    $statement = $pdo->prepare(
        'SELECT COLUMN_NAME
         FROM information_schema.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = :table_name'
    );

    $statement->execute([
        ':table_name' => (string) $table,
    ]);

    $columns = [];

    foreach ($statement->fetchAll() as $row) {
        $columnName = (string) (
            $row['COLUMN_NAME'] ??
            ''
        );

        if ($columnName !== '') {
            $columns[$columnName] = true;
        }
    }

    return $columns;
}

function popularHasColumn(array $columns, $column)
{
    return isset(
        $columns[(string) $column]
    );
}

/*
|--------------------------------------------------------------------------
| Helper tampilan dan URL
|--------------------------------------------------------------------------
*/

function popularTypeLabel($type)
{
    $type = strtoupper(
        trim((string) $type)
    );

    $labels = [
        'SL' => 'SLOT',
        'SLOT' => 'SLOT',
        'LC' => 'LIVE CASINO',
        'CASINO' => 'LIVE CASINO',
        'SB' => 'SPORTS',
        'SPORT' => 'SPORTS',
        'SPORTS' => 'SPORTS',
        'FH' => 'FISHING',
        'FISH' => 'FISHING',
        'FISHING' => 'FISHING',
        'PK' => 'POKER',
        'POKER' => 'POKER',
        'CB' => 'CARD',
        'CARD' => 'CARD',
        'LK' => 'LOTTERY',
        'LOTTERY' => 'LOTTERY',
        'ES' => 'E-SPORTS',
        'ESPORT' => 'E-SPORTS',
        'ESPORTS' => 'E-SPORTS',
        'OT' => 'LAINNYA',
        'MN' => 'MINI GAME',
    ];

    return isset($labels[$type])
        ? $labels[$type]
        : (
            $type !== ''
                ? $type
                : 'GAME'
        );
}

function popularTypeClass($type)
{
    $label = popularTypeLabel($type);

    $map = [
        'SLOT' => 'slot',
        'LIVE CASINO' => 'casino',
        'SPORTS' => 'sports',
        'FISHING' => 'fishing',
        'POKER' => 'poker',
        'CARD' => 'card',
        'LOTTERY' => 'lottery',
        'E-SPORTS' => 'esports',
        'MINI GAME' => 'mini',
    ];

    return isset($map[$label])
        ? $map[$label]
        : 'other';
}

function popularBuildPlayUrl(
    $endpoint,
    $source,
    $providerCode,
    $gameCode,
    $gameType
) {
    return
        (string) $endpoint .
        '?' .
        http_build_query([
            'api' => strtolower(
                trim((string) $source)
            ),
            'provider' => trim(
                (string) $providerCode
            ),
            'game' => trim(
                (string) $gameCode
            ),
            'type' => strtoupper(
                trim((string) $gameType)
            ),
        ]);
}

function popularBuildLoginUrl($playUrl)
{
    return
        'login.php?next=' .
        rawurlencode(
            (string) $playUrl
        );
}

function popularSafeImage($value)
{
    $value = trim(
        (string) $value
    );

    if ($value === '') {
        return 'assets/images/game-default.png';
    }

    if (
        preg_match('/^https?:\/\//i', $value) ||
        strpos($value, 'data:image/') === 0
    ) {
        return $value;
    }

    if (
        strpos($value, '//') === 0 ||
        preg_match('/[\r\n]/', $value)
    ) {
        return 'assets/images/game-default.png';
    }

    return ltrim($value, '/');
}

/*
|--------------------------------------------------------------------------
| Ambil game populer dari satu tabel
|--------------------------------------------------------------------------
*/

function popularFetchGames(
    PDO $pdo,
    $table,
    $source
) {
    $allowedTables = [
        'games_sgx',
        'games_nexus',
    ];

    if (
        !in_array(
            $table,
            $allowedTables,
            true
        )
    ) {
        return [];
    }

    if (!popularTableExists($pdo, $table)) {
        return [];
    }

    $columns = popularTableColumns(
        $pdo,
        $table
    );

    if (
        !popularHasColumn($columns, 'game_code') ||
        !popularHasColumn($columns, 'game_name') ||
        !popularHasColumn($columns, 'is_popular')
    ) {
        return [];
    }

    $providerColumn = '';

    if (
        $source === 'sgx' &&
        popularHasColumn(
            $columns,
            'game_provider'
        )
    ) {
        $providerColumn = 'game_provider';
    } elseif (
        popularHasColumn(
            $columns,
            'provider_code'
        )
    ) {
        $providerColumn = 'provider_code';
    }

    if ($providerColumn === '') {
        return [];
    }

    $imageColumn = '';

    if (
        popularHasColumn(
            $columns,
            'game_image'
        )
    ) {
        $imageColumn = 'game_image';
    } elseif (
        popularHasColumn(
            $columns,
            'banner'
        )
    ) {
        $imageColumn = 'banner';
    }

    $typeExpression = popularHasColumn(
        $columns,
        'game_type'
    )
        ? 'UPPER(TRIM(game_type))'
        : "''";

    $imageExpression = $imageColumn !== ''
        ? 'COALESCE(' .
            $imageColumn .
            ", '')"
        : "''";

    $orderExpression = popularHasColumn(
        $columns,
        'popular_order'
    )
        ? 'COALESCE(popular_order, 999)'
        : '999';

    $where = [
        'is_popular = 1',
    ];

    if (
        popularHasColumn(
            $columns,
            'game_status'
        )
    ) {
        $where[] =
            '(game_status = 1 OR ' .
            "UPPER(CAST(game_status AS CHAR)) " .
            "IN ('ACTIVE', 'ON', 'TRUE'))";
    }

    if (
        popularHasColumn(
            $columns,
            'is_active'
        )
    ) {
        $where[] = 'is_active = 1';
    }

    if (
        popularHasColumn(
            $columns,
            'is_show'
        )
    ) {
        $where[] = 'is_show = 1';
    }

    $sql =
        'SELECT
            id,
            ' .
            $providerColumn .
            ' AS provider_code,
            game_code,
            game_name,
            ' .
            $typeExpression .
            ' AS game_type,
            ' .
            $imageExpression .
            ' AS game_image,
            ' .
            $orderExpression .
            ' AS popular_order
         FROM ' .
            $table .
         '
         WHERE ' .
            implode(' AND ', $where) .
         '
         ORDER BY
            CASE
                WHEN ' .
                    $orderExpression .
                    ' > 0
                THEN 0
                ELSE 1
            END ASC,
            ' .
                $orderExpression .
                ' ASC,
            game_name ASC
         LIMIT 500';

    $rows = $pdo->query($sql)->fetchAll();

    foreach ($rows as &$row) {
        $row['source'] = $source;
    }

    unset($row);

    return $rows;
}

/*
|--------------------------------------------------------------------------
| Ambil dan gabungkan game
|--------------------------------------------------------------------------
*/

$popularGames = [];
$pageError = '';

try {
    $popularGames = array_merge(
        popularFetchGames(
            $pdo,
            'games_sgx',
            'sgx'
        ),
        popularFetchGames(
            $pdo,
            'games_nexus',
            'nexus'
        )
    );
} catch (Throwable $exception) {
    $popularGames = [];

    $pageError =
        'Game populer belum dapat dimuat. ' .
        'Periksa struktur tabel game.';

    error_log(
        'POPULAR PAGE ERROR: ' .
        $exception->getMessage()
    );
}

/*
|--------------------------------------------------------------------------
| Normalisasi dan hapus duplikat
|--------------------------------------------------------------------------
*/

$gameSeen = [];
$normalizedGames = [];

foreach ($popularGames as $game) {
    $source = strtolower(
        trim(
            (string) (
                $game['source'] ??
                ''
            )
        )
    );

    $providerCode = trim(
        (string) (
            $game['provider_code'] ??
            ''
        )
    );

    $gameCode = trim(
        (string) (
            $game['game_code'] ??
            ''
        )
    );

    $gameName = trim(
        (string) (
            $game['game_name'] ??
            'Game'
        )
    );

    $gameType = strtoupper(
        trim(
            (string) (
                $game['game_type'] ??
                ''
            )
        )
    );

    if (
        !in_array(
            $source,
            [
                'sgx',
                'nexus',
            ],
            true
        ) ||
        $providerCode === '' ||
        $gameCode === ''
    ) {
        continue;
    }

    $uniqueKey =
        $source .
        '|' .
        $providerCode .
        '|' .
        $gameCode;

    if (isset($gameSeen[$uniqueKey])) {
        continue;
    }

    $gameSeen[$uniqueKey] = true;

    $playUrl = popularBuildPlayUrl(
        $playEndpoint,
        $source,
        $providerCode,
        $gameCode,
        $gameType
    );

    $normalizedGames[] = [
        'source' => $source,
        'provider_code' => $providerCode,
        'game_code' => $gameCode,
        'game_name' => $gameName !== ''
            ? $gameName
            : 'Game',
        'game_type' => $gameType,
        'type_label' =>
            popularTypeLabel($gameType),
        'type_class' =>
            popularTypeClass($gameType),
        'game_image' =>
            popularSafeImage(
                $game['game_image'] ??
                ''
            ),
        'popular_order' => (int) (
            $game['popular_order'] ??
            999
        ),
        'play_url' => $playUrl,
        'action_url' => $isLoggedIn
            ? $playUrl
            : popularBuildLoginUrl(
                $playUrl
            ),
    ];
}

usort(
    $normalizedGames,
    function ($first, $second) {
        $firstOrder = (int) (
            $first['popular_order'] ??
            999
        );

        $secondOrder = (int) (
            $second['popular_order'] ??
            999
        );

        $firstPriority =
            $firstOrder > 0
                ? 0
                : 1;

        $secondPriority =
            $secondOrder > 0
                ? 0
                : 1;

        if ($firstPriority !== $secondPriority) {
            return
                $firstPriority <
                $secondPriority
                    ? -1
                    : 1;
        }

        if ($firstOrder !== $secondOrder) {
            return
                $firstOrder <
                $secondOrder
                    ? -1
                    : 1;
        }

        return strcasecmp(
            (string) $first['game_name'],
            (string) $second['game_name']
        );
    }
);

$popularGames = $normalizedGames;

/*
|--------------------------------------------------------------------------
| Daftar filter
|--------------------------------------------------------------------------
*/

$typeFilters = [];
$providerFilters = [];

$sgxCount = 0;
$nexusCount = 0;

foreach ($popularGames as $game) {
    $typeFilters[
        (string) $game['type_label']
    ] = true;

    $providerFilters[
        (string) $game['provider_code']
    ] = true;

    if ($game['source'] === 'sgx') {
        $sgxCount++;
    }

    if ($game['source'] === 'nexus') {
        $nexusCount++;
    }
}

$typeFilters = array_keys($typeFilters);
$providerFilters = array_keys($providerFilters);

sort($typeFilters);
sort($providerFilters);

/*
|--------------------------------------------------------------------------
| Header
|--------------------------------------------------------------------------
*/

require __DIR__ . '/includes/header.php';

?>

<style>
/*
|--------------------------------------------------------------------------
| Halaman game populer
|--------------------------------------------------------------------------
*/

.popular-page {
    position: relative;

    width: 100%;
    min-height: calc(100vh - 70px);

    padding: 12px 8px 30px;

    overflow: hidden;

    background:
        radial-gradient(
            circle at 50% -5%,
            rgba(0, 139, 255, 0.30),
            transparent 300px
        ),
        radial-gradient(
            circle at 110% 45%,
            rgba(255, 179, 0, 0.13),
            transparent 210px
        ),
        linear-gradient(
            180deg,
            #031431 0%,
            #020a1c 55%,
            #010610 100%
        );
}

.popular-page::before,
.popular-page::after {
    position: absolute;

    width: 205px;
    height: 205px;

    content: "";

    border-radius: 50%;

    filter: blur(42px);

    pointer-events: none;
}

.popular-page::before {
    top: 160px;
    left: -175px;

    background:
        rgba(0, 126, 255, 0.21);
}

.popular-page::after {
    right: -180px;
    bottom: 190px;

    background:
        rgba(255, 178, 0, 0.13);
}

.popular-shell {
    position: relative;
    z-index: 2;

    width: 100%;
    max-width: 620px;

    margin: 0 auto;
}

/*
|--------------------------------------------------------------------------
| Breadcrumb
|--------------------------------------------------------------------------
*/

.popular-breadcrumb {
    display: flex;

    align-items: center;

    margin-bottom: 9px;

    gap: 5px;

    color: #758ba7;

    font-size: 7px;
}

.popular-breadcrumb a {
    color: #8fd5ff;

    text-decoration: none;
}

.popular-breadcrumb span {
    color: #ffc943;
}

/*
|--------------------------------------------------------------------------
| Heading
|--------------------------------------------------------------------------
*/

.popular-heading {
    display: grid;

    justify-items: center;

    margin-bottom: 11px;

    text-align: center;
}

.popular-heading-crown {
    margin-bottom: -4px;

    color: #ffd451;

    font-size: 31px;
    line-height: 1;

    text-shadow:
        0 1px 0 #fff5ac,
        0 3px 0 #713600,
        0 0 11px rgba(255, 194, 39, 0.68);
}

.popular-heading h1 {
    margin: 0;

    color: #ffd450;

    background:
        linear-gradient(
            180deg,
            #fff9ba 0%,
            #ffd451 36%,
            #e58b00 72%,
            #fff09a 100%
        );

    background-clip: text;
    -webkit-background-clip: text;

    font-size: clamp(25px, 7vw, 36px);
    font-weight: 1000;

    letter-spacing: -0.035em;

    -webkit-text-fill-color: transparent;

    filter:
        drop-shadow(0 2px 0 #713600)
        drop-shadow(0 5px 6px rgba(0, 0, 0, 0.72));
}

.popular-heading p {
    max-width: 455px;

    margin: 6px 0 0;

    color: #96aac5;

    font-size: 9px;
    line-height: 1.55;
}

.popular-account-state {
    display: inline-flex;

    min-height: 24px;

    align-items: center;

    margin-top: 8px;
    padding: 0 9px;

    gap: 5px;

    border:
        1px solid rgba(70, 222, 150, 0.25);

    border-radius: 999px;

    color: #a9dec4;

    background:
        rgba(4, 48, 32, 0.56);

    font-size: 7px;
    font-weight: 850;
}

.popular-account-state i {
    width: 5px;
    height: 5px;

    border-radius: 50%;

    background: #50e39a;

    box-shadow:
        0 0 6px rgba(80, 227, 154, 0.70);
}

/*
|--------------------------------------------------------------------------
| Hero
|--------------------------------------------------------------------------
*/

.popular-hero {
    position: relative;

    margin-bottom: 10px;
    padding: 15px;

    overflow: hidden;

    border:
        1px solid rgba(255, 198, 48, 0.44);

    border-radius: 16px;

    background:
        radial-gradient(
            circle at 90% 0,
            rgba(255, 191, 32, 0.17),
            transparent 150px
        ),
        radial-gradient(
            circle at 0 100%,
            rgba(0, 157, 255, 0.17),
            transparent 165px
        ),
        linear-gradient(
            145deg,
            #0a2b5d,
            #04132f
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.08),
        0 9px 24px rgba(0, 0, 0, 0.34);
}

.popular-hero::before {
    position: absolute;

    top: 0;
    right: 18px;
    left: 18px;

    height: 1px;

    content: "";

    background:
        linear-gradient(
            90deg,
            transparent,
            rgba(255, 239, 157, 0.84),
            transparent
        );
}

.popular-hero-main {
    display: grid;

    grid-template-columns:
        56px
        minmax(0, 1fr);

    align-items: center;

    gap: 11px;
}

.popular-hero-icon {
    display: grid;

    width: 56px;
    height: 56px;

    place-items: center;

    border:
        2px solid #ffd24d;

    border-radius: 17px;

    color: #2d1700;

    background:
        linear-gradient(
            145deg,
            #fff6aa,
            #ffc52f 58%,
            #b86900
        );

    font-size: 24px;
    font-weight: 1000;

    box-shadow:
        inset 0 2px 0 rgba(255, 255, 255, 0.65),
        0 0 15px rgba(255, 183, 18, 0.30);
}

.popular-hero h2 {
    margin: 0;

    color: #ffffff;

    font-size: 15px;
    font-weight: 1000;
}

.popular-hero p {
    margin: 5px 0 0;

    color: #a3b6ce;

    font-size: 8px;
    line-height: 1.55;
}

.popular-stats {
    display: grid;

    margin-top: 12px;

    grid-template-columns:
        repeat(3, minmax(0, 1fr));

    gap: 6px;
}

.popular-stat {
    display: grid;

    min-height: 47px;

    align-content: center;
    justify-items: center;

    border:
        1px solid rgba(0, 163, 255, 0.18);

    border-radius: 9px;

    background:
        rgba(3, 27, 60, 0.62);

    text-align: center;
}

.popular-stat strong {
    color: #ffd34e;

    font-size: 14px;
    font-weight: 1000;
}

.popular-stat small {
    margin-top: 2px;

    color: #7188a5;

    font-size: 6px;
}

/*
|--------------------------------------------------------------------------
| Error
|--------------------------------------------------------------------------
*/

.popular-error {
    margin-bottom: 10px;
    padding: 9px 10px;

    border:
        1px solid rgba(255, 77, 77, 0.38);

    border-radius: 10px;

    color: #ffd6d6;
    background:
        rgba(102, 12, 17, 0.48);

    font-size: 8px;
    line-height: 1.45;
}

/*
|--------------------------------------------------------------------------
| Search and filters
|--------------------------------------------------------------------------
*/

.popular-tools {
    display: grid;

    margin-bottom: 10px;

    gap: 7px;
}

.popular-search {
    position: relative;
}

.popular-search input {
    display: block;

    width: 100%;
    min-height: 43px;

    padding:
        0
        42px
        0
        12px;

    border:
        1px solid rgba(0, 163, 255, 0.34);

    border-radius: 10px;

    outline: none;

    color: #ffffff;

    background:
        linear-gradient(
            180deg,
            rgba(3, 19, 44, 0.97),
            rgba(1, 9, 23, 0.99)
        );

    font-family: inherit;
    font-size: 10px;
}

.popular-search input::placeholder {
    color: #566d89;
}

.popular-search input:focus {
    border-color: #ffc83f;

    box-shadow:
        0 0 0 2px rgba(255, 192, 38, 0.10),
        0 0 9px rgba(255, 185, 25, 0.31);
}

.popular-search-icon {
    position: absolute;

    top: 50%;
    right: 12px;

    color: #ffd24c;

    font-size: 16px;

    transform: translateY(-50%);
}

.popular-filter-row {
    display: flex;

    overflow-x: auto;

    padding-bottom: 3px;

    gap: 6px;

    scrollbar-width: none;
}

.popular-filter-row::-webkit-scrollbar {
    display: none;
}

.popular-filter-button {
    flex: 0 0 auto;

    min-height: 29px;

    padding: 0 11px;

    border:
        1px solid rgba(0, 157, 255, 0.28);

    border-radius: 999px;

    color: #8fa7c3;

    background:
        linear-gradient(
            180deg,
            #08284f,
            #03142d
        );

    font-size: 7px;
    font-weight: 900;

    cursor: pointer;
}

.popular-filter-button.is-active {
    border-color:
        rgba(255, 211, 78, 0.72);

    color: #271400;

    background:
        linear-gradient(
            180deg,
            #ffe687,
            #ffb719
        );

    box-shadow:
        0 0 8px rgba(255, 183, 23, 0.28);
}

.popular-result-head {
    display: flex;

    align-items: center;
    justify-content: space-between;

    margin:
        11px
        1px
        7px;
}

.popular-result-head h2 {
    margin: 0;

    color: #ffffff;

    font-size: 12px;
}

.popular-result-head small {
    color: #758ba7;

    font-size: 7px;
}

/*
|--------------------------------------------------------------------------
| Game grid
|--------------------------------------------------------------------------
*/

.popular-grid {
    display: grid;

    grid-template-columns:
        repeat(3, minmax(0, 1fr));

    gap: 8px;
}

.popular-game-card {
    position: relative;

    display: grid;

    min-width: 0;

    overflow: hidden;

    border:
        1px solid rgba(0, 157, 255, 0.27);

    border-radius: 12px;

    background:
        linear-gradient(
            180deg,
            rgba(7, 30, 65, 0.98),
            rgba(2, 12, 29, 0.99)
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.07),
        0 4px 12px rgba(0, 0, 0, 0.25);

    transition:
        transform 160ms ease,
        border-color 160ms ease,
        box-shadow 160ms ease;
}

.popular-game-card:hover {
    transform: translateY(-2px);

    border-color:
        rgba(255, 194, 37, 0.58);

    box-shadow:
        0 7px 15px rgba(0, 0, 0, 0.34),
        0 0 9px rgba(255, 185, 23, 0.14);
}

.popular-game-image-link {
    position: relative;

    display: block;

    width: 100%;
    aspect-ratio: 1 / 1;

    overflow: hidden;

    background:
        linear-gradient(
            145deg,
            #082a5a,
            #04132d
        );
}

.popular-game-image {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;

    transition:
        transform 220ms ease,
        filter 220ms ease;
}

.popular-game-card:hover
.popular-game-image {
    transform: scale(1.045);

    filter: brightness(1.08);
}

.popular-badge {
    position: absolute;
    z-index: 2;

    top: 6px;
    left: 6px;

    display: inline-flex;

    min-height: 19px;

    align-items: center;

    padding: 0 6px;

    border:
        1px solid #ffe389;

    border-radius: 999px;

    color: #2d1700;

    background:
        linear-gradient(
            180deg,
            #fff29a,
            #ffc32e
        );

    font-size: 5px;
    font-weight: 1000;

    box-shadow:
        0 2px 6px rgba(0, 0, 0, 0.32);
}

.popular-source {
    position: absolute;
    z-index: 2;

    top: 6px;
    right: 6px;

    display: inline-flex;

    min-height: 19px;

    align-items: center;

    padding: 0 6px;

    border:
        1px solid rgba(96, 210, 255, 0.40);

    border-radius: 999px;

    color: #bceaff;

    background:
        rgba(3, 32, 69, 0.82);

    font-size: 5px;
    font-weight: 1000;
}

.popular-play-overlay {
    position: absolute;

    inset: 0;

    display: grid;

    place-items: center;

    opacity: 0;

    background:
        rgba(0, 7, 19, 0.52);

    transition:
        opacity 160ms ease;
}

.popular-game-card:hover
.popular-play-overlay {
    opacity: 1;
}

.popular-play-circle {
    display: grid;

    width: 42px;
    height: 42px;

    place-items: center;

    border:
        2px solid #ffe48c;

    border-radius: 50%;

    color: #2a1600;

    background:
        linear-gradient(
            145deg,
            #fff39d,
            #ffbd24
        );

    font-size: 18px;
    font-weight: 1000;

    box-shadow:
        0 0 13px rgba(255, 190, 32, 0.40);
}

.popular-game-body {
    display: grid;

    min-width: 0;

    padding: 8px;

    gap: 5px;
}

.popular-game-meta {
    display: flex;

    align-items: center;
    justify-content: space-between;

    gap: 4px;
}

.popular-type-label {
    overflow: hidden;

    color: #61cbff;

    font-size: 5px;
    font-weight: 1000;

    letter-spacing: 0.05em;

    text-overflow: ellipsis;
    white-space: nowrap;
}

.popular-provider-label {
    overflow: hidden;

    max-width: 58%;

    color: #8ca2bc;

    font-size: 5px;
    font-weight: 900;

    text-overflow: ellipsis;
    white-space: nowrap;
}

.popular-game-title {
    display: -webkit-box;

    min-height: 25px;

    margin: 0;

    overflow: hidden;

    color: #ffffff;

    font-size: 9px;
    font-weight: 1000;

    line-height: 1.35;

    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}

.popular-play-button {
    display: flex;

    min-height: 30px;

    align-items: center;
    justify-content: center;

    border:
        1px solid rgba(255, 205, 70, 0.50);

    border-radius: 7px;

    color: #271400;

    background:
        linear-gradient(
            180deg,
            #ffe37e,
            #f3aa14
        );

    font-size: 6px;
    font-weight: 1000;

    text-decoration: none;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.48),
        0 2px 0 #673800;
}

/*
|--------------------------------------------------------------------------
| Empty
|--------------------------------------------------------------------------
*/

.popular-empty {
    grid-column: 1 / -1;

    padding: 23px 12px;

    border:
        1px dashed rgba(255, 194, 39, 0.30);

    border-radius: 12px;

    color: #91a5bf;
    background:
        rgba(4, 18, 42, 0.74);

    font-size: 9px;
    line-height: 1.6;

    text-align: center;
}

.popular-empty strong {
    color: #ffd34e;
}

/*
|--------------------------------------------------------------------------
| Notice
|--------------------------------------------------------------------------
*/

.popular-notice {
    display: grid;

    margin-top: 12px;
    padding: 11px;

    grid-template-columns:
        43px
        minmax(0, 1fr);

    align-items: center;

    gap: 10px;

    border:
        1px solid rgba(78, 231, 151, 0.25);

    border-radius: 12px;

    background:
        linear-gradient(
            180deg,
            rgba(6, 67, 42, 0.50),
            rgba(2, 31, 21, 0.76)
        );
}

.popular-notice-icon {
    display: grid;

    width: 43px;
    height: 43px;

    place-items: center;

    border:
        2px solid #62e7a2;

    border-radius: 50%;

    color: #d6ffe8;
    background:
        rgba(4, 45, 29, 0.85);

    font-size: 13px;
    font-weight: 1000;
}

.popular-notice strong {
    display: block;

    color: #ffffff;

    font-size: 9px;
}

.popular-notice p {
    margin: 4px 0 0;

    color: #9bc8b2;

    font-size: 7px;
    line-height: 1.55;
}

.popular-footer-note {
    margin: 12px 0 0;

    color: #627894;

    font-size: 7px;
    line-height: 1.55;

    text-align: center;
}

@media (max-width: 470px) {
    .popular-grid {
        grid-template-columns:
            repeat(3, minmax(0, 1fr));
    }
}

@media (max-width: 390px) {
    .popular-hero {
        padding: 12px;
    }

    .popular-grid {
        gap: 6px;
    }

    .popular-game-body {
        padding: 6px;
    }
}

@media (max-width: 340px) {
    .popular-grid {
        grid-template-columns:
            repeat(2, minmax(0, 1fr));
    }

    .popular-stats {
        grid-template-columns: 1fr;
    }
}
</style>

<section class="popular-page">
    <div class="popular-shell">

        <nav
            class="popular-breadcrumb"
            aria-label="Breadcrumb"
        >
            <a href="index.php">
                Home
            </a>

            <span>›</span>

            <strong>
                Game Populer
            </strong>
        </nav>

        <header class="popular-heading">
            <span
                class="popular-heading-crown"
                aria-hidden="true"
            >
                ♛
            </span>

            <h1>
                GAME POPULER
            </h1>

            <p>
                Pilihan game unggulan dari berbagai provider.
                Tekan game untuk langsung bermain.
            </p>

            <span class="popular-account-state">
                <i></i>

                <?php if ($isLoggedIn): ?>
                    Halo <?= e($username); ?>, siap bermain
                <?php else: ?>
                    Login diperlukan untuk menjalankan game
                <?php endif; ?>
            </span>
        </header>

        <?php if ($pageError !== ''): ?>

            <div class="popular-error">
                <?= e($pageError); ?>
            </div>

        <?php endif; ?>

        <section class="popular-hero">

            <div class="popular-hero-main">

                <span class="popular-hero-icon">
                    ★
                </span>

                <div>
                    <h2>
                        Pilihan Favorit Member
                    </h2>

                    <p>
                        Daftar ini otomatis mengambil game dengan
                        status populer dari database SGX dan Nexus.
                    </p>
                </div>

            </div>

            <div class="popular-stats">

                <div class="popular-stat">
                    <strong>
                        <?= count($popularGames); ?>
                    </strong>

                    <small>
                        TOTAL GAME
                    </small>
                </div>

                <div class="popular-stat">
                    <strong>
                        <?= $nexusCount; ?>
                    </strong>

                    <small>
                        NEXUS
                    </small>
                </div>

                <div class="popular-stat">
                    <strong>
                        <?= $sgxCount; ?>
                    </strong>

                    <small>
                        SGX
                    </small>
                </div>

            </div>

        </section>

        <section class="popular-tools">

            <div class="popular-search">
                <input
                    id="popularSearch"
                    type="search"
                    placeholder="Cari nama game atau provider..."
                    autocomplete="off"
                    aria-label="Cari game populer"
                >

                <span
                    class="popular-search-icon"
                    aria-hidden="true"
                >
                    ⌕
                </span>
            </div>

            <div class="popular-filter-row">

                <button
                    class="popular-filter-button is-active"
                    type="button"
                    data-popular-filter="ALL"
                >
                    SEMUA
                </button>

                <button
                    class="popular-filter-button"
                    type="button"
                    data-popular-filter="NEXUS"
                >
                    NEXUS
                </button>

                <button
                    class="popular-filter-button"
                    type="button"
                    data-popular-filter="SGX"
                >
                    SGX
                </button>

                <?php foreach (
                    $typeFilters
                    as $typeFilter
                ): ?>

                    <button
                        class="popular-filter-button"
                        type="button"
                        data-popular-filter="<?= e(
                            strtoupper($typeFilter)
                        ); ?>"
                    >
                        <?= e($typeFilter); ?>
                    </button>

                <?php endforeach; ?>

            </div>

        </section>

        <div class="popular-result-head">
            <h2>
                Daftar Game
            </h2>

            <small id="popularResultCount">
                <?= count($popularGames); ?> game
            </small>
        </div>

        <section class="popular-grid">

            <?php if (empty($popularGames)): ?>

                <div class="popular-empty">
                    Belum ada game dengan
                    <strong>is_popular = 1</strong>.
                    Aktifkan game populer melalui halaman admin.
                </div>

            <?php else: ?>

                <?php foreach (
                    $popularGames
                    as $game
                ): ?>

                    <?php
                    $searchText = strtolower(
                        $game['game_name'] .
                        ' ' .
                        $game['provider_code'] .
                        ' ' .
                        $game['type_label'] .
                        ' ' .
                        $game['source']
                    );
                    ?>

                    <article
                        class="popular-game-card"
                        data-popular-game
                        data-popular-source="<?= e(
                            strtoupper(
                                $game['source']
                            )
                        ); ?>"
                        data-popular-type="<?= e(
                            strtoupper(
                                $game['type_label']
                            )
                        ); ?>"
                        data-popular-search="<?= e(
                            $searchText
                        ); ?>"
                    >

                        <a
                            class="popular-game-image-link"
                            href="<?= e(
                                $game['action_url']
                            ); ?>"
                            aria-label="Main <?= e(
                                $game['game_name']
                            ); ?>"
                            <?= !$isLoggedIn
                                ? 'onclick="alert(\'Silakan login terlebih dahulu untuk bermain.\');"'
                                : ''; ?>
                        >

                            <span class="popular-badge">
                                POPULER
                            </span>

                            <span class="popular-source">
                                <?= e(
                                    strtoupper(
                                        $game['source']
                                    )
                                ); ?>
                            </span>

                            <img
                                class="popular-game-image"
                                src="<?= e(
                                    $game['game_image']
                                ); ?>"
                                alt="<?= e(
                                    $game['game_name']
                                ); ?>"
                                loading="lazy"
                                onerror="
                                    this.onerror = null;
                                    this.src =
                                        'assets/images/game-default.png';
                                "
                            >

                            <span class="popular-play-overlay">
                                <span class="popular-play-circle">
                                    ▶
                                </span>
                            </span>

                        </a>

                        <div class="popular-game-body">

                            <div class="popular-game-meta">

                                <span class="popular-type-label">
                                    <?= e(
                                        $game['type_label']
                                    ); ?>
                                </span>

                                <span class="popular-provider-label">
                                    <?= e(
                                        $game['provider_code']
                                    ); ?>
                                </span>

                            </div>

                            <h3 class="popular-game-title">
                                <?= e(
                                    $game['game_name']
                                ); ?>
                            </h3>

                            <a
                                class="popular-play-button"
                                href="<?= e(
                                    $game['action_url']
                                ); ?>"
                                <?= !$isLoggedIn
                                    ? 'onclick="alert(\'Silakan login terlebih dahulu untuk bermain.\');"'
                                    : ''; ?>
                            >
                                <?= $isLoggedIn
                                    ? 'MAIN SEKARANG'
                                    : 'LOGIN UNTUK MAIN'; ?>
                            </a>

                        </div>

                    </article>

                <?php endforeach; ?>

                <div
                    class="popular-empty"
                    id="popularEmpty"
                    style="display: none;"
                >
                    Game tidak ditemukan.
                    Gunakan kata kunci atau filter lainnya.
                </div>

            <?php endif; ?>

        </section>

        <section class="popular-notice">

            <span class="popular-notice-icon">
                ✓
            </span>

            <div>
                <strong>
                    Game dijalankan melalui sistem launch
                </strong>

                <p>
                    Saat tombol main ditekan, game diarahkan
                    ke play.php dengan source, provider,
                    dan kode game yang sesuai.
                </p>
            </div>

        </section>

        <p class="popular-footer-note">
            Daftar game dapat diatur melalui kolom
            is_popular dan popular_order pada database.
        </p>

    </div>
</section>

<script>
(function () {
    'use strict';

    var searchInput =
        document.getElementById(
            'popularSearch'
        );

    var gameCards =
        document.querySelectorAll(
            '[data-popular-game]'
        );

    var filterButtons =
        document.querySelectorAll(
            '[data-popular-filter]'
        );

    var emptyState =
        document.getElementById(
            'popularEmpty'
        );

    var resultCount =
        document.getElementById(
            'popularResultCount'
        );

    var activeFilter = 'ALL';

    function normalize(value) {
        return String(value || '')
            .toUpperCase()
            .trim();
    }

    function applyFilter() {
        var searchValue = normalize(
            searchInput
                ? searchInput.value
                : ''
        );

        var visibleCount = 0;

        Array.prototype.forEach.call(
            gameCards,
            function (card) {
                var source = normalize(
                    card.getAttribute(
                        'data-popular-source'
                    )
                );

                var type = normalize(
                    card.getAttribute(
                        'data-popular-type'
                    )
                );

                var searchable = normalize(
                    card.getAttribute(
                        'data-popular-search'
                    )
                );

                var filterMatch =
                    activeFilter === 'ALL' ||
                    activeFilter === source ||
                    activeFilter === type;

                var searchMatch =
                    searchValue === '' ||
                    searchable.indexOf(
                        searchValue
                    ) !== -1;

                var show =
                    filterMatch &&
                    searchMatch;

                card.style.display =
                    show
                        ? ''
                        : 'none';

                if (show) {
                    visibleCount++;
                }
            }
        );

        if (emptyState) {
            emptyState.style.display =
                visibleCount === 0
                    ? 'block'
                    : 'none';
        }

        if (resultCount) {
            resultCount.textContent =
                visibleCount + ' game';
        }
    }

    if (searchInput) {
        searchInput.addEventListener(
            'input',
            applyFilter
        );
    }

    Array.prototype.forEach.call(
        filterButtons,
        function (button) {
            button.addEventListener(
                'click',
                function () {
                    activeFilter = normalize(
                        button.getAttribute(
                            'data-popular-filter'
                        )
                    );

                    Array.prototype.forEach.call(
                        filterButtons,
                        function (item) {
                            item.classList.remove(
                                'is-active'
                            );
                        }
                    );

                    button.classList.add(
                        'is-active'
                    );

                    applyFilter();
                }
            );
        }
    );
})();
</script>

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