<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| RTP.PHP
|--------------------------------------------------------------------------
| Menampilkan SEMUA provider dan game bertipe SLOT dari:
| - providers_sgx + games_sgx
| - providers_nexus + games_nexus
|
| Prioritas provider: Pragmatic, PG Soft, provider populer, lainnya.
| Prioritas game: game populer, popular_order, nama game.
|
| Angka RTP adalah indikator tampilan acak yang stabil selama 10 menit.
| Ini bukan RTP resmi dari provider.
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/bootstrap.php';

$pageTitle = 'RTP Slot';
$activeMenu = 'rtp';

/*
|--------------------------------------------------------------------------
| Konfigurasi
|--------------------------------------------------------------------------
*/

$rtpMinimum = 67;
$rtpMaximum = 95;
$rtpIntervalSeconds = 600; // 10 menit
$rtpBucket = intdiv(time(), $rtpIntervalSeconds);
$rtpNextUpdateAt = ($rtpBucket + 1) * $rtpIntervalSeconds;

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

if (!function_exists('rtpDisplayPercent')) {
    function rtpDisplayPercent(
        string $uniqueKey,
        int $bucket,
        int $minimum = 67,
        int $maximum = 95
    ): int {
        $minimum = max(0, min(100, $minimum));
        $maximum = max($minimum, min(100, $maximum));

        $range = ($maximum - $minimum) + 1;

        $hash = hash(
            'sha256',
            $uniqueKey . '|' . $bucket
        );

        $number = hexdec(
            substr($hash, 0, 8)
        );

        return $minimum + ($number % $range);
    }
}

if (!function_exists('rtpSafeImage')) {
    function rtpSafeImage(
        $value,
        string $fallback
    ): string {
        $value = trim((string) $value);

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

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

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

/*
|--------------------------------------------------------------------------
| Ambil provider SLOT dan game SLOT populer
|--------------------------------------------------------------------------
*/

$rtpRows = [];
$rtpError = '';

$rtpSql = "
    SELECT
        result_data.api_source,
        result_data.provider_code,
        result_data.provider_name,
        result_data.provider_image,
        result_data.provider_is_popular,
        result_data.provider_popular_order,
        result_data.game_code,
        result_data.game_name,
        result_data.game_image,
        result_data.game_is_popular,
        result_data.game_popular_order
    FROM
    (
        SELECT
            'sgx' AS api_source,
            p.provider_code,
            p.provider_name,
            COALESCE(p.provider_image, '') AS provider_image,
            COALESCE(p.is_popular, 0) AS provider_is_popular,
            COALESCE(NULLIF(p.popular_order, 0), 999999) AS provider_popular_order,
            g.game_code,
            g.game_name,
            COALESCE(g.game_image, '') AS game_image,
            COALESCE(g.is_popular, 0) AS game_is_popular,
            COALESCE(NULLIF(g.popular_order, 0), 999999) AS game_popular_order
        FROM providers_sgx AS p
        INNER JOIN games_sgx AS g
            ON UPPER(TRIM(g.game_provider)) = UPPER(TRIM(p.provider_code))
        WHERE UPPER(TRIM(COALESCE(p.provider_type, ''))) IN ('SL', 'SLOT')
          AND UPPER(TRIM(COALESCE(g.game_type, ''))) IN ('SL', 'SLOT')
          AND p.provider_status = 1
          AND p.is_active = 1
          AND g.game_status = 1
          AND g.is_active = 1

        UNION ALL

        SELECT
            'nexus' AS api_source,
            p.provider_code,
            p.provider_name,
            COALESCE(p.provider_image, '') AS provider_image,
            COALESCE(p.is_popular, 0) AS provider_is_popular,
            COALESCE(NULLIF(p.popular_order, 0), 999999) AS provider_popular_order,
            g.game_code,
            g.game_name,
            COALESCE(g.game_image, '') AS game_image,
            COALESCE(g.is_popular, 0) AS game_is_popular,
            COALESCE(NULLIF(g.popular_order, 0), 999999) AS game_popular_order
        FROM providers_nexus AS p
        INNER JOIN games_nexus AS g
            ON UPPER(TRIM(g.provider_code)) = UPPER(TRIM(p.provider_code))
        WHERE UPPER(TRIM(COALESCE(p.provider_type, ''))) IN ('SL', 'SLOT')
          AND UPPER(TRIM(COALESCE(g.game_type, ''))) IN ('SL', 'SLOT')
          AND p.provider_status = 1
          AND p.is_active = 1
          AND g.game_status = 1
          AND g.is_active = 1
    ) AS result_data
    ORDER BY
        CASE
            WHEN UPPER(TRIM(result_data.provider_code)) IN (
                'PP', 'PRAGMATIC', 'PRAGMATICPLAY', 'PRAGMATIC_PLAY'
            ) OR UPPER(result_data.provider_name) LIKE '%PRAGMATIC%'
            THEN 0

            WHEN UPPER(TRIM(result_data.provider_code)) IN (
                'PG', 'PGSOFT', 'PG_SOFT'
            ) OR REPLACE(REPLACE(UPPER(result_data.provider_name), ' ', ''), '-', '') LIKE '%PGSOFT%'
            THEN 1

            ELSE 2
        END ASC,
        result_data.provider_is_popular DESC,
        result_data.provider_popular_order ASC,
        result_data.provider_name ASC,
        result_data.api_source ASC,
        result_data.game_is_popular DESC,
        result_data.game_popular_order ASC,
        result_data.game_name ASC
";

try {
    $rtpStatement = $pdo->query($rtpSql);

    if ($rtpStatement) {
        $rtpRows = $rtpStatement->fetchAll(
            PDO::FETCH_ASSOC
        );
    }
} catch (Throwable $exception) {
    $rtpRows = [];
    $rtpError = $exception->getMessage();

    error_log(
        'RTP PAGE ERROR: ' .
        $rtpError
    );
}

/*
|--------------------------------------------------------------------------
| Kelompokkan berdasarkan provider
|--------------------------------------------------------------------------
*/

$rtpProviders = [];

foreach ($rtpRows as $row) {
    $apiSource = strtolower(
        trim(
            (string) (
                $row['api_source'] ??
                ''
            )
        )
    );

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

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

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

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

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

    $providerKey =
        $apiSource .
        '|' .
        $providerCode;

    if (!isset($rtpProviders[$providerKey])) {
        $rtpProviders[$providerKey] = [
            'key' => $providerKey,
            'api_source' => $apiSource,
            'provider_code' => $providerCode,
            'provider_name' => $providerName !== ''
                ? $providerName
                : $providerCode,
            'provider_image' => rtpSafeImage(
                $row['provider_image'] ?? '',
                'assets/images/provider-default.png'
            ),
            'is_popular' => !empty(
                $row['provider_is_popular']
            ),
            'games' => [],
        ];
    }

    $gameUniqueKey =
        $apiSource .
        '|' .
        $providerCode .
        '|' .
        $gameCode;

    $rtpPercent = rtpDisplayPercent(
        $gameUniqueKey,
        $rtpBucket,
        $rtpMinimum,
        $rtpMaximum
    );

    $playUrl = 'play.php?' . http_build_query([
        'api' => $apiSource,
        'provider' => $providerCode,
        'game' => $gameCode,
        'type' => 'SL',
        'return' => 'rtp.php',
    ]);

    $rtpProviders[$providerKey]['games'][] = [
        'game_code' => $gameCode,
        'game_name' => $gameName,
        'game_image' => rtpSafeImage(
            $row['game_image'] ?? '',
            'assets/images/game-default.png'
        ),
        'is_popular' => !empty(
            $row['game_is_popular']
        ),
        'rtp' => $rtpPercent,
        'play_url' => $playUrl,
    ];
}

$rtpProviders = array_values(
    $rtpProviders
);

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

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

?>

<style>
.rtp-page {
    min-height: calc(100vh - 70px);
    padding: 13px 9px 28px;
    background:
        radial-gradient(
            circle at 50% -5%,
            rgba(0, 145, 255, 0.24),
            transparent 300px
        ),
        linear-gradient(
            180deg,
            #031431 0%,
            #020a1c 58%,
            #010610 100%
        );
}

.rtp-shell {
    width: 100%;
    max-width: 560px;
    margin: 0 auto;
}

.rtp-heading {
    margin-bottom: 12px;
    text-align: center;
}

.rtp-heading small {
    display: block;
    color: #55cfff;
    font-size: 8px;
    font-weight: 1000;
    letter-spacing: 0.15em;
}

.rtp-heading h1 {
    margin: 4px 0 0;
    color: #ffd451;
    font-size: clamp(24px, 7vw, 34px);
    font-weight: 1000;
    text-shadow:
        0 2px 0 #6f3600,
        0 0 12px rgba(255, 194, 39, 0.32);
}

.rtp-heading p {
    margin: 6px auto 0;
    max-width: 440px;
    color: #93a9c3;
    font-size: 8px;
    line-height: 1.55;
}

.rtp-update-box {
    display: flex;
    min-height: 39px;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 11px;
    padding: 0 11px;
    gap: 10px;
    border: 1px solid rgba(79, 212, 255, 0.26);
    border-radius: 10px;
    background:
        linear-gradient(
            180deg,
            rgba(8, 43, 85, 0.96),
            rgba(3, 20, 45, 0.98)
        );
}

.rtp-update-box span {
    color: #8ea6c1;
    font-size: 8px;
    font-weight: 800;
}

.rtp-update-box strong {
    color: #ffd450;
    font-size: 11px;
    font-variant-numeric: tabular-nums;
}

.rtp-search {
    width: 100%;
    height: 39px;
    margin-bottom: 11px;
    padding: 0 12px;
    border: 1px solid rgba(0, 164, 255, 0.30);
    border-radius: 10px;
    outline: 0;
    color: #ffffff;
    background: #041a38;
    font-size: 10px;
}

.rtp-search::placeholder {
    color: #69829f;
}

.rtp-provider-tabs {
    display: flex;
    overflow-x: auto;
    margin-bottom: 12px;
    padding-bottom: 3px;
    gap: 6px;
    scrollbar-width: none;
}

.rtp-provider-tabs::-webkit-scrollbar {
    display: none;
}

.rtp-provider-tab {
    flex: 0 0 auto;
    min-height: 31px;
    padding: 0 11px;
    border: 1px solid rgba(0, 164, 255, 0.30);
    border-radius: 999px;
    color: #8fa7c2;
    background: #05224a;
    font-size: 7px;
    font-weight: 1000;
    cursor: pointer;
}

.rtp-provider-tab.is-active {
    border-color: #ffe07a;
    color: #311900;
    background:
        linear-gradient(
            180deg,
            #ffe88c,
            #f1a817
        );
}

.rtp-provider-section {
    margin-bottom: 14px;
}

.rtp-provider-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    padding: 8px 9px;
    gap: 8px;
    border: 1px solid rgba(255, 201, 54, 0.28);
    border-radius: 11px;
    background:
        linear-gradient(
            180deg,
            #092750,
            #03152f
        );
}

.rtp-provider-logo {
    width: 39px;
    height: 39px;
    flex: 0 0 39px;
    object-fit: contain;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.05);
}

.rtp-provider-copy {
    min-width: 0;
}

.rtp-provider-copy strong {
    display: block;
    overflow: hidden;
    color: #ffffff;
    font-size: 11px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.rtp-provider-copy small {
    display: block;
    margin-top: 3px;
    color: #64ceff;
    font-size: 6px;
    font-weight: 1000;
    letter-spacing: 0.08em;
}

.rtp-provider-count {
    margin-left: auto;
    color: #ffd34f;
    font-size: 7px;
    font-weight: 1000;
}

.rtp-grid {
    display: grid;
    grid-template-columns:
        repeat(3, minmax(0, 1fr));
    gap: 7px;
}

.rtp-card {
    position: relative;
    display: grid;
    min-width: 0;
    overflow: hidden;
    border: 1px solid rgba(0, 157, 255, 0.27);
    border-radius: 11px;
    color: inherit;
    background:
        linear-gradient(
            180deg,
            #082750,
            #03132d
        );
    text-decoration: none;
    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.07),
        0 5px 12px rgba(0, 0, 0, 0.27);
}

.rtp-popular-badge {
    position: absolute;
    top: 6px;
    left: 6px;
    z-index: 2;
    display: inline-flex;
    min-height: 18px;
    align-items: center;
    justify-content: center;
    padding: 0 6px;
    border: 1px solid rgba(255, 229, 129, 0.78);
    border-radius: 999px;
    color: #301800;
    background: linear-gradient(180deg, #fff0a1, #f4b51e);
    font-size: 6px;
    font-weight: 1000;
    letter-spacing: 0.04em;
    box-shadow: 0 3px 9px rgba(0, 0, 0, 0.28);
}

.rtp-card-image {
    width: 100%;
    aspect-ratio: 1 / 1;
    object-fit: cover;
    background: #061a37;
}

.rtp-card-body {
    display: grid;
    padding: 7px;
    gap: 5px;
}

.rtp-card-title {
    display: -webkit-box;
    min-height: 24px;
    margin: 0;
    overflow: hidden;
    color: #ffffff;
    font-size: 8px;
    font-weight: 1000;
    line-height: 1.35;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}

.rtp-value-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 5px;
}

.rtp-value-row span {
    color: #7f96b1;
    font-size: 6px;
    font-weight: 900;
}

.rtp-value-row strong {
    color: #ffd451;
    font-size: 13px;
    font-weight: 1000;
    font-variant-numeric: tabular-nums;
}

.rtp-bar {
    height: 5px;
    overflow: hidden;
    border-radius: 999px;
    background: #011026;
}

.rtp-bar > i {
    display: block;
    height: 100%;
    border-radius: inherit;
    background:
        linear-gradient(
            90deg,
            #18b4ff,
            #52e39a,
            #ffd34f
        );
    box-shadow:
        0 0 7px rgba(79, 220, 155, 0.35);
}

.rtp-empty,
.rtp-error {
    padding: 18px 12px;
    border-radius: 12px;
    font-size: 9px;
    line-height: 1.6;
    text-align: center;
}

.rtp-empty {
    border: 1px dashed rgba(255, 200, 49, 0.32);
    color: #91a6bf;
    background: rgba(4, 19, 44, 0.74);
}

.rtp-error {
    margin-bottom: 10px;
    border: 1px solid rgba(255, 73, 73, 0.35);
    color: #ffd4d4;
    background: rgba(96, 10, 18, 0.45);
}

.rtp-disclaimer {
    margin-top: 14px;
    padding: 10px;
    border: 1px solid rgba(255, 203, 62, 0.22);
    border-radius: 10px;
    color: #849bb6;
    background: rgba(5, 22, 48, 0.74);
    font-size: 7px;
    line-height: 1.55;
    text-align: center;
}

@media (max-width: 390px) {
    .rtp-grid {
        grid-template-columns:
            repeat(3, minmax(0, 1fr));
        gap: 5px;
    }

    .rtp-card-body {
        padding: 6px;
    }

    .rtp-card-title {
        font-size: 7px;
    }

    .rtp-value-row strong {
        font-size: 11px;
    }
}

@media (max-width: 330px) {
    .rtp-grid {
        grid-template-columns:
            repeat(2, minmax(0, 1fr));
    }
}
</style>

<main class="rtp-page">
    <div class="rtp-shell">

        <header class="rtp-heading">
            <small>UPDATE OTOMATIS </small>
            <h1>RTP SLOT HARI INI</h1>
            <p>
                Pilih Provider dengan kapasitas persentase besar
            </p>
        </header>

        <input
            type="search"
            class="rtp-search"
            id="rtpSearch"
            placeholder="Cari provider atau nama game..."
            autocomplete="off"
        >

        <?php if ($rtpError !== ''): ?>
            <div class="rtp-error">
                Data RTP gagal dimuat. Periksa struktur tabel
                provider dan game.
            </div>
        <?php endif; ?>

        <?php if (!empty($rtpProviders)): ?>

            <div
                class="rtp-provider-tabs"
                aria-label="Filter provider"
            >
                <button
                    type="button"
                    class="rtp-provider-tab is-active"
                    data-provider-filter="all"
                >
                    SEMUA
                </button>

                <?php foreach ($rtpProviders as $provider): ?>
                    <button
                        type="button"
                        class="rtp-provider-tab"
                        data-provider-filter="<?= e($provider['key']); ?>"
                    >
                        <?= e($provider['provider_name']); ?>
                    </button>
                <?php endforeach; ?>
            </div>

            <div id="rtpProviderList">
                <?php foreach ($rtpProviders as $provider): ?>

                    <section
                        class="rtp-provider-section"
                        data-provider-key="<?= e($provider['key']); ?>"
                        data-provider-name="<?= e(strtolower($provider['provider_name'])); ?>"
                    >
                        <header class="rtp-provider-header">
                            <img
                                class="rtp-provider-logo"
                                src="<?= e($provider['provider_image']); ?>"
                                alt="<?= e($provider['provider_name']); ?>"
                                loading="lazy"
                                decoding="async"
                                onerror="this.src='assets/images/provider-default.png';"
                            >

                            <div class="rtp-provider-copy">
                                <strong>
                                    <?= e($provider['provider_name']); ?>
                                </strong>

                               
                            </div>

                            <span class="rtp-provider-count">
                                <?= count($provider['games']); ?> GAME
                            </span>
                        </header>

                        <div class="rtp-grid">
                            <?php foreach ($provider['games'] as $game): ?>
                                <a
                                    class="rtp-card"
                                    href="<?= e($game['play_url']); ?>"
                                    data-game-name="<?= e(strtolower($game['game_name'])); ?>"
                                >
                                    <?php if (!empty($game['is_popular'])): ?>
                                        <span class="rtp-popular-badge">
                                            POPULER
                                        </span>
                                    <?php endif; ?>

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

                                    <div class="rtp-card-body">
                                        <h2 class="rtp-card-title">
                                            <?= e($game['game_name']); ?>
                                        </h2>

                                        <div class="rtp-value-row">
                                            <span>RTP</span>
                                            <strong>
                                                <?= e($game['rtp']); ?>%
                                            </strong>
                                        </div>

                                        <div class="rtp-bar">
                                            <i
                                                style="width:<?= e($game['rtp']); ?>%"
                                            ></i>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </section>

                <?php endforeach; ?>
            </div>

            <div
                class="rtp-empty"
                id="rtpNoResult"
                hidden
            >
                Provider atau game tidak ditemukan.
            </div>

        <?php else: ?>

            <div class="rtp-empty">
                Belum ada provider atau game slot aktif.
                Pastikan provider dan game bertipe <strong>SL</strong>
                atau <strong>SLOT</strong>, serta status dan is_active
                bernilai <strong>1</strong>.
            </div>

        <?php endif; ?>

        <div class="rtp-disclaimer">
            Persentase pada halaman ini merupakan indikator tampilan
            yang berubah otomatis setiap 10 menit dan bukan RTP resmi
            yang diterbitkan provider.
        </div>

    </div>
</main>

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

    var countdown = document.getElementById('rtpCountdown');

    if (countdown) {
        var nextUpdate = parseInt(
            countdown.getAttribute('data-next-update'),
            10
        ) * 1000;

        function updateCountdown() {
            var remaining = nextUpdate - Date.now();

            if (remaining <= 0) {
                window.location.reload();
                return;
            }

            var totalSeconds = Math.ceil(
                remaining / 1000
            );

            var minutes = Math.floor(
                totalSeconds / 60
            );

            var seconds = totalSeconds % 60;

            countdown.textContent =
                String(minutes).padStart(2, '0') +
                ':' +
                String(seconds).padStart(2, '0');
        }

        updateCountdown();

        window.setInterval(
            updateCountdown,
            1000
        );
    }

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

    var sections = Array.prototype.slice.call(
        document.querySelectorAll(
            '.rtp-provider-section'
        )
    );

    var tabs = Array.prototype.slice.call(
        document.querySelectorAll(
            '.rtp-provider-tab'
        )
    );

    var noResult =
        document.getElementById('rtpNoResult');

    var activeProvider = 'all';

    function applyFilter() {
        var keyword = searchInput
            ? searchInput.value
                .trim()
                .toLowerCase()
            : '';

        var visibleSections = 0;

        sections.forEach(function (section) {
            var providerKey =
                section.getAttribute(
                    'data-provider-key'
                );

            var providerName =
                section.getAttribute(
                    'data-provider-name'
                ) || '';

            var providerAllowed =
                activeProvider === 'all' ||
                providerKey === activeProvider;

            var cards = Array.prototype.slice.call(
                section.querySelectorAll(
                    '.rtp-card'
                )
            );

            var visibleCards = 0;

            cards.forEach(function (card) {
                var gameName =
                    card.getAttribute(
                        'data-game-name'
                    ) || '';

                var keywordMatch =
                    keyword === '' ||
                    providerName.indexOf(keyword) !== -1 ||
                    gameName.indexOf(keyword) !== -1;

                var showCard =
                    providerAllowed &&
                    keywordMatch;

                card.hidden = !showCard;

                if (showCard) {
                    visibleCards++;
                }
            });

            section.hidden =
                !providerAllowed ||
                visibleCards === 0;

            if (!section.hidden) {
                visibleSections++;
            }
        });

        if (noResult) {
            noResult.hidden =
                visibleSections !== 0;
        }
    }

    tabs.forEach(function (tab) {
        tab.addEventListener(
            'click',
            function () {
                activeProvider =
                    tab.getAttribute(
                        'data-provider-filter'
                    ) || 'all';

                tabs.forEach(function (item) {
                    item.classList.remove(
                        'is-active'
                    );
                });

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

                applyFilter();
            }
        );
    });

    if (searchInput) {
        searchInput.addEventListener(
            'input',
            applyFilter
        );
    }
}());
</script>

<?php

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