<?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 = 'Poker & Card';
$activeMenu = 'poker';

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

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

$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
|--------------------------------------------------------------------------
*/

function pokerNormalizeProviderName($value)
{
    $value = strtolower(
        trim((string) $value)
    );

    $value = preg_replace(
        '/[^a-z0-9]+/',
        '',
        $value
    );

    return (string) $value;
}

function pokerProviderKey($providerName)
{
    $normalized = pokerNormalizeProviderName(
        $providerName
    );

    if ($normalized === '') {
        $normalized = 'provider';
    }

    return substr(
        sha1($normalized),
        0,
        12
    );
}

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

    if ($value === '') {
        return 'SL';
    }

    $words = preg_split(
        '/\s+/',
        $value
    );

    $initial = '';

    foreach ($words as $word) {
        $word = preg_replace(
            '/[^A-Za-z0-9]/',
            '',
            (string) $word
        );

        if ($word === '') {
            continue;
        }

        $initial .= strtoupper(
            substr($word, 0, 1)
        );

        if (strlen($initial) >= 2) {
            break;
        }
    }

    return $initial !== ''
        ? $initial
        : 'SL';
}

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

    if ($value === '') {
        return '';
    }

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

    if (
        strpos($value, '//') === 0 ||
        preg_match('/[\r\n]/', $value)
    ) {
        return '';
    }

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

function pokerBuildPlayUrl(
    $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 pokerBuildLoginUrl($playUrl)
{
    return
        'login.php?next=' .
        rawurlencode(
            (string) $playUrl
        );
}

function pokerPageUrl(
    $page,
    $providerKey,
    $search
) {
    $parameters = [];

    if ($providerKey !== '') {
        $parameters['provider'] =
            $providerKey;
    }

    if ($search !== '') {
        $parameters['q'] = $search;
    }

    if ((int) $page > 1) {
        $parameters['page'] = (int) $page;
    }

    return
        'poker.php' .
        (
            empty($parameters)
                ? ''
                : '?' .
                    http_build_query(
                        $parameters
                    )
        );
}

/*
|--------------------------------------------------------------------------
| Ambil provider aktif dari kedua sumber
|--------------------------------------------------------------------------
*/

$providerRows = [];
$providerGroups = [];
$providerCounts = [];
$pageError = '';

try {
    $providerSql = "
        SELECT
            'sgx' AS source,
            provider_code,
            provider_name,
            provider_image,
            is_popular,
            popular_order
        FROM providers_sgx
        WHERE provider_type IN ('PK', 'CB')
          AND provider_status = 1
          AND is_active = 1

        UNION ALL

        SELECT
            'nexus' AS source,
            provider_code,
            provider_name,
            provider_image,
            is_popular,
            popular_order
        FROM providers_nexus
        WHERE provider_type IN ('PK', 'CB')
          AND provider_status = 1
          AND is_active = 1
    ";

    $providerRows =
        $pdo->query(
            $providerSql
        )->fetchAll();

    $sgxCountRows = $pdo->query(
        "SELECT
            game_provider AS provider_code,
            COUNT(*) AS total_games
         FROM games_sgx
         WHERE game_type IN ('PK', 'CB', 'POKER', 'CARD')
           AND game_status = 1
           AND is_active = 1
         GROUP BY game_provider"
    )->fetchAll();

    foreach ($sgxCountRows as $countRow) {
        $providerCounts[
            'sgx|' .
            (string) $countRow['provider_code']
        ] = (int) $countRow['total_games'];
    }

    $nexusCountRows = $pdo->query(
        "SELECT
            provider_code,
            COUNT(*) AS total_games
         FROM games_nexus
         WHERE game_type IN ('PK', 'CB', 'POKER', 'CARD')
           AND game_status = 1
           AND is_active = 1
         GROUP BY provider_code"
    )->fetchAll();

    foreach ($nexusCountRows as $countRow) {
        $providerCounts[
            'nexus|' .
            (string) $countRow['provider_code']
        ] = (int) $countRow['total_games'];
    }
} catch (Throwable $exception) {
    $pageError =
        'Data provider belum dapat dimuat.';

    error_log(
        'POKER PROVIDER ERROR: ' .
        $exception->getMessage()
    );
}

/*
|--------------------------------------------------------------------------
| Gabungkan provider dengan nama yang sama
|--------------------------------------------------------------------------
| Contoh:
| PRAGMATIC PLAY dari SGX dan Pragmatic Play dari Nexus
| menjadi satu tombol provider.
|--------------------------------------------------------------------------
*/

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

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

    $providerName = trim(
        (string) (
            $providerRow['provider_name'] ??
            $providerCode
        )
    );

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

    $groupKey = pokerProviderKey(
        $providerName
    );

    if (!isset($providerGroups[$groupKey])) {
        $providerGroups[$groupKey] = [
            'key' => $groupKey,
            'name' => $providerName,
            'image' => '',
            'initial' =>
                pokerInitial($providerName),
            'is_popular' => 0,
            'popular_order' => 999999,
            'game_count' => 0,
            'members' => [],
        ];
    }

    $providerImage = pokerSafeImage(
        $providerRow['provider_image'] ??
        ''
    );

    if (
        $providerGroups[$groupKey]['image'] === '' &&
        $providerImage !== ''
    ) {
        $providerGroups[$groupKey]['image'] =
            $providerImage;
    }

    $providerGroups[$groupKey]['is_popular'] =
        max(
            (int) $providerGroups[
                $groupKey
            ]['is_popular'],
            (int) (
                $providerRow['is_popular'] ??
                0
            )
        );

    $popularOrder = (int) (
        $providerRow['popular_order'] ??
        0
    );

    if ($popularOrder > 0) {
        $providerGroups[
            $groupKey
        ]['popular_order'] = min(
            (int) $providerGroups[
                $groupKey
            ]['popular_order'],
            $popularOrder
        );
    }

    $memberCountKey =
        $source .
        '|' .
        $providerCode;

    $providerGroups[
        $groupKey
    ]['game_count'] +=
        (int) (
            $providerCounts[
                $memberCountKey
            ] ??
            0
        );

    $providerGroups[
        $groupKey
    ]['members'][] = [
        'source' => $source,
        'provider_code' => $providerCode,
    ];
}

$providerGroups = array_values(
    $providerGroups
);

usort(
    $providerGroups,
    function ($first, $second) {
        $firstPopular =
            (int) $first['is_popular'];

        $secondPopular =
            (int) $second['is_popular'];

        if ($firstPopular !== $secondPopular) {
            return $firstPopular >
                $secondPopular
                ? -1
                : 1;
        }

        $firstOrder =
            (int) $first['popular_order'];

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

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

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

/*
|--------------------------------------------------------------------------
| Filter halaman
|--------------------------------------------------------------------------
*/

$selectedProviderKey = isset(
    $_GET['provider']
)
    ? trim(
        (string) $_GET['provider']
    )
    : '';

$search = isset($_GET['q'])
    ? trim(
        (string) $_GET['q']
    )
    : '';

if (strlen($search) > 80) {
    $search = substr(
        $search,
        0,
        80
    );
}

$page = isset($_GET['page'])
    ? max(
        1,
        (int) $_GET['page']
    )
    : 1;

$perPage = 30;

$selectedProvider = null;

foreach ($providerGroups as $providerGroup) {
    if (
        $providerGroup['key'] ===
        $selectedProviderKey
    ) {
        $selectedProvider =
            $providerGroup;

        break;
    }
}

if (
    $selectedProviderKey !== '' &&
    $selectedProvider === null
) {
    $selectedProviderKey = '';
}

/*
|--------------------------------------------------------------------------
| Query game dari SGX dan Nexus
|--------------------------------------------------------------------------
*/

$games = [];
$totalGames = 0;
$totalPages = 1;

$sgxWhere = [
    "game_type IN ('PK', 'CB', 'POKER', 'CARD')",
    'game_status = 1',
    'is_active = 1',
];

$nexusWhere = [
    "game_type IN ('PK', 'CB', 'POKER', 'CARD')",
    'game_status = 1',
    'is_active = 1',
];

$params = [];

if ($selectedProvider !== null) {
    $sgxCodes = [];
    $nexusCodes = [];

    foreach (
        $selectedProvider['members']
        as $member
    ) {
        if ($member['source'] === 'sgx') {
            $sgxCodes[] =
                (string) $member[
                    'provider_code'
                ];
        }

        if ($member['source'] === 'nexus') {
            $nexusCodes[] =
                (string) $member[
                    'provider_code'
                ];
        }
    }

    if (empty($sgxCodes)) {
        $sgxWhere[] = '1 = 0';
    } else {
        $sgxPlaceholders = [];

        foreach (
            array_values(
                array_unique($sgxCodes)
            )
            as $index => $providerCode
        ) {
            $placeholder =
                ':sgx_provider_' .
                $index;

            $sgxPlaceholders[] =
                $placeholder;

            $params[$placeholder] =
                $providerCode;
        }

        $sgxWhere[] =
            'game_provider IN (' .
            implode(
                ', ',
                $sgxPlaceholders
            ) .
            ')';
    }

    if (empty($nexusCodes)) {
        $nexusWhere[] = '1 = 0';
    } else {
        $nexusPlaceholders = [];

        foreach (
            array_values(
                array_unique($nexusCodes)
            )
            as $index => $providerCode
        ) {
            $placeholder =
                ':nexus_provider_' .
                $index;

            $nexusPlaceholders[] =
                $placeholder;

            $params[$placeholder] =
                $providerCode;
        }

        $nexusWhere[] =
            'provider_code IN (' .
            implode(
                ', ',
                $nexusPlaceholders
            ) .
            ')';
    }
}

if ($search !== '') {
    $sgxWhere[] =
        '(
            game_name LIKE :sgx_search_name
            OR game_code LIKE :sgx_search_code
            OR game_provider LIKE :sgx_search_provider
        )';

    $nexusWhere[] =
        '(
            game_name LIKE :nexus_search_name
            OR game_code LIKE :nexus_search_code
            OR provider_code LIKE :nexus_search_provider
        )';

    $like = '%' . $search . '%';

    $params[':sgx_search_name'] =
        $like;

    $params[':sgx_search_code'] =
        $like;

    $params[':sgx_search_provider'] =
        $like;

    $params[':nexus_search_name'] =
        $like;

    $params[':nexus_search_code'] =
        $like;

    $params[':nexus_search_provider'] =
        $like;
}

$gameUnionSql = "
    SELECT
        'sgx' AS source,
        id,
        game_provider AS provider_code,
        game_code,
        game_name,
        UPPER(TRIM(game_type)) AS game_type,
        game_image,
        is_popular,
        popular_order
    FROM games_sgx
    WHERE " .
        implode(
            ' AND ',
            $sgxWhere
        ) .
    "

    UNION ALL

    SELECT
        'nexus' AS source,
        id,
        provider_code,
        game_code,
        game_name,
        UPPER(TRIM(game_type)) AS game_type,
        game_image,
        is_popular,
        popular_order
    FROM games_nexus
    WHERE " .
        implode(
            ' AND ',
            $nexusWhere
        );

try {
    $countStatement = $pdo->prepare(
        'SELECT COUNT(*)
         FROM (' .
            $gameUnionSql .
         ') AS poker_games'
    );

    $countStatement->execute($params);

    $totalGames = (int)
        $countStatement->fetchColumn();

    $totalPages = max(
        1,
        (int) ceil(
            $totalGames /
            $perPage
        )
    );

    if ($page > $totalPages) {
        $page = $totalPages;
    }

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

    $listSql =
        'SELECT
            poker_games.*
         FROM (' .
            $gameUnionSql .
         ') AS poker_games
         ORDER BY
            poker_games.is_popular DESC,
            CASE
                WHEN poker_games.is_popular = 1
                 AND poker_games.popular_order > 0
                THEN 0
                ELSE 1
            END ASC,
            poker_games.popular_order ASC,
            poker_games.game_name ASC
         LIMIT ' .
            (int) $perPage .
         ' OFFSET ' .
            (int) $offset;

    $listStatement = $pdo->prepare(
        $listSql
    );

    $listStatement->execute($params);

    $games = $listStatement->fetchAll();
} catch (Throwable $exception) {
    $games = [];
    $totalGames = 0;
    $totalPages = 1;

    if ($pageError === '') {
        $pageError =
            'Daftar game poker belum dapat dimuat.';
    }

    error_log(
        'POKER GAME ERROR: ' .
        $exception->getMessage()
    );
}

/*
|--------------------------------------------------------------------------
| Normalisasi game dan URL launch
|--------------------------------------------------------------------------
*/

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

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

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

    $playUrl = pokerBuildPlayUrl(
        $playEndpoint,
        $source,
        $providerCode,
        $gameCode,
        (string) (
            $game['game_type'] ??
            'PK'
        )
    );

    $game['game_image'] =
        pokerSafeImage(
            $game['game_image'] ??
            ''
        );

    $game['play_url'] = $playUrl;

    $game['action_url'] =
        $isLoggedIn
            ? $playUrl
            : pokerBuildLoginUrl(
                $playUrl
            );
}

unset($game);

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

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

?>

<style>
/*
|--------------------------------------------------------------------------
| Halaman poker
|--------------------------------------------------------------------------
*/

.poker-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%
        );
}

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

    width: 205px;
    height: 205px;

    content: "";

    border-radius: 50%;

    filter: blur(42px);

    pointer-events: none;
}

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

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

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

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

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

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

    margin: 0 auto;
}

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

.poker-breadcrumb {
    display: flex;

    align-items: center;

    margin-bottom: 9px;

    gap: 5px;

    color: #758ba7;

    font-size: 7px;
}

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

    text-decoration: none;
}

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

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

.poker-heading {
    display: grid;

    justify-items: center;

    margin-bottom: 11px;

    text-align: center;
}

.poker-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);
}

.poker-heading h1 {
    margin: 0;

    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));
}

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

    margin: 6px 0 0;

    color: #96aac5;

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

.poker-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;
}

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

    border-radius: 50%;

    background: #50e39a;

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

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

.poker-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);
}

.poker-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
        );
}

.poker-hero-main {
    display: grid;

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

    align-items: center;

    gap: 11px;
}

.poker-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: 21px;
    font-weight: 1000;

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

.poker-hero h2 {
    margin: 0;

    color: #ffffff;

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

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

    color: #a3b6ce;

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

.poker-stats {
    display: grid;

    margin-top: 12px;

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

    gap: 6px;
}

.poker-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;
}

.poker-stat strong {
    color: #ffd34e;

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

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

    color: #7188a5;

    font-size: 6px;
}

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

.poker-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;
}

/*
|--------------------------------------------------------------------------
| Pencarian
|--------------------------------------------------------------------------
*/

.poker-search-form {
    position: relative;

    margin-bottom: 10px;
}

.poker-search-form input {
    display: block;

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

    padding:
        0
        85px
        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;
}

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

.poker-search-form 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);
}

.poker-search-button {
    position: absolute;

    top: 5px;
    right: 5px;
    bottom: 5px;

    min-width: 72px;

    border:
        1px solid #ffe17f;

    border-radius: 7px;

    color: #301700;

    background:
        linear-gradient(
            180deg,
            #fff08c,
            #ffc32d 50%,
            #d87700
        );

    font-family: inherit;
    font-size: 7px;
    font-weight: 1000;

    cursor: pointer;
}

/*
|--------------------------------------------------------------------------
| Provider
|--------------------------------------------------------------------------
*/

.poker-section-head {
    display: flex;

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

    margin:
        11px
        1px
        7px;
}

.poker-section-head h2 {
    margin: 0;

    color: #ffffff;

    font-size: 12px;
}

.poker-section-head small {
    color: #758ba7;

    font-size: 7px;
}

.poker-provider-scroll {
    display: flex;

    overflow-x: auto;

    padding:
        1px
        1px
        6px;

    gap: 7px;

    scrollbar-width: none;
}

.poker-provider-scroll::-webkit-scrollbar {
    display: none;
}

.poker-provider-card {
    display: grid;

    width: 82px;
    min-width: 82px;
    min-height: 91px;

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

    padding: 7px;

    border:
        1px solid rgba(0, 159, 255, 0.24);

    border-radius: 11px;

    color: #a9bdd4;

    background:
        linear-gradient(
            180deg,
            rgba(8, 34, 72, 0.97),
            rgba(2, 14, 33, 0.99)
        );

    text-align: center;
    text-decoration: none;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.06),
        0 4px 11px rgba(0, 0, 0, 0.22);
}

.poker-provider-card.is-active {
    border-color:
        rgba(255, 205, 68, 0.67);

    background:
        radial-gradient(
            circle at 50% 0,
            rgba(255, 191, 30, 0.14),
            transparent 70px
        ),
        linear-gradient(
            180deg,
            rgba(55, 38, 7, 0.96),
            rgba(18, 13, 3, 0.99)
        );

    box-shadow:
        0 0 9px rgba(255, 183, 23, 0.16);
}

.poker-provider-logo {
    position: relative;

    display: grid;

    width: 43px;
    height: 43px;

    place-items: center;

    overflow: hidden;

    border:
        1px solid rgba(255, 205, 69, 0.42);

    border-radius: 11px;

    color: #ffd34e;

    background:
        linear-gradient(
            145deg,
            rgba(255, 199, 44, 0.12),
            rgba(4, 24, 53, 0.95)
        );

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

.poker-provider-logo img {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: contain;
}

.poker-provider-name {
    display: -webkit-box;

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

    margin-top: 5px;

    overflow: hidden;

    color: #ffffff;

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

    line-height: 1.35;

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

.poker-provider-count {
    margin-top: 2px;

    color: #7087a1;

    font-size: 5px;
}

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

.poker-game-head {
    display: flex;

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

    margin:
        11px
        1px
        7px;
}

.poker-game-head h2 {
    margin: 0;

    color: #ffffff;

    font-size: 12px;
}

.poker-game-head small {
    color: #758ba7;

    font-size: 7px;
}

.poker-game-grid {
    display: grid;

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

    gap: 8px;
}

.poker-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;
}

.poker-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);
}

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

    display: block;

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

    overflow: hidden;

    background:
        radial-gradient(
            circle at 50% 25%,
            rgba(255, 196, 38, 0.15),
            transparent 65px
        ),
        linear-gradient(
            145deg,
            #082a5a,
            #04132d
        );
}

.poker-game-image-link.image-error::after {
    position: absolute;

    inset: 0;

    display: grid;

    content: "POKER";

    place-items: center;

    color: #ffd34e;

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

    letter-spacing: 0.12em;

    text-shadow:
        0 2px 5px rgba(0, 0, 0, 0.55);
}

.poker-game-image {
    display: block;

    width: 100%;
    height: 100%;

    object-fit: cover;

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

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

    filter: brightness(1.08);
}

.poker-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);
}

.poker-play-overlay {
    position: absolute;

    inset: 0;

    display: grid;

    place-items: center;

    opacity: 0;

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

    transition:
        opacity 160ms ease;
}

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

.poker-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);
}

.poker-game-body {
    display: grid;

    min-width: 0;

    padding: 8px;

    gap: 5px;
}

.poker-game-card-meta {
    display: flex;

    min-width: 0;

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

    gap: 5px;
}

.poker-game-provider {
    overflow: hidden;

    min-width: 0;

    color: #61cbff;

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

    letter-spacing: 0.04em;

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

.poker-game-type {
    display: inline-flex;

    min-height: 16px;

    flex: 0 0 auto;
    align-items: center;

    padding: 0 5px;

    border: 1px solid rgba(255, 205, 70, 0.30);
    border-radius: 999px;

    color: #ffd34e;
    background: rgba(255, 193, 31, 0.08);

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

.poker-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;
}

.poker-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 dan pagination
|--------------------------------------------------------------------------
*/

.poker-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;
}

.poker-pagination {
    display: flex;

    flex-wrap: wrap;
    justify-content: center;

    margin-top: 12px;

    gap: 5px;
}

.poker-page-link {
    display: inline-flex;

    min-width: 31px;
    min-height: 31px;

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

    padding: 0 8px;

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

    border-radius: 8px;

    color: #9ab1cc;

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

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

    text-decoration: none;
}

.poker-page-link.is-active {
    border-color: #ffe17f;

    color: #301700;

    background:
        linear-gradient(
            180deg,
            #fff08c,
            #ffc32d 50%,
            #d87700
        );
}

.poker-page-link.is-disabled {
    opacity: 0.42;

    pointer-events: none;
}

/*
|--------------------------------------------------------------------------
| Catatan
|--------------------------------------------------------------------------
*/

.poker-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)
        );
}

.poker-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;
}

.poker-notice strong {
    display: block;

    color: #ffffff;

    font-size: 9px;
}

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

    color: #9bc8b2;

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

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

    color: #627894;

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

    text-align: center;
}

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

    .poker-game-grid {
        gap: 6px;
    }

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

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

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

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

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

            <span>›</span>

            <strong>
                Poker
            </strong>
        </nav>

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

            <h1>
                POKER & CARD
            </h1>

            <p>
                Pilih provider dan mainkan poker atau card game
                dari seluruh koleksi yang tersedia.
            </p>

            <span class="poker-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="poker-error">
                <?= e($pageError); ?>
            </div>

        <?php endif; ?>

        <section class="poker-hero">

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

                <span class="poker-hero-icon">
                    ♠
                </span>

                <div>
                    <h2>
                        Semua Poker & Card dalam Satu Halaman
                    </h2>

                    <p>
                        Provider poker dan card dari berbagai sumber ditampilkan
                        dalam satu halaman, sementara proses launch tetap
                        menggunakan API yang sesuai.
                    </p>
                </div>

            </div>

            <div class="poker-stats">

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

                    <small>
                        PROVIDER
                    </small>
                </div>

                <div class="poker-stat">
                    <strong>
                        <?= $totalGames; ?>
                    </strong>

                    <small>
                        GAME POKER
                    </small>
                </div>

                <div class="poker-stat">
                    <strong>
                        <?= $page; ?>/<?= $totalPages; ?>
                    </strong>

                    <small>
                        HALAMAN
                    </small>
                </div>

            </div>

        </section>

        <form
            class="poker-search-form"
            method="get"
            action="poker.php"
        >

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

                <input
                    type="hidden"
                    name="provider"
                    value="<?= e(
                        $selectedProviderKey
                    ); ?>"
                >

            <?php endif; ?>

            <input
                type="search"
                name="q"
                value="<?= e($search); ?>"
                placeholder="Cari poker, card game, kode, atau provider..."
                autocomplete="off"
                aria-label="Cari game poker"
            >

            <button
                class="poker-search-button"
                type="submit"
            >
                CARI
            </button>

        </form>

        <div class="poker-section-head">
            <h2>
                Pilih Provider Poker
            </h2>

            <small>
                Geser untuk melihat lainnya
            </small>
        </div>

        <nav
            class="poker-provider-scroll"
            aria-label="Daftar provider poker"
        >

            <a
                class="poker-provider-card <?= $selectedProviderKey === ''
                    ? 'is-active'
                    : ''; ?>"
                href="<?= e(
                    pokerPageUrl(
                        1,
                        '',
                        $search
                    )
                ); ?>"
            >
                <span class="poker-provider-logo">
                    ALL
                </span>

                <span class="poker-provider-name">
                    SEMUA PROVIDER
                </span>

                <span class="poker-provider-count">
                    Lihat semua game
                </span>
            </a>

            <?php foreach (
                $providerGroups
                as $providerGroup
            ): ?>

                <a
                    class="poker-provider-card <?= $selectedProviderKey ===
                        $providerGroup['key']
                        ? 'is-active'
                        : ''; ?>"
                    href="<?= e(
                        pokerPageUrl(
                            1,
                            $providerGroup['key'],
                            $search
                        )
                    ); ?>"
                >

                    <span class="poker-provider-logo">

                        <span>
                            <?= e(
                                $providerGroup['initial']
                            ); ?>
                        </span>

                        <?php if (
                            $providerGroup['image'] !== ''
                        ): ?>

                            <img
                                src="<?= e(
                                    $providerGroup['image']
                                ); ?>"
                                alt="<?= e(
                                    $providerGroup['name']
                                ); ?>"
                                loading="lazy"
                                onerror="
                                    this.style.display = 'none';
                                "
                            >

                        <?php endif; ?>

                    </span>

                    <span class="poker-provider-name">
                        <?= e(
                            $providerGroup['name']
                        ); ?>
                    </span>

                    <span class="poker-provider-count">
                        <?= (int) $providerGroup[
                            'game_count'
                        ]; ?> game
                    </span>

                </a>

            <?php endforeach; ?>

        </nav>

        <div class="poker-game-head">
            <h2>
                <?= $selectedProvider !== null
                    ? e($selectedProvider['name'])
                    : 'Semua Poker & Card'; ?>
            </h2>

            <small>
                <?= $totalGames; ?> hasil
            </small>
        </div>

        <section class="poker-game-grid">

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

                <div class="poker-empty">
                    Tidak ada poker atau card game yang sesuai
                    dengan provider atau pencarian ini.
                </div>

            <?php else: ?>

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

                    <article class="poker-game-card">

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

                            <?php if (
                                !empty(
                                    $game['is_popular']
                                )
                            ): ?>

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

                            <?php endif; ?>

                            <?php if (
                                $game['game_image'] !== ''
                            ): ?>

                                <img
                                    class="poker-game-image"
                                    src="<?= e(
                                        $game['game_image']
                                    ); ?>"
                                    alt="<?= e(
                                        $game['game_name']
                                    ); ?>"
                                    loading="lazy"
                                    onerror="
                                        this.style.display = 'none';
                                        this.parentElement.classList.add(
                                            'image-error'
                                        );
                                    "
                                >

                            <?php endif; ?>

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

                        </a>

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

                            <div class="poker-game-card-meta">
                                <span class="poker-game-provider">
                                    <?= e(
                                        $game['provider_code']
                                    ); ?>
                                </span>

                                <span class="poker-game-type">
                                    <?= e(
                                        $game['game_type'] === 'CB'
                                            ? 'CARD'
                                            : 'POKER'
                                    ); ?>
                                </span>
                            </div>

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

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

                        </div>

                    </article>

                <?php endforeach; ?>

            <?php endif; ?>

        </section>

        <?php if ($totalPages > 1): ?>

            <?php
            $paginationStart = max(
                1,
                $page - 2
            );

            $paginationEnd = min(
                $totalPages,
                $page + 2
            );
            ?>

            <nav
                class="poker-pagination"
                aria-label="Pagination game poker"
            >

                <a
                    class="poker-page-link <?= $page <= 1
                        ? 'is-disabled'
                        : ''; ?>"
                    href="<?= e(
                        pokerPageUrl(
                            max(1, $page - 1),
                            $selectedProviderKey,
                            $search
                        )
                    ); ?>"
                >
                    ‹
                </a>

                <?php if (
                    $paginationStart > 1
                ): ?>

                    <a
                        class="poker-page-link"
                        href="<?= e(
                            pokerPageUrl(
                                1,
                                $selectedProviderKey,
                                $search
                            )
                        ); ?>"
                    >
                        1
                    </a>

                <?php endif; ?>

                <?php for (
                    $paginationPage =
                        $paginationStart;
                    $paginationPage <=
                        $paginationEnd;
                    $paginationPage++
                ): ?>

                    <a
                        class="poker-page-link <?= $paginationPage ===
                            $page
                            ? 'is-active'
                            : ''; ?>"
                        href="<?= e(
                            pokerPageUrl(
                                $paginationPage,
                                $selectedProviderKey,
                                $search
                            )
                        ); ?>"
                        <?= $paginationPage ===
                            $page
                            ? 'aria-current="page"'
                            : ''; ?>
                    >
                        <?= $paginationPage; ?>
                    </a>

                <?php endfor; ?>

                <?php if (
                    $paginationEnd <
                    $totalPages
                ): ?>

                    <a
                        class="poker-page-link"
                        href="<?= e(
                            pokerPageUrl(
                                $totalPages,
                                $selectedProviderKey,
                                $search
                            )
                        ); ?>"
                    >
                        <?= $totalPages; ?>
                    </a>

                <?php endif; ?>

                <a
                    class="poker-page-link <?= $page >=
                        $totalPages
                        ? 'is-disabled'
                        : ''; ?>"
                    href="<?= e(
                        pokerPageUrl(
                            min(
                                $totalPages,
                                $page + 1
                            ),
                            $selectedProviderKey,
                            $search
                        )
                    ); ?>"
                >
                    ›
                </a>

            </nav>

        <?php endif; ?>

        <section class="poker-notice">

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

            <div>
                <strong>
                    Source API tidak ditampilkan pada kartu game
                </strong>

                <p>
                    Source dan tipe game hanya digunakan secara internal agar
                    play.php memilih API serta kategori yang benar.
                </p>
            </div>

        </section>

        <p class="poker-footer-note">
            Game aktif otomatis diambil dari games_sgx dan
            games_nexus dengan tipe PK dan CB.
        </p>

    </div>
</section>

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