<?php
include 'template/header.php';
?>

<?php if ($mobile): ?>
    <div style="margin-top: 50px;">
    <?php else: ?>
        <div style="margin-top: 170px;">
        <?php endif; ?>
        <?php if ($mobile): ?>
            <div>
                <img src="https://rajabotak.dataklmsad902.site/asset/images/banner-game-7.jpg?s=7f179090673f5332302799f134d11a4c"
                    style="width: 100%;">
            </div>
            <?php include "template/menu-outer.php" ?>
        <?php endif; ?>
        <div style="width: 95%; margin: 0 auto 20px auto;">
            <div
                style="font-family: Teko-SemiBold; text-align: center; font-size: 24px; color: transparent !important; -webkit-background-clip: text; background-image: radial-gradient(ellipse farthest-corner at right bottom, #FEDB37 0%, #FDB931 8%, #9f7928 30%, #8A6E2F 40%, transparent 80%), radial-gradient(ellipse farthest-corner at left top, #e99c05 0%, #f4ae00 8%, #f8bf33 25%, #f8ce19 62.5%, #ffdc02 100%); padding: 10px 0;">
                PASARAN
                <hr
                    style="background: linear-gradient(#000 0 0) padding-box, linear-gradient(to left, #FEDB37, #8A6E2F) border-box; border-top: 2px solid transparent; margin: 0 auto; width: 70px;">
            </div>
            <div style="margin: auto 0 auto auto; position: relative; width: 45%;">
                <i class="fa fa-search" aria-hidden="true"
                    style="position: absolute; top: 10px; left: 15px; height: 18px; width: 18px; margin: 0; color: transparent !important; -webkit-background-clip: text; background-image: radial-gradient(ellipse farthest-corner at right bottom, #FEDB37 0%, #FDB931 8%, #9f7928 30%, #8A6E2F 40%, transparent 80%), radial-gradient(ellipse farthest-corner at left top, #e99c05 0%, #f4ae00 8%, #f8bf33 25%, #f8ce19 62.5%, #ffdc02 100%);"></i>
                <input type="text" name="search" class="search" id="searchPasaran" placeholder="Cari Pasaran"
                    style="font-family: Poppins-Regular; font-size: 12px; width: 100%; background-color: transparent; color: #fff; border: 1px solid #FFD700; border-radius: 25px; padding: 6px 15px 6px 35px;">
            </div>
            <?php if ($mobile): ?>
                <ul style="list-style-type: none; padding: 0; margin-bottom: 0; display: flex; flex-wrap: wrap;">
                    <?php
                    $q = mysqli_query($koneksi, "SELECT * FROM tb_provider WHERE provider_type = 'TOGEL'");

                    while ($data = mysqli_fetch_assoc($q)):
                        $providerName = htmlspecialchars($data['provider_name']);
                        $providerImg = htmlspecialchars($data['provider_image']);
                        $slug = htmlspecialchars($data['slug']);
                        $code = $data['code'] ?? '';

                        if (empty($id)) {
                            $onclick = "alert('Silahkan login terlebih dahulu!'); window.location.href='login.php'";
                        } else {
                            $onclick = empty($code) ? "?s=" . urlencode($slug) : "play.php?game=" . urlencode($code) . "&provider=" . urlencode($slug);
                        }
                        ?>
                        <li onclick="<?= $onclick ?>" style="display: inline-block; width: 50%; padding: 0 5px;">
                            <img src="<?= $providerImg ?>" alt="<?= $providerName ?>"
                                onerror="this.src='https://via.placeholder.com/300x150/667eea/ffffff?text=<?= urlencode($providerName) ?>'"
                                style="width: 50%; margin-bottom: 6px;">
                        </li>
                    <?php endwhile; ?>
                </ul>
            <?php else: ?>
                <ul style="list-style-type: none; padding: 20px 0 0 0; margin: 0; display: flex; flex-wrap: wrap;">

                    <?php
                    $providers = mysqli_query($koneksi, "SELECT * FROM tb_provider WHERE provider_type = 'TOGEL'");

                    while ($data = mysqli_fetch_assoc($providers)):
                        $providerName = htmlspecialchars($data['provider_name']);
                        $providerImg = htmlspecialchars($data['provider_image']);
                        $slug = htmlspecialchars($data['slug']);
                        $status = (int) $data['status'];
                        $code = $data['code'] ?? '';

                        if (empty($id)) {
                            $onclick = "alert('Silahkan login terlebih dahulu!'); window.location.href='login.php'";
                        } else {
                            if ($status === 1 && !empty($code)) {
                                $onclick = "window.open('play.php?game=" . urlencode($code) . "&provider=" . urlencode($slug) . "', '_blank')";
                            } else {
                                $onclick = "alert('Provider ini sedang Maintenance!')";
                            }
                        }
                        ?>
                        <li onclick="<?= $onclick ?>"
                            style="display: inline-block; padding: 0 10px; width: 20%; margin-bottom: 20px; cursor: pointer;">
                            <img src="<?= $providerImg ?>" alt="<?= $providerName ?>" style="width: 100%; border-radius: 6px;">
                        </li>
                    <?php endwhile; ?>

                </ul>
            <?php endif; ?>

            <table width="100%" style="margin: 10px auto 0 auto; background-color: #201E21;">
                <tbody id="togelBody">
                    <tr>
                        <td style="color:#fff; padding:10px;">Loading...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script>
        async function loadTogel() {
            const tbody = document.getElementById('togelBody');
            tbody.innerHTML = `<tr><td style="color:#fff; padding:10px;">Loading...</td></tr>`;

            try {
                const res = await fetch('togel-scraper', { cache: 'no-store' });
                const json = await res.json();

                if (!json.ok) throw new Error(json.message || 'API error');

                tbody.innerHTML = (json.data || []).map(renderRow).join('') ||
                    `<tr><td style="color:#fff; padding:10px;">Tidak ada data</td></tr>`;

            } catch (e) {
                console.error(e);
                tbody.innerHTML = `<tr><td style="color:#fff; padding:10px;">Gagal ambil data</td></tr>`;
            }
        }

        function esc(s) {
            return String(s ?? '').replace(/[&<>"']/g, m =>
                ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[m])
            );
        }

        function renderRow(item) {
            const pasaran = esc(item.pasaran);
            const hari = esc(item.hari);
            const tanggal = esc(item.tanggal);
            const tutup = esc(item.tutup);
            const buka = esc(item.buka);

            const linkPasaran = esc(item.link_pasaran || '#');

            const linkAllea = "game=3724&provider=LK";
            const linkDetail = 'play.php?' + linkAllea;

            const digits = String(item.hasil || '').split('');
            const d1 = esc(digits[0] || '');
            const d2 = esc(digits[1] || '');
            const d3 = esc(digits[2] || '');
            const d4 = esc(digits[3] || '');

            return `
<tr class="lottery-list lottery-4"
  style="border-bottom: 1px solid rgba(136, 145, 174, .35); display: flex; margin: 2% 5%; padding-bottom: 2%;">
  <td style="width: 50%;">
    <div onclick="window.open('${linkPasaran}', '_blank')"
      style="color: transparent !important; -webkit-background-clip: text;
      background-image: radial-gradient(ellipse farthest-corner at right bottom, #FEDB37 0%, #FDB931 8%, #9f7928 30%, #8A6E2F 40%, transparent 80%),
      radial-gradient(ellipse farthest-corner at left top, #e99c05 0%, #f4ae00 8%, #f8bf33 25%, #f8ce19 62.5%, #ffdc02 100%);
      font-weight: 500; cursor: pointer;">
      ${pasaran}
    </div>
    <div style="font-weight: 500; margin-bottom: 10px; font-size: 13px;">
      ( Setiap Hari )
    </div>
    <div style="font-size: 12px; font-weight: 500; margin-bottom: 10px;">
      Tutup: ${tutup} | Buka: ${buka}
    </div>
    <div style="opacity: 0.65; font-size: 12px;">
      ${hari}<br>${tanggal}
    </div>
  </td>
  <td style="width: 50%; margin: auto 0 auto auto;">
    <table style="margin: 0 0 0 auto; font-weight: 500; text-align: center;">
      <tbody>
        <tr onclick="window.location='${linkDetail}'" style="cursor: pointer;">
          <td style="padding-right: 10px;">
            <div style="background: linear-gradient(#000 0 0) padding-box, linear-gradient(to left, #FEDB37, #8A6E2F) border-box;
              border: 1px solid transparent; color: #fff; width: 27px; line-height: 27px; border-radius: 6px;
              box-shadow: 1px .125rem .5rem rgba(0, 0, 0, .3);">${d1}</div>
          </td>
          <td style="padding-right: 10px;">
            <div style="background: linear-gradient(#000 0 0) padding-box, linear-gradient(to left, #FEDB37, #8A6E2F) border-box;
              border: 1px solid transparent; color: #fff; width: 27px; line-height: 27px; border-radius: 6px;
              box-shadow: 1px .125rem .5rem rgba(0, 0, 0, .3);">${d2}</div>
          </td>
          <td style="padding-right: 10px;">
            <div style="background: linear-gradient(#000 0 0) padding-box, linear-gradient(to left, #FEDB37, #8A6E2F) border-box;
              border: 1px solid transparent; color: #fff; width: 27px; line-height: 27px; border-radius: 6px;
              box-shadow: 1px .125rem .5rem rgba(0, 0, 0, .3);">${d3}</div>
          </td>
          <td>
            <div style="background: linear-gradient(#000 0 0) padding-box, linear-gradient(to left, #FEDB37, #8A6E2F) border-box;
              border: 1px solid transparent; color: #fff; width: 27px; line-height: 27px; border-radius: 6px;
              box-shadow: 1px .125rem .5rem rgba(0, 0, 0, .3);">${d4}</div>
          </td>
        </tr>
      </tbody>
    </table>
  </td>
</tr>`;
        }

        document.addEventListener('DOMContentLoaded', loadTogel);
        setInterval(loadTogel, 5 * 60 * 1000);

        const searchInput = document.getElementById('searchPasaran');

        searchInput.addEventListener('keyup', function () {
            const keyword = this.value.toLowerCase().trim();
            const tbody = document.getElementById('togelBody');

            document.querySelectorAll('.lottery-list').forEach(row => {
                const pasaranEl = row.querySelector('td div');
                if (!pasaranEl) return;

                const pasaranText = pasaranEl.textContent.toLowerCase();

                row.style.display = pasaranText.includes(keyword) ? 'flex' : 'none';
                tbody.innerHTML = `<tr><td style="color:#fff; padding:10px;">Pasaran untuk ${keyword} tidak ditemukan!</td></tr>`
            });
        });
    </script>

    <?php include 'template/footer.php' ?>