<?php
session_start(); // Oturum başlat

// Kullanıcının giriş yapıp yapmadığını kontrol et
$isLoggedIn = isset($_SESSION['loggedin']) && $_SESSION['loggedin'];

// Eğer giriş yapılmışsa, kullanıcı adını al
$userUsername = $isLoggedIn ? $_SESSION['username'] : '';

// Veritabanı bağlantısı (MySQLi örneği)
$servername = "localhost";
$username2 = "blacrhdy_bet1";
$password2 = "blacrhdy_bet1";
$dbname = "blacrhdy_bet1";

$conn = new mysqli($servername, $username2, $password2, $dbname);

// Bağlantı kontrolü
if ($conn->connect_error) {
    die("Bağlantı hatası: " . $conn->connect_error);
}

// Eğer kullanıcı oturum açmamışsa, hata mesajı döndürebiliriz
if (empty($userUsername)) {
    echo "Lütfen giriş yapınız.";
    exit;
}

// Aktif kullanıcının bakiyesini çekmek için SQL sorgusu
$sql = "SELECT ana_bakiye FROM kullanicilar WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $userUsername); // "s" parametre tipi, burada kullanici_adi bir string'dir
$stmt->execute();
$stmt->bind_result($userBalance);
$stmt->fetch();

// Eğer bakiye bulunamazsa, hata mesajı
if ($userBalance === null) {
    echo "Kullanıcı bakiyesi bulunamadı.";
    exit;
}

// Oturumdaki bakiyeyi PHP'ye aktar
$_SESSION['ana_bakiye'] = $userBalance;

// Veritabanı bağlantısını kapat
$stmt->close();
$conn->close();
?>


<html lang="tr" class="browser-Chrome" style="--vh: 9.450000000000001px;">

<head>
    <meta charset="utf-8">
    <title data-rh="true"></title>



    <meta name="viewport" content="width=device-width, maximum-scale=1, viewport-fit=cover">


    <link data-chunk="main" rel="stylesheet" href="/sporassets/main.15203e0c84ea961ee027.css">
    <link data-chunk="theme" rel="stylesheet" href="/sporassets/theme.3ed7d24f26ca4b2477c4.css">
    <link data-chunk="home" rel="stylesheet" href="/sporassets/3.5ea1511a7cce485e81ae.css">
    <link data-chunk="home" rel="stylesheet" href="/sporassets/0.38c1ac79ecf1be31d551.css">
    <link data-chunk="home" rel="stylesheet" href="/sporassets/2.604450a90727135839a1.css">
    <link data-chunk="home" rel="stylesheet" href="/sporassets/1.b3fcf877461209e39ccd.css">
    <link data-chunk="home" rel="stylesheet" href="/sporassets/6.3b5480dc1d9cd739b966.css">

    <!-- Env variables -->
    <script type="text/javascript">
        Object.defineProperty(window, 'PROCESS_ENV', {
            value: Object.freeze({ "NODE_ENV": "production", "PROJECT_ENV": "production", "BETTING_PLATFORM_SVC_URL": "https://sportsbook-betting-betby-prod-2.gtdevteam.work", "BETTING_PLATFORM_SVC_TENANT_ID": "be607739-89aa-4e11-a32f-6521cbf19241", "BETTING_PLATFORM_CMS_SVC_URL": "https://sportsbook-cms-svc-prod.gtdevteam.work", "BETTING_PLATFORM_CONFIG_SVC_URL": "https://sportsbook-betting-config-svc-prod.gtdevteam.work", "MAINTENANCE_WHITELISTED_IPS": "217.21.60.69,54.247.131.117,193.161.14.148,128.124.60.16,79.110.133.34,93.73.252.12,178.158.194.96", "GTAG": "G-Q2QHHDJV3K", "SENTRY_DSN": "https://dc2208bdb44da909920fd615e6557580@o249775.ingest.sentry.io/4506240876871680", "BETBY_API_URL": "https://sportsbook-betting-betby-prod-2.gtdevteam.work/v3", "BETBY_API_URL_V2": "https://sportsbook-betting-betby-prod-2.gtdevteam.work/v3", "BETBY_BRAND_ID": "2346016880764006400", "BETBY_LIVE_TRACKER_URL": "https://start9.sptpub.com", "BETBY_WS_URL": "wss://api1-ws.sptpub.com/api/v1", "BETBY_RINDLES_URL": "https://s.sptpub.com/92a4b2bb", "BRAND_NAME": "casipol" }),
            writable: false
        });
        window.__HISTORY_STATE__ = undefined;
    </script>
    <!-- End Env variables-->
    <link rel="stylesheet" type="text/css" href="/sporassets/13.ca7386153f0814e7c5d8.css">
    <script charset="utf-8" src="/sporassets/13.8612bbd3e0340393cd4c.js"></script>
    <link rel="stylesheet" type="text/css" href="/sporassets/7.10632a04adb21a618427.css">
    <script charset="utf-8" src="/sporassets/7.2248abf3440d4330b8d4.js"></script>
</head>

<body class="">

    <div id="root" class="container-min-width d-flex flex-column">
        <div class="global-notifications-stack position-fixed d-flex flex-column px-1 mt-sm-3 px-sm-2"></div>
        <div class="main-bg-wrapper overflow-hidden position-absolute">
            <div class="main-bg position-absolute main-bg-default main-bg-1"></div>
        </div>
        <div class="d-flex main-content">
            <div class="left-sidebar d-none d-lg-block bg-main-2 pb-4 flex-shrink-0">
                <div class="d-flex m-1_5 mt-2">

                  
                </div>
                <div class="pb-2 text-small"><span role="button" tabindex="0"
                        class="d-flex fast-navigation-item justify-content-between align-items-center pl-lg-2_5 pr-2 inert-element text-capitalize position-relative pl-4">
                        <div class="icon text-truncate"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"
                                viewBox="0 0 20 20">
                                <path fill="#FFFFFF" fill-rule="evenodd"
                                    d="M10.664.59l8 7.112c.214.19.336.461.336.747V18c0 .552-.448 1-1 1h-4.25v-5l-.005-.2c-.104-1.978-1.74-3.55-3.745-3.55-2.071 0-3.75 1.679-3.75 3.75v5H2c-.552 0-1-.448-1-1V8.45c0-.287.122-.559.336-.748l8-7.111c.379-.337.95-.337 1.328 0zM10 11.75c1.243 0 2.25 1.007 2.25 2.25v5h-4.5v-5l.005-.154c.08-1.17 1.054-2.096 2.245-2.096z">
                                </path>
                            </svg><span class="pl-2_5 align-text-top">Ana sayfa</span><span
                                class="text-extra-3 pl-1 d-inline font-weight-normal align-text-top"></span></div>
                    </span>
                    
                    
                    <span role="button" tabindex="0"
                        class="d-flex fast-navigation-item justify-content-between align-items-center pl-lg-2_5 pr-2 inert-element text-capitalize position-relative">
                        <div class="icon text-truncate"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"
                                viewBox="0 0 20 20">
                                <path fill="#FFFFFF"
                                    d="M11 14.5l-.001 2.5H14v2H6v-2h2.999L9 14.5h2zM18.01 2C19.108 2 20 2.9 20 3.992v7.016c0 1.1-.898 1.992-1.99 1.992H1.99C.892 13 0 12.1 0 11.008V3.992C0 2.892.898 2 1.99 2h16.02zM3.028 4.591c-.535 0-.961.17-1.28.51-.283.304-.44.716-.472 1.238l-.006.2v1.593c0 .62.165 1.1.494 1.438.33.338.77.507 1.322.507s.97-.149 1.253-.447c.252-.265.39-.643.414-1.136l.003-.19-.01-.022H3.742c.012.352-.031.6-.13.746-.099.145-.274.218-.526.218-.256 0-.45-.092-.584-.275-.114-.157-.179-.385-.195-.683l-.004-.156v-1.6c0-.371.062-.648.186-.831.125-.183.304-.275.539-.275.273 0 .465.077.575.23.094.133.142.336.145.611l-.002.144H4.75l.011-.022c-.01-.593-.16-1.041-.449-1.344-.289-.303-.717-.454-1.283-.454zm4.5.077H6.443L4.943 10h1.051l.286-1.132h1.406L7.976 10h1.05L7.528 4.668zm2.855 0H9.34V10h1.044V6.598l.022-.007L12.036 10h1.036V4.668h-1.037v3.398l-.022.008-1.63-3.406zm4.444 0h-1.043V10h2.992v-.831h-1.949V4.668zm3.46 0h-1.036V10h1.036V4.668zM6.994 6.144l.48 1.886h-.982l.48-1.886h.022z">
                                </path>
                            </svg><span class="pl-2_5 align-text-top">Canlı</span><span
                                class="text-extra-3 pl-1 d-inline font-weight-normal align-text-top">143</span><span
                                class="position-absolute in-play-animation animation-first first-animation-positionY animation-positionX"></span><span
                                class="position-absolute in-play-animation animation-second second-animation-positionY animation-positionX"></span><span
                                class="position-absolute in-play-animation animation-third third-animation-positionY animation-positionX"></span>
                        </div>
                    </span></div>
                <div class="left-sidebar-divider"></div>
                <div class="sports">




                    <div class="text-uppercase pt-2_5 pl-lg-2_5 label text-extra-3 pb-1_5">Tüm Sporlar</div>
                 
                 
                <div id="sports-list" class="sports-list">
    <!-- Dinamik spor listesi buraya eklenecek -->
</div>

<!-- SweetAlert CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<!-- SweetAlert JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>






<script>
    const API_BASE_URL = 'https://ariabet.tech/api';

    // 1. Sporları API'den almak
    async function fetchSports() {
        try {
            const response = await fetch(`${API_BASE_URL}/sports?langId=4&partnerId=326&sportType=live`);
            if (!response.ok) throw new Error('Sporları yüklerken hata oluştu');
            const sports = await response.json();
            displaySports(sports);
        } catch (error) {
            console.error('Sporlar yüklenemedi:', error);
            alert('Sporlar yüklenemedi. Lütfen daha sonra tekrar deneyin.');
        }
    }

    // 2. Sporları HTML sayfasında listelemek
    function displaySports(sports) {
        const sportsList = document.getElementById('sports-list');
        sportsList.innerHTML = '';

        if (sports.length === 0) {
            sportsList.textContent = 'Spor bulunamadı.';
            return;
        }

        sports.forEach(sport => {
            const sportItem = document.createElement('div');
            sportItem.className = 'sports-list-subitem position-relative';
            sportItem.innerHTML = `
                <div class="sports-list-subitem-element is-country d-flex pl-4 pl-lg-2_5 pr-8 pr-sm-8_5 pr-lg-5 align-items-center position-relative font-weight-bold"
                    tabindex="0" role="button">
                    <div class="d-flex align-items-center">
                        <div class="right-arrow arrow-active">
                            <svg xmlns="http://www.w3.org/2000/svg" width="9" height="14" class="arrow-icon" viewBox="0 0 9 14">
                                <g fill="none" fill-rule="evenodd">
                                    <path stroke="rgba(255,255,255,.65)" stroke-linecap="square" stroke-width="2" d="M2 12.286L6.966 7.32 2 2"></path>
                                </g>
                            </svg>
                        </div>
                    </div>
                    <div class="d-flex pl-1_5 my-1 py-0_25 overflow-hidden">
                        <span class="navigation-item-name overflow-hidden">${sport.N}</span>
                    </div>
                </div>
                <div id="countries-${sport.Id}" class="countries-container" style="display: none;">
                    <!-- Ülke listesi buraya eklenecek -->
                </div>`;

            sportsList.appendChild(sportItem);

            const sportElement = sportItem.querySelector('.sports-list-subitem-element');
            const countriesContainer = sportItem.querySelector(`#countries-${sport.Id}`);
            const arrowIcon = sportElement.querySelector('.arrow-icon');

            sportElement.addEventListener('click', () => {
                const isVisible = countriesContainer.style.display === 'block';
                countriesContainer.style.display = isVisible ? 'none' : 'block';
                arrowIcon.style.transform = isVisible ? 'rotate(0deg)' : 'rotate(90deg)';

                // Eğer ülkeler henüz yüklenmemişse, ülkeleri al
                if (!isVisible && countriesContainer.children.length === 0) {
                    fetchCountries(sport, `countries-${sport.Id}`);
                }
            });
        });
    }
// 3. Ülke listesini almak (Canlı etkinlik verisiyle)
async function fetchCountries(sport, containerId, sportType = 'live') {
    try {
        // Canlı etkinlikler için URL ve query parametreleri
        const url = `${API_BASE_URL}/live/getliveevents?sportId=${sport.Id}&checkIsActiveAndBetStatus=false&stakeTypes=1&stakeTypes=702&stakeTypes=2&stakeTypes=3&stakeTypes=37&langId=4&partnerId=326`;

        const response = await fetch(url, {
            method: 'GET',  // Canlı etkinlikler için GET methodu
            headers: {
                'Content-Type': 'application/json',
                'Referer': 'https://ariabet.tech',
                'Origin': 'https://ariabet.tech',
            },
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`API Hatası: ${response.status} - ${errorText}`);
        }

        const events = await response.json();
        displayCountries(events, containerId, sport);
    } catch (error) {
        console.error('Canlı Etkinlikler yüklenemedi:', error);
        alert(`Canlı etkinlikler yüklenemedi. Hata: ${error.message}`);
    }
}



// 4. Ülkeleri HTML sayfasında listelemek
// Ülkeleri listelemek
async function displayCountries(countries, containerId, sport) {
    const container = document.getElementById(containerId);
    container.innerHTML = '';  // Önceki içerikleri temizle

    if (countries.length === 0) {
        container.textContent = 'Ülke bulunamadı.';
        return;
    }

    countries.forEach(country => {
        const countryItem = document.createElement('div');
        countryItem.className = 'country-item';  // Her ülkeye özel bir sınıf
        countryItem.id = `country-${country.Id}`; // Her ülkeye özel bir ID

        countryItem.innerHTML = `
            <div role="button" tabindex="0" class="country-header">
                <span class="country-name">${country.N}</span>
                <svg xmlns="http://www.w3.org/2000/svg" width="9" height="14" class="arrow-icon" viewBox="0 0 9 14">
                    <g fill="none" fill-rule="evenodd">
                        <path stroke="rgba(255,255,255,.65)" stroke-linecap="square" stroke-width="2" d="M2 12.286L6.966 7.32 2 2"></path>
                    </g>
                </svg>
            </div>
            <div class="league-container-wrapper">
                <div id="leagues-${country.Id}" class="leagues-container" style="display: none;">
                    <!-- Lig listesi buraya eklenecek -->
                </div>
            </div>
        `;

        container.appendChild(countryItem);

        const countryElement = countryItem.querySelector('.country-header');
        const leaguesContainer = countryItem.querySelector(`#leagues-${country.Id}`);
        const arrowIcon = countryItem.querySelector('.arrow-icon');

        countryElement.addEventListener('click', () => {
            const isVisible = leaguesContainer.style.display === 'block';
            leaguesContainer.style.display = isVisible ? 'none' : 'block';
            arrowIcon.style.transform = isVisible ? 'rotate(0deg)' : 'rotate(90deg)';

            // Eğer ligler henüz yüklenmemişse, ligleri al
            if (!isVisible && leaguesContainer.children.length === 0) {
                fetchLeagues(country, sport, leaguesContainer);  // Ligleri al
            }
        });
    });
}

// Ligleri listelemek
async function fetchLeagues(country, sport, container) {
    try {
        const response = await fetch(`${API_BASE_URL}/leagues`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ countryId: country.Id, sportId: sport.Id }),
        });

        if (!response.ok) throw new Error('Lig listesi yüklenirken hata oluştu');
        const leagues = await response.json();

        // Ligleri belirtilen container'a ekleyelim
        leagues.forEach(league => {
            const leagueItem = document.createElement('div');
            leagueItem.className = 'league-item';

            leagueItem.innerHTML = `
                <span role="button" tabindex="0">
                    <div class="league-name">${league.N}</div>
                </span>
            `;

              // Etkinlikleri getir fonksiyonunu bağla
                leagueItem.addEventListener('click', () => fetchEvents(league, sport));
                container.appendChild(leagueItem);
            });
        } catch (error) {
            alert('Lig listesi yüklenemedi. Lütfen daha sonra tekrar deneyin.');
        }
    }

// 7. Etkinlik listesini almak


// Sayfa yüklendiğinde etkinlikleri otomatik olarak çek
document.addEventListener('DOMContentLoaded', () => {
    const league = { Id: 4520 }; // Champ ID'yi burada belirliyoruz
    const sport = 'football'; // Sport türünü belirleyin (örneğin, 'football')

    fetchEvents(league, sport); // Etkinlikleri yükle
});

// Etkinlik listesini almak
async function fetchEvents(league, sport) {
    try {
        const response = await fetch(`${API_BASE_URL}/events?champId=${league.Id}`);
        if (!response.ok) throw new Error('Etkinlik listesi yüklenirken hata oluştu');
        const events = await response.json();
        displayEvents(events, sport, league);
    } catch (error) {
        console.error('Etkinlik listesi yüklenemedi:', error);
        alert('Etkinlik listesi yüklenemedi. Lütfen daha sonra tekrar deneyin.');
    }
}

// Etkinlikleri görüntüleme fonksiyonu
function displayEvents(events, sport, league) {
    const eventListElement = document.getElementById('event-list');
    eventListElement.innerHTML = '';  // Önceki etkinlikleri temizle

    events.forEach(event => {
        // Etkinlik kutusu
        const eventContainer = document.createElement('div');
        eventContainer.classList.add('event-item', 'bg-main-2', 'p-2', 'rounded');

        // Etkinlik detayları
        const eventDetails = document.createElement('div');
        eventDetails.classList.add('event-details');
        
        const eventName = document.createElement('h3');
        eventName.classList.add('font-bold', 'text-lg');
        eventName.textContent = `${event.N} - OC: ${event.OC || 'Bilgi Yok'}`;

        const eventTime = document.createElement('p');
        eventTime.classList.add('text-sm', 'text-gray-600');
        eventTime.textContent = `Zaman: ${event.D || 'TBA'}`;

        // Oranlar konteyneri
        const oddsContainer = document.createElement('div');
        oddsContainer.classList.add('odds-container', 'position-relative');

        if (event.StakeTypes && event.StakeTypes.length > 0) {
            event.StakeTypes.forEach(stakeType => {
                const marketName = document.createElement('div');
                marketName.classList.add('market-name', 'text-center', 'mt-1');
                const marketTitle = document.createElement('span');
                marketTitle.classList.add('text-nowrap', 'text-extra-3');
                marketTitle.textContent = stakeType.N;
                marketName.appendChild(marketTitle);
                oddsContainer.appendChild(marketName);

                // Oran kaydırma konteyneri
                const oddsScrollWrapper = document.createElement('div');
                oddsScrollWrapper.classList.add('odds-scroll-wrapper', 'd-flex', 'overflow-auto', 'mt-2');

                stakeType.Stakes.forEach(stake => {
                    const outcomeWrapper = document.createElement('div');
                    outcomeWrapper.classList.add('outcome-wrapper', 'odd-cell', 'd-flex', 'flex-column', 'justify-content-between', 'align-items-center', 'text-small', 'px-2', 'py-1', 'mr-2');
                    outcomeWrapper.setAttribute('data-event-id', event.Id); // eventId'yi ekle
                    outcomeWrapper.setAttribute('data-stake-id', stake.Id); // stakeId'yi ekle

                    const oddLabel = document.createElement('span');
                    oddLabel.classList.add('odd-cell-label', 'text-nowrap');
                    oddLabel.textContent = stake.A !== null && stake.A !== undefined ? `${stake.N} (${stake.A >= 0 ? '+' : ''}${stake.A})` : stake.N;

                    const oddValue = document.createElement('div');
                    oddValue.classList.add('odd-cell-value', 'd-flex', 'align-items-center', 'justify-content-center');
                    const rankArrow = document.createElement('div');
                    rankArrow.classList.add('rank-arrow', 'font-weight-bold');
                    rankArrow.textContent = stake.F;

                    oddValue.appendChild(rankArrow);
                    outcomeWrapper.appendChild(oddLabel);
                    outcomeWrapper.appendChild(oddValue);
                    oddsScrollWrapper.appendChild(outcomeWrapper);

                    // Oran seçme tıklama olayını ekle
                    outcomeWrapper.addEventListener('click', () => handleOddSelection(outcomeWrapper, event));
                });

                oddsContainer.appendChild(oddsScrollWrapper);
            });
        } else {
            const noOdds = document.createElement('div');
            noOdds.textContent = 'Oranlar mevcut değil';
            oddsContainer.appendChild(noOdds);
        }

        // Etkinlik detaylarını etkinlik kutusuna ekle
        eventDetails.appendChild(eventName);
        eventDetails.appendChild(eventTime);
        eventDetails.appendChild(oddsContainer);

        // Etkinlik kutusunu etkinlik listesine ekle
        eventContainer.appendChild(eventDetails);
        eventListElement.appendChild(eventContainer);
    });
}


let selectedOdds = JSON.parse(localStorage.getItem('selectedOdds')) || {}; // LocalStorage'dan oranları al

// Sayfa yüklenirken seçili oranları geri yükle
document.addEventListener('DOMContentLoaded', () => {
    Object.keys(selectedOdds).forEach(eventId => {
        const oddData = selectedOdds[eventId];
        const outcomeWrapper = document.querySelector(`[data-event-id="${eventId}"][data-stake-id="${oddData.stakeId}"]`);
        if (outcomeWrapper) {
            outcomeWrapper.classList.add('selected-odd'); // Seçili oranı işaretle
        }
    });
});

// Oran seçme işlevi
function handleOddSelection(outcomeWrapper, event) {
    const stakeInput = document.getElementById('stake-amount'); // Stake input öğesini al
    if (!stakeInput) {
        console.error('Stake amount input element not found!');
        return;
    }
    const stakeAmount = parseFloat(stakeInput.value) || 0; // Miktar yoksa varsayılan 0

    const eventId = event.Id;
    const stakeId = outcomeWrapper.getAttribute('data-stake-id'); // Oran için benzersiz ID

    // Oranı kaydet
    if (!selectedOdds[eventId]) {
        selectedOdds[eventId] = {}; // Eğer eventId daha önce kaydedilmediyse, yeni bir obje oluştur
    }

    selectedOdds[eventId][stakeId] = {
        stakeId: stakeId,
        eventName: event.N,
        stakeName: outcomeWrapper.querySelector('.odd-cell-label').textContent,
        stakeAmount: stakeAmount,
        oddValue: outcomeWrapper.querySelector('.odd-cell-value').textContent
    };

    outcomeWrapper.classList.add('selected-odd'); // Seçilen oranı işaretle

    localStorage.setItem('selectedOdds', JSON.stringify(selectedOdds)); // LocalStorage'a kaydet
    addToBetSlip(event, outcomeWrapper, stakeAmount); // Bet slip'ine ekle
}
////////////////////////////////////////////////////////////////

// Bet slip'ine oran eklemek
function handleOddSelection(outcomeWrapper, event, category) {
    const betSlipContent = document.getElementById('bet-slip-content');
    const eventId = event.Id;
    const selectedOddValue = parseFloat(outcomeWrapper.querySelector('.rank-arrow').textContent);

    // Eğer oran zaten seçildiyse
    if (selectedOdds[eventId]) {
        if (selectedOdds[eventId] === outcomeWrapper) {
            // Oran zaten seçili, hiçbir şey yapma
            return;
        }
    } else {
        // Yeni oran seçildiğinde
        outcomeWrapper.classList.add('selected-odd'); // Seçilen oranı işaretle
        selectedOdds[eventId] = outcomeWrapper; // Kaydet
        addToBetSlip(event, selectedOddValue, category); // Bet slip'e ekle
    }
}


// Tarih ve saat formatlama fonksiyonları
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('tr-TR', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

function formatTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' });
}

let totalOdds = 0; // Başlangıç oranı 1 olmalı, çünkü çarpmak için 1 ile başlamak gerekiyor
let totalStakeAmount = 10; // Varsayılan stake miktarı

function addToBetSlip(event, oddValue, category) {
    const betSlipContent = document.getElementById('bet-slip-content');
    const eventId = event.Id;

    // Tarih ve saat formatlama
    const eventDate = formatDate(event.D);
    const eventTime = formatTime(event.D);

    // Seçilen oran (selected-odd) bilgisini al
    const selectedOddElement = selectedOdds[eventId];
    const selectedOddLabel = selectedOddElement 
        ? selectedOddElement.querySelector('.odd-cell-label').textContent 
        : 'N/A';

    // Seçilen oran ile ilişkili market-name bilgisini al
    const marketNameElement = selectedOddElement 
        ? selectedOddElement.closest('.odds-container').querySelector('.market-name span')
        : null;
    const marketName = marketNameElement 
        ? marketNameElement.textContent 
        : 'Belirtilmedi';

    // Mevcut oranı bet slip'e ekle
    const stakeItemHTML = `
        <div class="stake-item" id="stake-item-${eventId}">
            <div class="d-flex justify-content-between">
                <span class="event-name">${event.N}</span>
                <span class="odd-value modern-odd">${oddValue}</span>
            </div>
            <div class="bet-category">
                <span class="odd-label">Seçim: ${selectedOddLabel}</span> |
                <span class="teams">Market: ${marketName}</span>
            </div>
            <div class="bet-category">
                Tarih: ${eventDate} Saat: ${eventTime}
            </div>
            <div class="remove-odd" role="button" onclick="removeFromBetSlip('${eventId}', ${oddValue})">Kaldır</div>
        </div>
    `;

    // HTML'i ekle
    betSlipContent.insertAdjacentHTML('beforeend', stakeItemHTML);

    totalOdds += oddValue;

    // Eğer ilk defa stake-input ve potential-winnings ekleniyorsa, bunları ekle
    if (betSlipContent.querySelector('.bet-amount-input') === null) {
        const stakeAmountHTML = `
            <div class="bet-amount-input">
                <input 
                    type="number" 
                    class="stake-amount" 
                    id="stake-amount"
                    value="${totalStakeAmount}"
                />
                <div class="bet-amount-input-currency">TL</div>
            </div>
            <div class="potential-winnings" id="potential-winnings">
                Muhtemel Kazanç: ${(totalStakeAmount * totalOdds).toFixed(2)} TL
            </div>
        `;
        betSlipContent.insertAdjacentHTML('beforeend', stakeAmountHTML);

        // Stake input için event listener ekle
        const stakeAmountInput = document.getElementById('stake-amount');
        if (stakeAmountInput) {
            stakeAmountInput.addEventListener('input', updatePotentialWinnings);
        } else {
            console.error("Stake amount input element not found!");
        }
    } else {
        // Oranlar güncellendikçe kazançları güncelle
        updatePotentialWinnings();
    }

    // Bet slip content'i her güncelleme sonrasında aşağıya kaydır
    moveToBottom();
}


function updatePotentialWinnings() {
    const stakeAmountInput = document.getElementById('stake-amount');
    const potentialWinningsElement = document.getElementById('potential-winnings');

    if (!stakeAmountInput || !potentialWinningsElement) {
        console.error("Stake amount input or potential winnings element not found!");
        return;
    }

    // Get the stake amount and ensure it's a valid number
    const stakeAmount = parseFloat(stakeAmountInput.value);

    // Ensure that the stake amount and total odds are valid numbers
    if (isNaN(stakeAmount) || stakeAmount <= 0 || isNaN(totalOdds) || totalOdds <= 0) {
        potentialWinningsElement.textContent = "Muhtemel Kazanç: 0.00 TL";
        return;
    }

    // Calculate potential winnings
    const potentialWinnings = stakeAmount * totalOdds;
    potentialWinningsElement.textContent = `Muhtemel Kazanç: ${potentialWinnings.toFixed(2)} TL`;
}

function moveToBottom() {
    // Scroll betSlipContent to the bottom after each update
    const betSlipContent = document.getElementById('bet-slip-content');
    betSlipContent.scrollTop = betSlipContent.scrollHeight;

    // Ensure the stake input and potential winnings stay at the bottom
    const stakeAmountInput = document.getElementById('stake-amount');
    const potentialWinningsElement = document.getElementById('potential-winnings');

    if (stakeAmountInput && potentialWinningsElement) {
        betSlipContent.appendChild(stakeAmountInput.parentElement); // Move stake amount and potential winnings to the bottom
        betSlipContent.appendChild(potentialWinningsElement); // Move potential winnings to the bottom
    }
}


function removeFromBetSlip(eventId, oddValue) {
    // Bet slip'ten oranı kaldır
    const stakeItem = document.getElementById(`stake-item-${eventId}`);
    if (stakeItem) stakeItem.remove();

    // Oranı çıkar
    totalOdds -= oddValue;  // Oranı toplamadan çıkar (çıkar)

    // Eğer oran zaten seçildiyse, selected-odd sınıfını kaldır
    const outcomeWrapper = selectedOdds[eventId];
    if (outcomeWrapper) {
        outcomeWrapper.classList.remove('selected-odd'); // Seçimi kaldır
        delete selectedOdds[eventId]; // Seçilen oranı sil
    }

    // Eğer bet slip'te hiç maç yoksa, stake ve kazanç alanlarını kaldır
    const betSlipContent = document.getElementById('bet-slip-content');
    const remainingItems = betSlipContent.querySelectorAll('.stake-item');

    if (remainingItems.length === 0) {
        const betAmountInput = document.querySelector('.bet-amount-input');
        const potentialWinnings = document.querySelector('.potential-winnings');
        
        // Kaldır
        if (betAmountInput) betAmountInput.remove();
        if (potentialWinnings) potentialWinnings.remove();
    } else {
        // Oranlar güncellenip, kazançları yeniden hesapla
        updatePotentialWinnings();
    }
}



document.addEventListener('DOMContentLoaded', () => {
    const betSlipContent = document.getElementById('bet-slip-content');
    const isUserLoggedIn = <?php echo json_encode($isLoggedIn); ?>;
    const userBalance = <?php echo json_encode($userBalance); ?>;
    const minBetAmount = <?php echo json_encode($minBetAmount); ?>;

    if (betSlipContent) {
        const betSlipFooter = document.createElement('div');
        betSlipFooter.className = 'bet-slip-footer pb-2_5 pt-2 bg-main-4 is-ordinar';
        betSlipFooter.innerHTML = `
            <div class="d-flex align-items-center"></div>
            <button type="button" class="position-relative btn btn-primary btn-sm btn-block">
                <div class="btn-content"><span>Bahis yap</span></div>
            </button>
        `;

        betSlipContent.parentElement.appendChild(betSlipFooter);

        const betButton = betSlipFooter.querySelector('button');
        betButton.addEventListener('click', () => {
            if (!isUserLoggedIn) {
                Swal.fire({
                    icon: 'error',
                    title: 'Giriş Yapınız',
                    text: 'Bahis yapabilmek için lütfen giriş yapınız.',
                });
                return;
            }

            const stakeAmountInput = document.getElementById('stake-amount');
            const stakeAmount = stakeAmountInput ? parseFloat(stakeAmountInput.value) : 0;

            if (stakeAmount < minBetAmount) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Yetersiz Bahis Tutarı',
                    text: `Minimum bahis tutarı ${minBetAmount} TL olmalıdır.`,
                });
                return;
            }

            if (userBalance < stakeAmount) {
                Swal.fire({
                    icon: 'error',
                    title: 'Yetersiz Bakiye',
                    text: 'Bahis yapmak için lütfen bakiyenizi yükleyin.',
                });
                return;
            }

            Swal.fire({
                icon: 'success',
                title: 'Kupon Kaydediliyor',
                text: 'Kuponunuz başarıyla kaydediliyor...',
            }).then(() => {
                processBetSlip(stakeAmount); // Bahis işlemini başlat
            });
        });
    }
});

function processBetSlip(stakeAmount) {
    const betSlipContent = document.getElementById('bet-slip-content');
    const betItems = betSlipContent.querySelectorAll('.stake-item');

    // Eğer betItems boşsa veya betItems null ise, fonksiyonu sonlandır
    if (!betItems || betItems.length === 0) {
        console.error('No bet items found.');
        return;
    }

    const bets = Array.from(betItems).map(item => {
        const eventName = item.querySelector('.event-name').textContent;
        const oddValueElement = item.querySelector('.odd-value');
        const oddValue = oddValueElement ? parseFloat(oddValueElement.textContent) : 0;
        const eventId = item.id.replace('stake-item-', '');
        
        // Tarih ve saat bilgilerini al
        const eventDate = item.querySelector('.bet-category').textContent.trim().split("Saat: ")[0];
        const eventTime = item.querySelector('.bet-category').textContent.trim().split("Saat: ")[1];
        
        // Seçilen oran ve market bilgilerini al
        const selectedOddLabel = item.querySelector('.odd-label').textContent.split(': ')[1];
        const marketName = item.querySelector('.teams').textContent.split(': ')[1];

        return {
            eventId: eventId,
            eventName: eventName,
            oddValue: oddValue,
            stakeAmount: stakeAmount,
            eventDate: eventDate,
            eventTime: eventTime,
            selectedOddLabel: selectedOddLabel,
            marketName: marketName,
            status: 'Bekliyor'  // Başlangıçta statü 'Bekliyor'
        };
    });

    const payload = {
        stakeAmount,
        bets,
    };

    // Verileri sunucuya gönder
    fetch('/save-bet-slip.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
    })
    .then(response => response.json())
    .then(data => {
        console.log('Server Response:', data); // Sunucu yanıtını konsola yazdır
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Başarılı',
                text: 'Kuponunuz başarıyla kaydedildi.',
            });
            betSlipContent.innerHTML = ''; // Bahis slip'ini temizle
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Hata',
                text: data.message || 'Kupon kaydedilirken bir hata oluştu.',
            });
        }
    })
    .catch(error => {
        console.error('Error saving bet slip:', error);
        Swal.fire({
            icon: 'error',
            title: 'Hata',
            text: 'Bir hata oluştu. Lütfen tekrar deneyin.',
        });
    });
}



// Etkinlik detaylarını almak
async function fetchEventDetails(event, sport, league) {
    console.log('Detayları al:', event);
}




// Sayfa yüklendiğinde sporları getir
fetchSports();

</script>



<style>

    

/* Oran için modern görünüm */
.modern-odd {
    background-color: #28a745; /* Yeşil arka plan */
    color: #fff; /* Beyaz yazı */
    font-size: 18px; /* Büyük yazı */
    font-weight: bold; /* Kalın yazı */
    padding: 5px 10px; /* İç boşluk */
    border-radius: 5px; /* Yuvarlatılmış köşeler */
    display: inline-block; /* Inline görünüm */
    text-align: center; /* Metin hizalama */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* Hafif gölge */
    transition: background-color 0.3s ease, transform 0.2s ease; /* Animasyon */
}

/* Hover efekti */
.modern-odd:hover {
    background-color: #218838; /* Daha koyu yeşil */
    transform: scale(1.05); /* Hafif büyüme efekti */
}

/* Diğer tasarım iyileştirmeleri */
.stake-item {
    margin-bottom: 15px;
    padding: 15px;
}

.stake-item .d-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.remove-odd {
    margin-top: 10px;
    color: #dc3545; /* Kırmızı yazı */
    cursor: pointer;
    font-weight: bold;
    text-align: center;
    padding: 5px 10px;
    border-radius: 5px;
    background-color: #f8d7da; /* Hafif kırmızı arka plan */
    transition: background-color 0.3s ease, color 0.3s ease;
}

.remove-odd:hover {
    background-color: #f5c6cb; /* Daha koyu kırmızı */
    color: #721c24; /* Koyu kırmızı yazı */
}

.bet-amount-input {
    position: relative;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 15px;
    background-color: #2c2c2c; /* Arka plan koyu gri */
    border-radius: 8px; /* Yuvarlatılmış köşeler */
    padding: 10px 15px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); /* Hafif gölge */
}


.stake-amount {
    width: 100px; /* Giriş alanının genişliği */
    padding: 8px;
    font-size: 16px;
    font-weight: bold;
    background-color: #1a1a1a; /* Koyu arka plan */
    color: #e0e0e0; /* Açık gri yazı rengi */
    border: 1px solid #444; /* İnce çerçeve */
    border-radius: 5px; /* Yuvarlatılmış kenarlar */
    text-align: right; /* Yazıyı sağa yasla */
    outline: none; /* Odak çerçevesini kaldır */
    transition: all 0.3s ease; /* Pürüzsüz animasyon */
}

.stake-amount:focus {
    border-color: #888; /* Odaklanınca çerçeve rengi */
    box-shadow: 0 0 8px rgba(136, 136, 136, 0.5); /* Hafif bir parlama */
    background-color: #333; /* Odaklanınca arka plan rengi */
}

.bet-amount-input-currency {
    color: #b3b3b3; /* Gri tonunda yazı rengi */
    font-size: 14px;
    font-weight: 600; /* Hafif kalın yazı */
    pointer-events: none; /* Kullanıcı ile etkileşim engellendi */
    margin-left: auto; /* Giriş alanının sağına hizalar */
}

.bet-amount-input:hover {
    background-color: #333; /* Hover efekti için daha koyu gri */
}

.bet-amount-input-currency::before {
    content: "₺"; /* Para birimi sembolü */
    margin-right: 5px;
    color: #f2f2f2; /* Hafif açık gri sembol */
}


.selected-odd {
    background-color: lightblue; /* Or any light color to highlight the selected odd */
}



/* Ülke başlıkları */
.country-item {
  margin-bottom: 15px;
}

.country-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #ddd;
  cursor: pointer;
  border-radius: 5px;
}

.country-name {
  font-size: 16px;
  font-weight: bold;
}

.arrow-icon {
  transition: transform 0.3s ease-in-out;
}

/* Ligler listesi */
.league-container-wrapper {
  margin-top: 10px;
}

.leagues-container {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  display: none;
}

/* Lig öğeleri */
.league-item {
  padding: 8px;
  margin-bottom: 5px;
  border-radius: 3px;
  cursor: pointer;
}

.league-item:hover {
  background-color: #d3d3d3;
}

/* Arrow icon transformations */
.arrow-icon.rotate {
  transform: rotate(90deg);
}




</style>



                                    











                </div>

            </div>
            <div class="d-flex flex-column central-part position-relative px-0 px-sm-2 container-fluid">
                <div class="header-main d-flex flex-column mx-sm-n2 flex-shrink-0 bg-main-3"></div>
                <div class="league position-relative flex-fill">
                    <div class="d-none d-sm-block d-lg-none mt-2_5 text-small text-extra-2">Futbol</div>
                    <div class="d-none d-lg-block league-title h2 mt-3 mb-2 font-weight-bolder"></div>
                    <div role="button" tabindex="0" class="d-none d-sm-block d-lg-none">
                        <div class="league-title d-flex align-items-center h2 mt-0_5 mb-2 font-weight-bolder">3. Lig<svg
                                class="ml-1 flex-shrink-0" opacity="0.65" width="12px" height="12px" viewBox="0 0 12 12"
                                version="1.1" xmlns="http://www.w3.org/2000/svg">
                                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                    <g>
                                        <rect fill="transparent" x="0" y="0" width="12" height="12"></rect>
                                        <polygon fill="white" fill-rule="nonzero"
                                            points="6.0595297 7.00014982 10.06081 3 11.1213203 4.06081002 6.0595297 9.12117051 1 4.0630703 2.0605103 3.00226028">
                                        </polygon>
                                    </g>
                                </g>
                            </svg></div>
                    </div>

                    <div class="leagues d-lg-none is-league">
                        <div class="d-sm-none mt-2_5 mb-2_5 px-2"><span class="text-small text-extra-2">Futbol</span>
                            <div class="mt-0_5">
                                <div role="button" tabindex="0" class="d-flex align-items-center"><span
                                        class="h3 m-0 font-weight-bolder">3. Lig</span><svg class="ml-1 flex-shrink-0"
                                        opacity="0.65" width="12px" height="12px" viewBox="0 0 12 12" version="1.1"
                                        xmlns="http://www.w3.org/2000/svg">
                                        <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                            <g>
                                                <rect fill="transparent" x="0" y="0" width="12" height="12"></rect>
                                                <polygon fill="white" fill-rule="nonzero"
                                                    points="6.0595297 7.00014982 10.06081 3 11.1213203 4.06081002 6.0595297 9.12117051 1 4.0630703 2.0605103 3.00226028">
                                                </polygon>
                                            </g>
                                        </g>
                                    </svg></div>
                            </div>
                        </div>
                    </div>
                    <div class="tabs px-2 px-sm-0 mb-2_5">
                        <ul class="d-flex flex-nowrap mb-1_5 border-bottom nav nav-tabs">
                            <li class="cursor-pointer position-relative pr-2 pr-sm-0 active nav-item"><a
                                    class="h6 text-uppercase text-nowrap p-0 pb-1_5 nav-link"><span>Etkinlikler</span></a>
                            </li>
                        </ul>
                        <div class="tab-content">
                            <div class="tab-pane active"></div>
                        </div>
                    
                   
                                    </div>

                                
                                
<div id="event-list"></div>

                                                            
                   
                   
                    </div>
                   
                   <!-- kupon -->
                   
                   
                 <div class="right-sidebar d-none d-lg-flex flex-column flex-shrink-0 pr-2 pt-2">
    <div></div>
    <div>
        <div class="ticket position-relative d-none d-lg-block rounded bg-main-2">
            <div>
                <div class="tabs">
                    <ul class="d-flex flex-nowrap mb-1_5 border-bottom nav nav-tabs">
                        <li class="cursor-pointer position-relative mr-2_5 active nav-item">
                            <a class="h6 text-uppercase text-nowrap p-0 pb-1_5 nav-link">
                                <div class="stakes-amount d-flex align-items-center justify-content-center rounded-circle order-last ml-1">
                                    1
                                </div><span>Kupon</span>
                            </a>
                        </li>
                        <li class="cursor-pointer position-relative pr-2 pr-sm-0 nav-item">
                            <a class="h6 text-uppercase text-nowrap p-0 pb-1_5 text-extra-2 nav-link">
                                <span>Bahislerim</span>
                            </a>
                        </li>
                    </ul>
                    <div class="tab-content">
                        <div class="tab-pane active">
                            <div>
                                <div class="bet-slip position-relative">
                                    <!-- Sticky Header -->
                                    <div class="bet-slip-sticky-header position-fixed d-flex align-items-center justify-content-between pr-1_5 bg-main-2 is-hidden">
                                        <span class="caption font-weight-bold text-extra-2">Tekli</span>
                                        <span class="caption text-extra-2" role="button" tabindex="0">Temizle</span>
                                    </div>

                                    <!-- Bet Items (Dynamic Content) -->
                                    <div id="bet-slip-content">
                                        <!-- New bets will be inserted here dynamically -->
                                    </div>

    <div id="bet-slip-footer">


                                    <!-- Notification (Optional) -->
                                    <div class="bet-slip-notification p-1_5 d-flex justify-content-center align-items-center position-fixed">
                                        <svg class="flex-shrink-0" xmlns="http://www.w3.org/2000/svg" width="13" height="10" viewBox="0 0 13 10">
                                            <path fill="#ffeb3b" d="M7.009.105c.145.086.266.207.352.352l4.747 8.034c.281.476.124 1.089-.352 1.37-.154.091-.33.139-.508.139H1.752c-.552 0-1-.448-1-1 0-.179.048-.355.14-.509L5.639.457c.281-.476.894-.633 1.37-.352zM7 7H6v1h1V7zm0-4H6v3h1V3z"></path>
                                        </svg>
                                        <span class="ml-1 text-small font-weight-bold">Kuponda en fazla 20 adet bahis bulunabilir.</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="tab-pane"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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






</body>

</html>