<?php 
session_start(); 

// Veritabanı bağlantısını yapın
include '../inc/database.php'; 

// Kullanıcının oturum açıp açmadığını kontrol edin
$isLoggedIn = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
$username = $isLoggedIn ? $_SESSION['username'] : ''; // Kullanıcı adını al
$email = ''; // E-posta adresi için bir değişken tanımlayın
$firstName = ''; // Kullanıcının ismi için bir değişken
$surname = ''; // Kullanıcının soyismi için bir değişken

// Kullanıcı giriş yapmamışsa yönlendirme yap
if (!$isLoggedIn) {
    header('Location: /'); // Giriş sayfasına yönlendir
    exit();
}

// Kullanıcının baş harfini al
$initial = strtoupper(substr($username, 0, 1)); // İlk karakteri al ve büyük harfe çevir

// E-posta adresi ve kullanıcı bilgilerini sorgula
$sql = "SELECT email, first_name, surname FROM kullanicilar WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($email, $firstName, $surname);
$stmt->fetch();
$stmt->close();
?>

<?php include '../inc/head.php'; ?>
<?php include '../inc/header.php'; ?>
<style>body{background:#000 !important;color:#fff}</style>
<style>
.mt-theme{display:flex;align-items:center;gap:10px;padding:8px 0}
.mt-theme .breadcrumb{display:flex;flex-wrap:wrap;gap:6px;background:transparent !important;margin:0 !important;padding:0 !important}
.breadcrumb-item, .breadcrumb-item a{color:#fff !important;text-decoration:none}
.breadcrumb-item + .breadcrumb-item::before{color:rgba(255,255,255,.6) !important}
.backBtn{margin-right:8px;border:1px solid rgba(255,255,255,.2);border-radius:8px;padding:8px 12px;color:#fff;background:transparent}
 .centerWrap.porfileWrap{padding-top:64px !important}
@media (max-width: 768px){
  .mt-theme{flex-wrap:wrap}
  .backBtn{width:36px;height:36px;padding:0;display:inline-flex;align-items:center;justify-content:center}
  .breadcrumb{font-size:14px}
  .centerWrap.porfileWrap{padding-top:25px !important}
}
</style>



<div _ngcontent-ouf-c21="" class="centerWrap porfileWrap">
    <aside _ngcontent-ouf-c27="" class="sidebarMain playersidebarMain">
        <div _ngcontent-ouf-c27="" class="profile-content">
            <div _ngcontent-ouf-c27="" class="edit-user"><!----><!---->                <span class="avatar-holder ng-tns-c27-2 ng-star-inserted"><?php echo $initial; ?></span>

                <div _ngcontent-ouf-c27="" class="user-right"><!----><!---->                    <span class="username ng-tns-c27-2 ng-star-inserted"><?php echo htmlspecialchars($username); ?></span>
</div>
            </div>
            
            
<script>
                document.addEventListener('DOMContentLoaded', function() {
                    const isLoggedIn = <?php echo json_encode($isLoggedIn); ?>;

                    if (isLoggedIn) {
                        // Kullanıcı giriş yapmışsa API'den ana bakiyeyi çek
                        fetch('/api/balanceapi.php')
                            .then(response => response.json())
                            .then(data => {
                                const balanceText = document.querySelector('.amount'); // .amount sınıfını hedef alıyoruz

                                if (data.status === 'success') {
                                    // Bakiye başarılı bir şekilde çekildiyse span'a yaz
                                    balanceText.textContent = data.ana_bakiye + ' '; // Para birimini ekleyerek yaz
                                } else {
                                    // Hata durumunda kullanıcıya bilgi ver
                                    alert("Hata: " + data.message); // Hata mesajını kullanıcıya göster
                                    console.error(data.message); // Hata mesajını konsola yazdır
                                }
                            })
                            .catch(error => {
                                console.error('Hata:', error);
                                alert("Bir hata oluştu. Lütfen tekrar deneyin."); // Genel hata mesajı
                            });
                    }
                });
            </script>


            
            
            <div _ngcontent-ouf-c27="" class="main-balance">
                <div _ngcontent-ouf-c27="" class="total-balance">
                    <div _ngcontent-ouf-c27="" class="user-balance"><span _ngcontent-ouf-c27="" class="balance-title">Ana Baki̇ye</span><!---->  <span class="amount ng-tns-c27-2 ng-star-inserted">0 ₺</span><!----></div><!----><i _ngcontent-ouf-c27="" class="fa-solid fa-eye eye-icon ng-tns-c27-2 ng-star-inserted"></i>
                </div>
                
                
                
<div _ngcontent-ouf-c27="" class="buttons-bottom">
    <a _ngcontent-ouf-c27="" class="btn deposit-bc" href="/profile/deposit-withdraw">
        <i _ngcontent-ouf-c27="" class="fa-solid fa-wallet"></i> Para Yatır
    </a>
    <a _ngcontent-ouf-c27="" class="btn withdraw-bc" href="/profile/deposit-withdraw">
        <img _ngcontent-ouf-c27="" class="ng-tns-c27-2" alt="" src="assets/images/withdraw-icon.png"> Para Çekme
    </a>
</div></div>
            <div _ngcontent-ouf-c27="" class="main-balance bonus">
                <div _ngcontent-ouf-c27="" class="user-balance"><span _ngcontent-ouf-c27="" class="balance-title">Bonus Bakiyesi</span><!----><span _ngcontent-ouf-c27="" class="amount ng-tns-c27-2 ng-star-inserted">0 ₺</span><!----></div>
            </div>
        </div>
        <div _ngcontent-ouf-c27="" class="sideSports">
            <ul _ngcontent-ouf-c27="" class="ng-tns-c27-2"><!----><!----><!----><!---->


 <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
    <a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/account-details">Profilim</a>
</li>

                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/account-statement">İşlem Geçmişi</a></li><!----><!----><!----><!----><!----><!---->

                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2 select active" style="cursor: pointer" type="GROUP">Casino Geçmişi</a></li><!----><!----><!----><!----><!----><!----><!---->
                               <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><span _ngcontent-ouf-c27="" class="ng-tns-c27-2" aria-disabled="true" style="cursor: default" type="GROUP"></span></li><!----><!---->

                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/invite">Davet Linki</a></li>
                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/referral">Referans Programı</a></li>
                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/responsible_gaming">Sorumlu Oyun</a></li>

                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/promotions.php">Promosyonlar</a></li><!----><!---->
         <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/deposit-withdraw">Para Yatırma/para Çekme</a></li><!----><!----><!----><!----><!----><!----><!---->
                <li _ngcontent-ouf-c27="" style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted"><a _ngcontent-ouf-c27="" class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/kyc">Kyc</a></li><!----><!---->
            </ul>
        </div>
    </aside>
</app-g6-sidebar-profile></app-player-sidebar-profile>



<app-all-bet-history _ngcontent-mhw-c56="" _nghost-mhw-c57="" class="ng-star-inserted"><div _ngcontent-mhw-c57="" class="container-fluid"><div _ngcontent-mhw-c57="" class="row"><app-g1-downline-navigation _ngcontent-mhw-c57="" _nghost-mhw-c48=""><div _ngcontent-mhw-c48="" class="col-12 mt-theme"><button _ngcontent-mhw-c48="" class="btn backBtn"><i _ngcontent-mhw-c48="" class="fa-solid fa-angle-left"></i></button><ul _ngcontent-mhw-c48="" class="breadcrumb">
    
<li _ngcontent-ouf-c48="" class="breadcrumb-item">
    <a _ngcontent-ouf-c48="" href="/">Ana Sayfa</a>
</li>
    
  <li _ngcontent-mhw-c48="" aria-current="page" class="breadcrumb-item">Casino Geçmişi</li>
</ul>
</div></app-g1-downline-navigation>
<div _ngcontent-mhw-c57="" class="col-12">
    <div _ngcontent-mhw-c57="" class="row">
        <div _ngcontent-mhw-c57="" class="col-md-12 col-lg-11 tableFilter">
           
        <div _ngcontent-mhw-c57="" class="col-md-2 col-lg-1 docButton"><!----><button _ngcontent-mhw-c57=""
                class="btn btn-sm btn-danger ng-star-inserted"><i _ngcontent-mhw-c57=""
                    class="fa-solid fa-file-pdf"></i></button><!----><button _ngcontent-mhw-c57=""
                class="btn btn-sm btn-success ng-star-inserted"><i _ngcontent-mhw-c57=""
                    class="fa-solid fa-file-excel"></i></button></div>
    </div>


<?php
// Oturum kontrolü (sayfanın başında zaten session_start() çağrıldı)
$isLoggedIn = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
$username = $isLoggedIn ? $_SESSION['username'] : ''; // Kullanıcı adını al

// Eğer kullanıcı giriş yapmamışsa, hata mesajı göster
if (!$isLoggedIn) {
    die("Lütfen giriş yapın.");
}

// Veritabanı bağlantısı
$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) {
    die("Veritabanı bağlantısı başarısız: " . $e->getMessage());
}

// Kullanıcıyı veritabanından çekme
function getUserFromDatabase($username) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM kullanicilar WHERE username = :username");
    $stmt->execute(['username' => $username]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Kullanıcının casino geçmişini live_bet tablosundan almak (sayfalama desteği)
function getBetHistory($user_id, $limit, $offset) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM live_bet WHERE users_id = :user_id AND (game_code IS NULL OR game_code <> 'sports') ORDER BY created_at DESC LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':user_id', (int)$user_id, PDO::PARAM_INT);
    $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getBetHistoryByUsername($username, $limit, $offset) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT lb.* FROM live_bet lb INNER JOIN kullanicilar u ON lb.users_id = u.id WHERE u.username = :username AND (lb.game_code IS NULL OR lb.game_code <> 'sports') ORDER BY lb.id DESC LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':username', $username, PDO::PARAM_STR);
    $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getBetHistoryCount($user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM live_bet WHERE users_id = :user_id AND (game_code IS NULL OR game_code <> 'sports')");
    $stmt->bindValue(':user_id', (int)$user_id, PDO::PARAM_INT);
    $stmt->execute();
    return (int)$stmt->fetchColumn();
}

function getBetHistoryCountByUsername($username) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM live_bet lb INNER JOIN kullanicilar u ON lb.users_id = u.id WHERE u.username = :username AND (lb.game_code IS NULL OR lb.game_code <> 'sports')");
    $stmt->bindValue(':username', $username, PDO::PARAM_STR);
    $stmt->execute();
    return (int)$stmt->fetchColumn();
}

// Game bilgilerini game_code üzerinden almak
function getGameInfo($game_code) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM games WHERE game_code = :game_code");
    $stmt->execute(['game_code' => $game_code]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Provider ismini game_code üzerinden almak
function getProviderName($game_code) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT provider_game FROM games WHERE game_code = :game_code");
    $stmt->execute(['game_code' => $game_code]);
    $game = $stmt->fetch(PDO::FETCH_ASSOC);
    return $game ? $game['provider_game'] : 'Bilinmiyor';
}

// Kullanıcıyı ve bahis geçmişini almak (sayfalama)
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = isset($_GET['per_page']) ? min(100, max(10, intval($_GET['per_page']))) : 25;
$offset = ($page - 1) * $perPage;
$user = getUserFromDatabase($username);
if (!$user) {
    $totalRecords = getBetHistoryCountByUsername($username);
    $betHistory = getBetHistoryByUsername($username, $perPage, $offset);
} else {
    $totalRecords = getBetHistoryCount($user['id']);
    $betHistory = getBetHistory($user['id'], $perPage, $offset);
}
$totalPages = max(1, (int)ceil($totalRecords / $perPage));
?>

<div class="container">
    <div class="table-responsive mt-1 mt-lg-4" id="container">
        <style>
            .statement-wrapper { max-width: 960px; width: 100%; margin: 0 auto; }
            .table-responsive { background:#000; margin:0 0 24px 0; padding:0 0 24px 0; }
            .statement-table {
                width: 100%;
                border-collapse: separate;
                border-spacing: 0;
                table-layout: fixed;
                background-color: #000;
                border: 1px solid rgba(var(--textwhite),0.08);
                border-radius: 8px;
                overflow: hidden;
            }
            .statement-table thead th {
                font-size: 13px; font-weight: 600; letter-spacing: .2px;
                color: var(--white-color); background: var(--primary);
                padding: 0 4px; white-space: nowrap;
            }
            .statement-table tbody td {
                font-size: 13px; color: var(--white-color); padding: 0 4px; white-space: nowrap; line-height: 1.2;
                border-top: 1px solid rgba(var(--textwhite),0.06);
            }
            .statement-table tr:hover td { background: rgba(var(--textwhite),0.06); }
            .text-right { text-align: right; }
            .chip { display: inline-block; padding: 2px 6px; border-radius: 999px; font-size: 11px; line-height: 1; white-space: nowrap; border: 1px solid rgba(var(--textwhite),0.10); }
            .chip-loss { background: rgba(239,68,68,.15); color: #ef4444; border-color: rgba(239,68,68,.35); }
            .chip-win { background: rgba(34,197,94,.15); color: #22c55e; border-color: rgba(34,197,94,.35); }
            .col-index{ width:10%; }
            .col-game{ width:45%; }
            .col-status{ width:25%; }
            .col-pnl{ width:30%; }
            .col-reason{ width:35%; }
        </style>
        <div class="statement-wrapper">
            <table class="statement-table">
                <thead>
                    <tr>
                        <th class="col-game">Oyun</th>
                        <th class="col-status">Durum</th>
                        <th class="col-pnl text-right">Kar/Zarar</th>
                    </tr>
                </thead>
            <tbody>
                <?php if (empty($betHistory)) : ?>
                    <tr>
                        <td colspan="3" class="text-center" style="padding:12px;color:#fff;background:#111;border:1px solid rgba(255,255,255,.08);border-radius:6px;">Gösterilecek kayıt bulunamadı.</td>
                    </tr>
                <?php else : ?>
                    <?php foreach ($betHistory as $index => $entry) : ?>
                        <?php $gameInfo = getGameInfo($entry['game_code'] ?? null); ?>
                        <?php $betAmount = isset($entry['bet_amount']) ? floatval($entry['bet_amount']) : 0; ?>
                        <?php $pnl = (isset($entry['get_amount']) ? floatval($entry['get_amount']) : 0) - $betAmount; ?>
                        <?php if ($pnl == 0) { continue; } ?>
                        <?php $isWin = isset($entry['get_amount']) && floatval($entry['get_amount']) > 0; ?>
                        <tr>
                            <td><?php echo htmlspecialchars($gameInfo['game_name'] ?? 'Bilinmiyor'); ?></td>
                            <td><?php echo $isWin ? '<span class="chip chip-win">Kazanç</span>' : '<span class="chip chip-loss">Kayıp</span>'; ?></td>
                            <td class="text-right <?php echo $pnl >= 0 ? 'profit' : 'loss'; ?>"><?php echo number_format($pnl, 2, ',', '.'); ?> ₺</td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
        <div class="table-pagination" style="display:flex;align-items:center;justify-content:space-between;margin-top:8px;gap:12px;">
            <div class="page-info" style="color:#fff;font-size:12px;">Sayfa <?php echo (int)$page; ?> / <?php echo (int)$totalPages; ?></div>
            <div class="page-controls" style="display:flex;align-items:center;gap:8px;">
                <?php
                $baseUrl = '/profile/bet-history.php';
                $prevPage = max(1, $page - 1);
                $nextPage = min($totalPages, $page + 1);
                ?>
                <a href="<?php echo $baseUrl . '?page=' . $prevPage . '&per_page=' . $perPage; ?>" class="btn" style="padding:4px 8px;border:1px solid rgba(255,255,255,.2);border-radius:6px;color:#fff;">Önceki</a>
                <a href="<?php echo $baseUrl . '?page=' . $nextPage . '&per_page=' . $perPage; ?>" class="btn" style="padding:4px 8px;border:1px solid rgba(255,255,255,.2);border-radius:6px;color:#fff;">Sonraki</a>
                <form method="get" action="<?php echo $baseUrl; ?>" style="margin:0;display:flex;align-items:center;gap:6px;">
                    <input type="hidden" name="page" value="1" />
                    <label for="per_page" style="color:#fff;font-size:12px;">Satır:</label>
                    <select id="per_page" name="per_page" onchange="this.form.submit()" style="background:#000;color:#fff;border:1px solid rgba(255,255,255,.2);border-radius:6px;padding:2px 6px;">
                        <?php foreach ([10,25,50,100] as $opt): ?>
                            <option value="<?php echo $opt; ?>" <?php echo ($perPage == $opt) ? 'selected' : ''; ?>><?php echo $opt; ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div>
        </div>
    </div>

<style>
    /* Kazançlar için yeşil renk, kayıplar için kırmızı renk, bahisler için kırmızı */
    .profit { color: green; font-weight: bold; }
    .loss { color: red; font-weight: bold; }
    .bet { color: red; font-weight: bold; }
</style>



</div>
</div><app-casino-winner-details _ngcontent-mhw-c57="" _nghost-mhw-c59="">
    <div _ngcontent-mhw-c59="" aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade"
        id="winner-detail" role="dialog" tabindex="-1">
        <div _ngcontent-mhw-c59="" class="modal-dialog" role="document">
            <div _ngcontent-mhw-c59="" class="modal-content">
                <div _ngcontent-mhw-c59="" class="modal-header">
                    <h5 _ngcontent-mhw-c59="" class="modal-title" id="exampleModalLabel" style=" float: left;">Round
                        ID:0</h5>
                </div>
                <div _ngcontent-mhw-c59="" class="modal-body " id="scrolltop" style="overflow-y: scroll;">
                    <!----><!----><!----><!----><!----><!----><!----><!---->
                    <table _ngcontent-mhw-c59="" class="table ng-star-inserted"
                        style="float: left; width: 100%; margin-top: 20px;">
                        <tbody _ngcontent-mhw-c59="" style="text-align: center;"><!----></tbody>
                    </table><!---->
                </div>
                <div _ngcontent-mhw-c59="" class="modal-footer" style="justify-content: flex-end;"><button
                        _ngcontent-mhw-c59="" class="btn btn-secondary"
                        style="background-color: var(--maindark); color: #fff;" type="button">Close</button></div>
            </div>
        </div>
    </div>
    <div _ngcontent-mhw-c59="" aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade"
        id="live-winner-detail" role="dialog" tabindex="-1">
        <div _ngcontent-mhw-c59="" class="modal-dialog" role="document">
            <div _ngcontent-mhw-c59="" class="modal-content">
                <div _ngcontent-mhw-c59="" class="modal-header">
                    <h5 _ngcontent-mhw-c59="" class="modal-title" id="exampleModalLabel" style=" float: left;">Bet ID:
                    </h5>
                </div><!---->
                <div _ngcontent-mhw-c59="" class="modal-footer" style="justify-content: flex-end;"><button
                        _ngcontent-mhw-c59="" class="btn btn-secondary"
                        style="background-color: var(--maindark); color: #fff;" type="button">Close</button></div>
            </div>
        </div>
    </div>
    <div _ngcontent-mhw-c59="" aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade" id="no-result"
        role="dialog" tabindex="-1">
        <div _ngcontent-mhw-c59="" class="modal-dialog" role="document">
            <div _ngcontent-mhw-c59="" class="modal-content">
                <div _ngcontent-mhw-c59="" class="modal-header">
                    <h5 _ngcontent-mhw-c59="" class="modal-title" id="exampleModalLabel" style=" float: left;">Round ID:
                    </h5>
                </div>
                <div _ngcontent-mhw-c59="" class="modal-body " id="scrolltop" style="overflow-y: scroll;height:100px">
                    <h2 _ngcontent-mhw-c59="">No Result Found</h2>
                </div>
                <div _ngcontent-mhw-c59="" class="modal-footer" style="justify-content: flex-end;"><button
                        _ngcontent-mhw-c59="" class="btn btn-secondary"
                        style="background-color: var(--maindark); color: #fff;" type="button">Close</button></div>
            </div>
        </div>
    </div>
</app-casino-winner-details><!----></app-all-bet-history>