<?php include './inc/head.php' ?>
<?php include './inc/header.php' ?>
<?php include './inc/slider.php' ?>
</div>
<?php
$host = 'localhost';
$dbname = 'blacrhdy_bet1';
$user = 'blacrhdy_bet1';
$pass = 'blacrhdy_bet1';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Veritabanı bağlantı hatası: ' . $e->getMessage();
    exit;
}

function searchGames($searchTerm) {
    global $pdo;
    $sql = "SELECT game_id, game_name, cover FROM games WHERE game_name LIKE :searchTerm";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':searchTerm', '%' . $searchTerm . '%', PDO::PARAM_STR);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getGameCount() {
    global $pdo;
    $sql = "SELECT COUNT(*) as total_games FROM games";
    $stmt = $pdo->query($sql);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result['total_games'];
}

$total_games = getGameCount();

// Game type'ları tanımla - Öncelikli oyunlar ilk sırada, sonra alfabetik
$gameTypes = [
    // Öncelikli oyunlar
    'roulette' => 'Rulet',
    'baccarat' => 'Bakara', 
    'blackjack' => 'Blackjack',
    
    // Alfabetik sıralama
    'andarbahar' => 'Andar Bahar',
    'arcade' => 'Arcade',
    'shooting' => 'Atış Oyunları',
    'bingo' => 'Bingo',
    'crashgame' => 'Crash Oyunları',
    'other' => 'Diğer',
    'dragontiger' => 'Dragon Tiger',
    'interactivegame' => 'Etkileşimli Oyunlar',
    'instantgame' => 'Anında Oyunlar',
    'cards' => 'Kart Oyunları',
    'scratchcards' => 'Kazı Kazan',
    'keno' => 'Keno',
    'lobby' => 'Lobi',
    'tablegames' => 'Masa Oyunları',
    'gameshow' => 'Oyun Şovları',
    'lottery' => 'Piyango',
    'plinko' => 'Plinko',
    'poker' => 'Poker',
    'virtual' => 'Sanal Oyunlar',
    'sicbo' => 'Sic Bo',
    'dice' => 'Zar Oyunları'
];
?>

<style>
    .iframe-popup {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        height: 80%;
        background-color: white;
        border-radius: 10px;
        border: 1px solid #ccc;
        z-index: 9999;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .iframe-popup iframe {
        width: 100%;
        height: 100%;
        border: none;
    }

    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        z-index: 9998;
    }

    .flex-container {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    /* Game Type Tabs Styling - Site Theme Uyumlu */
    .game-type-tabs {
        display: flex;
        flex-wrap: nowrap;
        gap: 8px;
        padding: 12px 15px;
        margin-bottom: 20px;
        overflow-x: auto;
        overflow-y: hidden;
        white-space: nowrap;
        background: #0b1020;
        border-radius: 8px;
        border: 2px solid #D4AF37;
        scrollbar-width: thin;
        scrollbar-color: #D4AF37 #0b1020;
    }

    .game-type-tabs::-webkit-scrollbar {
        height: 6px;
    }

    .game-type-tabs::-webkit-scrollbar-track {
        background: #0b1020;
        border-radius: 3px;
    }

    .game-type-tabs::-webkit-scrollbar-thumb {
        background: #D4AF37;
        border-radius: 3px;
    }

    .game-type-tabs::-webkit-scrollbar-thumb:hover {
        background: #E6C547;
    }

    .game-type-tab {
        position: relative;
        padding: 8px 14px;
        background: #11162a;
        color: #eaeef7;
        border: 1px solid rgba(212, 175, 55, 0.3);
        border-radius: 15px;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 12px;
        font-weight: 500;
        white-space: nowrap;
        min-width: fit-content;
        flex-shrink: 0;
        text-transform: capitalize;
        letter-spacing: 0.3px;
    }

    .game-type-tab:hover {
        background: #D4AF37;
        color: #0b1020;
        border-color: #D4AF37;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(212, 175, 55, 0.3);
    }

    .game-type-tab.active {
        background: #D4AF37;
        color: #0b1020;
        border-color: #D4AF37;
        box-shadow: 0 2px 8px rgba(212, 175, 55, 0.4);
        font-weight: 600;
    }

    .game-type-tab .count {
        background: rgba(234, 238, 247, 0.2);
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 10px;
        margin-left: 6px;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .game-type-tab:hover .count,
    .game-type-tab.active .count {
        background: rgba(11, 16, 32, 0.3);
        color: #0b1020;
    }

    /* Priority tabs special styling - Site teması ile uyumlu */
    .game-type-tab[data-type="roulette"],
    .game-type-tab[data-type="baccarat"],
    .game-type-tab[data-type="blackjack"] {
        border: 2px solid #D4AF37;
        font-weight: 600;
        background: #0e1426;
    }

    .game-type-tab[data-type="roulette"]:hover,
    .game-type-tab[data-type="baccarat"]:hover,
    .game-type-tab[data-type="blackjack"]:hover {
        background: #D4AF37;
        color: #0b1020;
        box-shadow: 0 3px 12px rgba(212, 175, 55, 0.4);
    }

@media (max-width: 768px) {
    .game-type-tabs {
        padding: 10px 0;
        gap: 6px;
    }
    
    .game-type-tab {
        padding: 8px 12px;
        font-size: 13px;
    }
    
    .iframe-popup {
        width: 95%;
        height: 90%;
        top: 5%;
        left: 2.5%;
        transform: none;
    }
    
    .livecasino-search {
        margin-top: 0;
        padding-top: 0;
    }
    
    .livecasino-search input[type="text"] {
        max-width: 100%;
        font-size: 14px;
    }
    
    /* Header'ın tam ekrana oturması için */
    body {
        padding-top: 60px !important;
    }
    
    .headBar {
        position: fixed !important;
        top: 0 !important;
        left: 0 !important;
        right: 0 !important;
        width: 100% !important;
        z-index: 1000 !important;
    }
}

@media (max-width: 575px) {
    .game-type-tab {
        padding: 6px 10px;
        font-size: 12px;
    }
    
    .iframe-popup {
        width: 98%;
        height: 95%;
        top: 2.5%;
        left: 1%;
    }
    
    .livecasino-search {
        padding: 5px 0;
    }
    
    .livecasino-search input[type="text"] {
        padding: 6px 10px;
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .game-type-tab {
        padding: 5px 8px;
        font-size: 11px;
    }
    
    .iframe-popup {
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        border-radius: 0;
    }
    
    .livecasino-search input[type="text"] {
        padding: 5px 8px;
        font-size: 12px;
    }
}

    .livecasino-search {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        padding: 10px 0;
    }

    .livecasino-search input[type="text"] {
        width: 100%;
        max-width: 380px;
        padding: 8px 12px;
        border-radius: 8px;
        border: 1px solid #D4AF37;
        background: #11162a;
        color: #eaeef7;
        outline: none;
        transition: all 0.3s ease;
    }

    .livecasino-search input[type="text"]:focus {
        border-color: #D4AF37;
        box-shadow: 0 0 0 2px rgba(212, 175, 55, 0.2);
        background: #0e1426;
    }

    .livecasino-search input::placeholder {
        color: #b8c1d9;
    }

    /* Minimal provider filter - Site teması ile uyumlu */
    .provider-filter {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 6px 0 12px 0;
    }
    .provider-filter label {
        font-size: 12px;
        color: #b8c1d9;
    }
    #providerSelect {
        max-width: 220px;
        padding: 6px 8px;
        border-radius: 6px;
        border: 1px solid #D4AF37;
        background: #11162a;
        color: #eaeef7;
        outline: none;
        font-size: 12px;
        height: 30px;
        transition: all 0.3s ease;
    }

    #providerSelect:focus {
        border-color: #D4AF37;
        box-shadow: 0 0 0 2px rgba(212, 175, 55, 0.2);
        background: #0e1426;
    }

    #providerSelect:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        background: #0e1426;
    }

    .loading-spinner {
        display: none;
        text-align: center;
        padding: 40px;
        color: #eaeef7;
    }

    .loading-spinner.show {
        display: block;
    }

    .no-games-message {
        display: none;
        text-align: center;
        padding: 40px;
        color: #b8c1d9;
        font-size: 16px;
    }

    .no-games-message.show {
        display: block;
    }
</style>

<script>
    // Oyunları yeni sekmede aç (sayfa içinde sayfa olmasını engelle)
    function openIframe(url) {
        try {
            window.open(url, '_blank');
        } catch (e) {
            console.error('Yeni sekme açılamadı:', e);
        }
    }

    function closeIframe() {
        // Artık iframe popup kullanılmıyor; fonksiyon yedek olarak bırakıldı
        const iframe = document.getElementById('gameIframe');
        if (iframe) iframe.src = '';
        const iframePopup = document.getElementById('iframePopup');
        const overlay = document.getElementById('overlay');
        if (iframePopup) iframePopup.style.display = 'none';
        if (overlay) overlay.style.display = 'none';
    }
</script>

<script>
// Canlı Casino global arama
(function(){
    let searchTimeout;
    
    function globalSearchGames(term){
        // Önceki timeout'u temizle
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }
        
        const container = document.getElementById('gamesContainer');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const noGamesMessage = document.getElementById('noGamesMessage');
        
        // Eğer arama terimi boşsa, mevcut kategoriyi yeniden yükle
        if (!term || term.trim() === '') {
            const activeTab = document.querySelector('.game-type-tab.active');
            const currentType = window.currentGameType || (activeTab ? activeTab.getAttribute('data-type') : 'roulette');
            if (activeTab) {
                loadGamesByType(currentType, activeTab);
            }
            return;
        }
        
        // Debounce: 300ms bekle
        searchTimeout = setTimeout(() => {
            loadingSpinner.classList.add('show');
            noGamesMessage.classList.remove('show');
            container.innerHTML = '';
            
            // Global arama yap
            fetch(`./games/livecasino/search_all_games.php?search=${encodeURIComponent(term.trim())}`)
                .then(response => response.json())
                .then(data => {
                    loadingSpinner.classList.remove('show');
                    
                    if (data.success) {
                        container.innerHTML = data.html;
                        // Demo butonlarını enjekte et
                        attachDemoButtonsGlobal();
                        
                        // Tüm sekmelerin active durumunu kaldır (arama modunda)
                        document.querySelectorAll('.game-type-tab').forEach(tab => {
                            tab.classList.remove('active');
                        });
                        
                        // Provider select'i devre dışı bırak
                        const providerSelect = document.getElementById('providerSelect');
                        if (providerSelect) {
                            providerSelect.disabled = true;
                            providerSelect.value = 'all';
                        }
                        
                    } else {
                        noGamesMessage.classList.add('show');
                        const noGamesDiv = document.getElementById('noGamesMessage');
                        if (noGamesDiv) {
                            noGamesDiv.innerHTML = `<div>Arama sonucu bulunamadı: "${term}"</div>`;
                        }
                    }
                })
                .catch(error => {
                    console.error('Arama hatası:', error);
                    loadingSpinner.classList.remove('show');
                    noGamesMessage.classList.add('show');
                });
        }, 300);
    }

    // Fonksiyonu globalde kullanılabilir yap
    window.livecasinoFilterGames = globalSearchGames;

    // Game type değişimi sonrası filtre loadGamesByType içinde uygulanacaktır.
})();
</script>

<div class="iframe-popup" id="iframePopup">
    <button onclick="closeIframe()" style="position: absolute; top: 10px; right: 10px;">Kapat</button>
    <iframe id="gameIframe" src=""></iframe>
</div>

<div class="overlay" id="overlay" onclick="closeIframe()"></div>

<div class="livecasino-search">
    <input type="text" id="livecasinoSearchInput" placeholder="Canlı Casino oyunlarında ara..." oninput="window.livecasinoFilterGames(this.value)" onfocus="window.livecasinoFilterGames(this.value)">
</div>

<!-- Game Type Tabs -->
<div class="game-type-tabs" id="gameTypeTabs">
    <?php foreach ($gameTypes as $type => $label): ?>
        <div class="game-type-tab" data-type="<?= $type ?>" onclick="loadGamesByType('<?= $type ?>', this)">
            <?= $label ?>
            <span class="count" id="count-<?= $type ?>">0</span>
        </div>
    <?php endforeach; ?>
</div>

<!-- Minimal Provider Filter -->
<div class="provider-filter">
    <label for="providerSelect">Sağlayıcı:</label>
    <select id="providerSelect" onchange="window.onProviderChange(this.value)" disabled>
        <option value="all">Tümü</option>
    </select>
    
    <small id="providerInfo" style="color:#bfbfbf; display:none;">Yükleniyor...</small>
</div>

<div class="loading-spinner" id="loadingSpinner">
    <div>Oyunlar yükleniyor...</div>
</div>

<div class="no-games-message" id="noGamesMessage">
    <div>Bu kategoride henüz oyun bulunmuyor.</div>
</div>

<div id="gamesContainer">
    <!-- Oyunlar buraya yüklenecek -->
</div>

<script>
function attachDemoButtonsGlobal() {
    const container = document.getElementById('gamesContainer');
    const scope = container || document;
    const items = scope.querySelectorAll('.game-item');
    items.forEach(item => {
        if (item.querySelector('.btn-demo')) return; // zaten eklenmişse tekrar ekleme
        const gameId = (function(){
            const link = item.querySelector('a[href*="/start/game.php?gameid="]');
            if (link) {
                try {
                    const url = new URL(link.getAttribute('href'), window.location.origin);
                    const id = url.searchParams.get('gameid');
                    if (id) return id;
                } catch(e){}
            }
            const clickable = item.querySelector('[onclick*="/start/game.php?gameid="]') || item;
            if (clickable && clickable.hasAttribute('onclick')) {
                const text = clickable.getAttribute('onclick');
                const m = text.match(/game\.php\?gameid=(\d+)/);
                if (m) return m[1];
            }
            return null;
        })();
        if (!gameId) return;
        let actions = item.querySelector('.game-actions');
        if (!actions) {
            actions = document.createElement('div');
            actions.className = 'game-actions';
            // Global CSS handles layout for .game-actions; avoid inline overrides
            actions.style.cssText = '';
            const img = item.querySelector('img');
            if (img && img.parentNode === item) {
                img.insertAdjacentElement('afterend', actions);
            } else {
                item.appendChild(actions);
            }
        }
        const btnReal = document.createElement('button');
        btnReal.className = 'btn-real';
        btnReal.textContent = 'Oyna';
        // Rely on global CSS for size, colors and layout
        btnReal.style.cssText = '';
        btnReal.addEventListener('click', () => window.open(`/start/game.php?gameid=${gameId}`, '_blank'));
        const btnDemo = document.createElement('button');
        btnDemo.className = 'btn-demo';
        btnDemo.textContent = 'Demo';
        btnDemo.style.cssText = '';
        btnDemo.addEventListener('click', () => window.open(`/start/game.php?gameid=${gameId}&demo=1`, '_blank'));
        actions.appendChild(btnReal);
        actions.appendChild(btnDemo);
    });
}

function observeAndInjectDemo() {
    const container = document.getElementById('gamesContainer');
    if (!container) return;
    attachDemoButtonsGlobal();
    const observer = new MutationObserver(() => {
        attachDemoButtonsGlobal();
    });
    observer.observe(container, { childList: true, subtree: true });
}

// Game type'a göre oyunları yükle
function loadGamesByType(gameType, element) {
    window.currentGameType = gameType;
    
    // Arama modundan çık - provider select'i etkinleştir ve arama inputunu temizle
    const providerSelect = document.getElementById('providerSelect');
    const searchInput = document.querySelector('#livecasino-search input');
    
    if (providerSelect) {
        providerSelect.disabled = false;
    }
    
    if (searchInput) {
        searchInput.value = '';
    }
    
    // Loading göster
    const loadingSpinner = document.getElementById('loadingSpinner');
    const noGamesMessage = document.getElementById('noGamesMessage');
    const container = document.getElementById('gamesContainer');
    const providerVal = providerSelect && !providerSelect.disabled ? providerSelect.value : 'all';
    
    loadingSpinner.classList.add('show');
    noGamesMessage.classList.remove('show');
    container.innerHTML = '';

    // AJAX ile oyunları getir
    {
        let url = `./games/livecasino/load_by_type.php?type=${encodeURIComponent(gameType)}`;
        if (providerVal && providerVal !== 'all') {
            url += `&provider_game=${encodeURIComponent(providerVal)}`;
        }
        fetch(url)
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.text();
        })
        .then(data => {
            loadingSpinner.classList.remove('show');
            
            if (data.trim() === '' || data.includes('Oyun bulunamadı')) {
                noGamesMessage.classList.add('show');
            } else {
                container.innerHTML = data;
            }

            // Seçili sekmeyi güncelle
            updateActiveGameType(element);

            // Provider listesini güncelle
            populateProviders(gameType);

            // Mevcut arama terimine göre filtre uygula
            const input = document.getElementById('livecasinoSearchInput');
            if (input) {
                const q = input.value.trim().toLowerCase();
                const grid = document.querySelector('#gamesContainer .game-grid');
                if (grid) {
                    grid.querySelectorAll('.game-item').forEach(item => {
                        const nameEl = item.querySelector('p');
                        const name = nameEl ? nameEl.textContent.toLowerCase() : '';
                        item.style.display = (!q || name.includes(q)) ? '' : 'none';
                    });
                }
            }

            // Demo butonlarını enjekte et
            attachDemoButtonsGlobal();
        })
        .catch(error => {
            console.error('Error loading the games:', error);
            loadingSpinner.classList.remove('show');
            noGamesMessage.classList.add('show');
        });
    }
}

function updateActiveGameType(selectedElement) {
    const tabs = document.querySelectorAll('.game-type-tab');
    
    // Tüm sekmelerdeki "active" sınıfını kaldır
    tabs.forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Seçilen sekmeye "active" sınıfını ekle
    if (selectedElement) {
        selectedElement.classList.add('active');
    }
}

// Sayfa yüklendiğinde oyun sayılarını getir ve ilk sekmeyi aktif et
document.addEventListener('DOMContentLoaded', function() {
    observeAndInjectDemo();
    
    // Oyun sayılarını getir
    fetch('./games/livecasino/get_counts.php')
        .then(response => response.json())
        .then(counts => {
            Object.keys(counts).forEach(type => {
                const countElement = document.getElementById(`count-${type}`);
                if (countElement) {
                    countElement.textContent = counts[type] || 0;
                }
            });
        })
        .catch(error => console.error('Error loading game counts:', error));
    
    // İlk sekmeyi aktif et (roulette)
    const firstTab = document.querySelector('.game-type-tab[data-type="roulette"]');
    if (firstTab) {
        loadGamesByType('roulette', firstTab);
    }
});

// Provider listesini getir ve select'i doldur
function populateProviders(gameType) {
    const select = document.getElementById('providerSelect');
    const info = document.getElementById('providerInfo');
    if (!select) return;
    if (info) info.style.display = 'inline';
    select.disabled = true;
    select.innerHTML = `<option value="all">Tümü</option>`;
    fetch(`./games/livecasino/get_providers.php?type=${encodeURIComponent(gameType)}`)
        .then(res => res.json())
        .then(list => {
            if (Array.isArray(list)) {
                list.forEach(p => {
                    const opt = document.createElement('option');
                    opt.value = p.provider_game;
                    opt.textContent = `${p.provider_game} (${p.count})`;
                    select.appendChild(opt);
                });
                select.disabled = false;
            }
        })
        .catch(err => console.error('Provider listesi yüklenemedi:', err))
        .finally(() => { if (info) info.style.display = 'none'; });
}

// Provider seçimi değiştiğinde oyunları yeniden yükle
window.onProviderChange = function(val) {
    // Eğer arama modundaysak (provider disabled), işlem yapma
    const providerSelect = document.getElementById('providerSelect');
    if (providerSelect && providerSelect.disabled) {
        return;
    }
    
    const activeTab = document.querySelector('.game-type-tab.active');
    const type = window.currentGameType || (activeTab ? activeTab.getAttribute('data-type') : 'roulette');
    if (activeTab) {
        loadGamesByType(type, activeTab);
    } else {
        const firstTab = document.querySelector('.game-type-tab[data-type="roulette"]');
        if (firstTab) loadGamesByType('roulette', firstTab);
    }
};
</script>

<style id="livecasino-grid-override">
#gamesContainer .game-grid {
    display: grid !important;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)) !important;
    grid-gap: 10px !important;
    margin: 10px !important;
}
#gamesContainer .game-item p {
    font-size: 12px !important;
    margin-top: 6px !important;
}
#gamesContainer .game-item img {
    border-radius: 6px !important;
}
</style>

</body>
</html>
