<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.php');

$sid = session_id();
$sql_0 = mysqli_query($conn, "SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error($conn));
$s0 = mysqli_fetch_array($sql_0);

if (!function_exists('get_active_base_url')) {
    include(__DIR__ . '/../config/url_helper.php');
}
$urlweb = get_active_base_url();
$pengguna = $s0['user'];
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d');

// Statistik & Popup Logic
mysqli_query($conn, "INSERT INTO `tb_stat` (`ip`, `date`, `hits`, `page`, `user`) VALUES ('$ip', '$date', 1, 'Beranda', '$pengguna')");

$sql_banner = mysqli_query($conn, "SELECT * FROM `tb_banner` WHERE cuid = 1");
$ssb = mysqli_fetch_array($sql_banner);
$status = $ssb['status'];
$lihat = 'false';

if ($status == true) {
    $cekPopup = mysqli_query($conn, "SELECT * FROM `tb_popup` WHERE ip = '$ip'");
    if (mysqli_num_rows($cekPopup) == 0) {
        mysqli_query($conn, "INSERT INTO `tb_popup` (`ip`, `date`, `status`) VALUES ('$ip', '$date', 0)");
        $lihat = $status;
    } else {
        $cp = mysqli_fetch_array($cekPopup);
        $lihat = ($cp['status'] == 0) ? $status : 'false';
    }
} else {
    $lihat = $status;
}

include "header.php";

$providerQuery = "SELECT * FROM tb_wprovider 
                  WHERE type = 'slot' AND status = 1 
                  ORDER BY COALESCE(sort_order, 0) ASC, cuid ASC";
$providerResult = mysqli_query($conn, $providerQuery);

$providers = [];
if ($providerResult && mysqli_num_rows($providerResult) > 0) {
    while ($provider = mysqli_fetch_assoc($providerResult)) {
        $providerCode = $provider['code'];
        $gameCount = 0;
        
        // Cek jumlah game untuk validasi (Opsional: bisa dihilangkan jika performa berat)
        $gameCountQuery = "SELECT COUNT(*) as count FROM tb_gamelist 
                          WHERE provider_code = '" . mysqli_real_escape_string($conn, $providerCode) . "' 
                          AND game_category = 'slot' AND status = 1";
        $gameCountResult = mysqli_query($conn, $gameCountQuery);
        if ($gameCountResult) {
            $gameCountRow = mysqli_fetch_assoc($gameCountResult);
            $gameCount = (int)$gameCountRow['count'];
        }
        
        $providers[] = [
            'name' => $provider['name'],
            'provider' => $provider['code'],
            'img' => $provider['image'] ? $provider['image'] : '',
            'status' => $provider['status'] == 1 ? 'active' : 'maintenance',
            'game_count' => $gameCount
        ];
    }
}

// Notification System
if (!empty($_GET['notif']) && $_GET['notif'] == 1) {
    echo "
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                Swal.fire({
                    icon: 'info',
                    title: 'Notification',
                    html: '<strong>Akun Anda Sedang Dalam Masa Promosi Silahkan Melakukan Deposit Terlebih Dahulu</strong>',
                });
            });
        </script>
    ";
}
?>

<style>
    /* CSS Tambahan agar video dan gambar konsisten */
    .game-wrapper .game {
        display: block;
        position: relative;
        overflow: hidden;
        border-radius: 10px;
        background: #222;
        aspect-ratio: 1 / 1; /* Membuat kotak sempurna */
    }
    .game-wrapper img, .game-wrapper video {
        width: 100%;
        height: 100%;
        object-fit: cover; /* Agar konten memenuhi kotak tanpa distorsi */
        display: block;
    }
    .maintenance-overlay {
        position: absolute;
        top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-weight: bold;
        text-transform: uppercase;
        font-size: 10px;
    }
</style>

<div class="container pt-1 games-category">
    <h2 class="title">SLOTS</h2>
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12 image-grid">
            
            <?php if (!empty($providers)): ?>
                <?php foreach ($providers as $provider): ?>
                    <div class="col-xs-4 col-sm-3 col-md-2 box">
                        <div class="game-wrapper">
                            
                            <?php 
                            $targetUrl = site_url("m/slots/game/?provider=" . urlencode($provider['provider']));
                            $isMaintenance = ($provider['status'] == 'maintenance');
                            $mediaUrl = $provider['img'];
                            
                            // Default Fallback
                            if (empty($mediaUrl)) {
                                $mediaUrl = "https://files.sitestatic.net/GameImage/SlotsProviders/mobile/normal/slot_default.jpg";
                            }

                            // Cek Ekstensi File
                            $ext = strtolower(pathinfo($mediaUrl, PATHINFO_EXTENSION));
                            $isVideo = in_array($ext, ['mp4', 'webm', 'ogg']);
                            ?>

                            <?php if ($isMaintenance): ?>
                                <div class="game">
                                    <?php if ($isVideo): ?>
                                        <video autoplay loop muted playsinline>
                                            <source src="<?= htmlspecialchars($mediaUrl) ?>" type="video/mp4">
                                        </video>
                                    <?php else: ?>
                                        <img class="img-fluid lazy" alt="<?= htmlspecialchars($provider['name']) ?>" data-src="<?= htmlspecialchars($mediaUrl) ?>" src="" />
                                    <?php endif; ?>
                                    <div class="maintenance-overlay">Maintenance</div>
                                </div>
                            <?php else: ?>
                                <a href="<?= $targetUrl ?>" rel="opener" class="game">
                                    <?php if ($isVideo): ?>
                                        <video autoplay loop muted playsinline poster="https://files.sitestatic.net/GameImage/SlotsProviders/mobile/normal/slot_default.jpg">
                                            <source src="<?= htmlspecialchars($mediaUrl) ?>" type="video/mp4">
                                        </video>
                                    <?php else: ?>
                                        <img class="img-fluid lazy" alt="<?= htmlspecialchars($provider['name']) ?>" data-src="<?= htmlspecialchars($mediaUrl) ?>" src="" />
                                    <?php endif; ?>
                                    <div class="loader-b"></div>
                                </a>
                            <?php endif; ?>

                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-xs-12">
                    <div class="alert alert-info text-center">
                        <p>Tidak ada provider slot yang tersedia saat ini.</p>
                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>
</div>

<?php include "footer.php"; ?>