<?php
$providerCode = isset($_GET['provider']) ? $_GET['provider'] : 'af';
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.php');
$sid = session_id();

// Ambil data SEO
$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();

// Cek Status Maintenance
$sql_m = "SELECT status FROM maintenance WHERE id = 1";
$result_m = $conn->query($sql_m);
if ($result_m->num_rows > 0) {
    $row_m = $result_m->fetch_assoc();
    if ($row_m["status"] == 1) {
        echo "<script>alert('Halaman sedang dalam pemeliharaan. Kembali ke halaman sebelumnya.'); window.history.back();</script>";
        exit();
    }
}

include "../m/header.php";

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

// Cek apakah ada game untuk setiap provider
$casinos = [];
if ($providerResult && mysqli_num_rows($providerResult) > 0) {
    while ($provider = mysqli_fetch_assoc($providerResult)) {
        // Cek apakah provider punya game di tb_gamelist dengan category 'live'
        $gameCountQuery = "SELECT COUNT(*) as count FROM tb_gamelist 
                          WHERE provider_code = '" . mysqli_real_escape_string($conn, $provider['code']) . "' 
                          AND (game_category = 'live' OR game_category = 'lc') AND status = 1";
        $gameCountResult = mysqli_query($conn, $gameCountQuery);
        $gameCount = 0;
        if ($gameCountResult) {
            $gameCountRow = mysqli_fetch_assoc($gameCountResult);
            $gameCount = (int)$gameCountRow['count'];
        }
        
        // Tentukan status provider
        $providerStatus = ($provider['status'] == 1 && $gameCount > 0) ? 'active' : 'maintenance';
        
        // Tentukan URL
        if ($providerStatus == 'active') {
            $targetUrl = site_url('m/casino/game/?provider=' . urlencode($provider['code']));
        } else {
            $targetUrl = '#';
        }
        
        // Tentukan tag (hot untuk provider populer)
        $tag = 'none';
        $popularProviders = ['PR', 'PRAGMATICLIVE', 'EVOLUTION', 'EZUGI', 'DG'];
        if (in_array($provider['code'], $popularProviders)) {
            $tag = 'hot';
        }
        
        $casinos[] = [
            'name' => $provider['name'],
            'provider' => $provider['code'],
            'img' => $provider['image'] ? $provider['image'] : '',
            'url' => $targetUrl,
            'type' => $providerStatus,
            'tag' => $tag,
            'game_count' => $gameCount
        ];
    }
}
?>

<div class="container pt-1 games-category">
    <h2 class="title" style="text-transform: uppercase;">casino</h2>
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12 image-grid">
            
            <?php if (!empty($casinos)): ?>
                <?php foreach ($casinos as $casino): ?>
                    <div class="col-xs-4 col-sm-3 col-md-2 box">
                        <div class="game-wrapper">
                            
                            <?php if ($casino['tag'] == 'live'): ?>
                                <div style="position:absolute;right:0;top:0;z-index: 9;">
                                    <img src="https://files.sitestatic.net/images/live_icon.gif" ref="live" height="25px">
                                </div>
                            <?php elseif ($casino['tag'] == 'hot'): ?>
                                <div class="hot-tag" style="z-index: 3;"></div>
                            <?php endif; ?>

                            <?php if ($casino['type'] == 'maintenance'): ?>
                                <div class="game maintenance-alert">
                                    <?php if (!empty($casino['img'])): ?>
                                        <img class="img-fluid lazy" alt="<?php echo htmlspecialchars($casino['name']); ?>" data-src="<?php echo htmlspecialchars($casino['img']); ?>" src="" />
                                    <?php else: ?>
                                        <img class="img-fluid lazy" alt="<?php echo htmlspecialchars($casino['name']); ?>" data-src="https://files.sitestatic.net/GameImage/CasinoProviders/mobile/normal/casino_default.jpg" src="" />
                                    <?php endif; ?>
                                    <div class="loader-b"></div>
                                </div>
                            <?php else: ?>
                                <a href="<?php echo htmlspecialchars($casino['url']); ?>" rel="opener" class="game">
                                    <?php if (!empty($casino['img'])): ?>
                                        <img class="img-fluid lazy" alt="<?php echo htmlspecialchars($casino['name']); ?>" data-src="<?php echo htmlspecialchars($casino['img']); ?>" src="" />
                                    <?php else: ?>
                                        <!-- Fallback image jika tidak ada gambar di database -->
                                        <img class="img-fluid lazy" alt="<?php echo htmlspecialchars($casino['name']); ?>" data-src="https://files.sitestatic.net/GameImage/CasinoProviders/mobile/normal/casino_default.jpg" 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 casino yang tersedia saat ini.</p>
                    </div>
                </div>
            <?php endif; ?>

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

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