<?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>
/* Filtre selectlerinin daralmamasını sağla */
.tableFilter .form-group select.form-control,
.tableFilter .form-group select.form-control-sm { min-width: 160px; width: 100%; max-width: 260px; padding-right: 18px; letter-spacing: .2px; }
.tableFilter .form-group select.form-control option,
 .tableFilter .form-group select.form-control-sm option { letter-spacing: .2px; }
 @media (max-width: 768px){ .tableFilter .form-group select.form-control, .tableFilter .form-group select.form-control-sm { max-width: 100%; } }
 .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:40px !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>
        <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 select active" style="cursor: pointer" type="GROUP">İş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" style="cursor: pointer" type="GROUP" href="/profile/bet-history">Casino 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" 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">
    <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="/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>
        </div></div>
        
    <div _ngcontent-gdo-c41="" class="centerWrap porfileWrap"><router-outlet _ngcontent-gdo-c41=""></router-outlet><app-account-statement _nghost-gdo-c53="" class="ng-star-inserted"><!----><!----><!----><!----><!----><!----><!----><app-all-account-statement _ngcontent-gdo-c53="" _nghost-gdo-c54="" class="ng-star-inserted">
                <div _ngcontent-gdo-c54="" class="container-fluid">
                    <div _ngcontent-gdo-c54="" class="row"><app-g1-downline-navigation _ngcontent-gdo-c54="" _nghost-gdo-c49="">
                            <div _ngcontent-gdo-c49="" class="col-12 mt-theme"><button _ngcontent-gdo-c49="" class="btn backBtn"><i _ngcontent-gdo-c49="" class="fa-solid fa-angle-left"></i></button>
                                <ul _ngcontent-gdo-c49="" class="breadcrumb">
<li _ngcontent-ouf-c48="" class="breadcrumb-item">
    <a _ngcontent-ouf-c48="" href="/">Ana Sayfa</a>
</li>
                                    <li _ngcontent-gdo-c49="" aria-current="page" class="breadcrumb-item">İşlem Geçmişi</li>
                                </ul>
                            </div>
                        </app-g1-downline-navigation>
                    <?php
// Veritabanı bağlantısı
$host = 'localhost';
$dbname = 'blacrhdy_bet1';
$user = 'blacrhdy_bet1';
$pass = 'blacrhdy_bet1';


try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    error_log('Connection failed: ' . $e->getMessage());
    exit();
}

// Kullanıcı bilgilerini al
$username = $_SESSION['username'];

try {
    $stmt = $pdo->prepare("SELECT id, username FROM kullanicilar WHERE username = :username");
    $stmt->execute(['username' => $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $user_id = $user['id'];
    } else {
        echo "User not found.";
        exit();
    }
} catch (PDOException $e) {
    error_log('Query failed: ' . $e->getMessage());
    exit();
}

// Filtreleri al
$transactionType = $_GET['transactionType'] ?? 'ALL';
$status = $_GET['status'] ?? 'ALL';

// SQL filtreleri
$whereClauses = [];
$params = ['user_id' => $user_id, 'username' => $username];

if ($transactionType !== 'ALL') {
    $table = $transactionType === 'DEPOSIT' ? 'parayatir' : 'paracek';
} else {
    $table = '';
}

if ($status !== 'ALL') {
    $whereClauses[] = 'durum = :status';
    $params['status'] = $status === 'PENDING' ? 0 : ($status === 'APPROVED' ? 1 : 2);
}

$whereSql = count($whereClauses) > 0 ? ' AND ' . implode(' AND ', $whereClauses) : '';

// Kayıtları al
$records = [];
if ($table) {
    try {
        // Hem user_id hem username ile eklenmiş kayıtları yakalayalım
        $stmt = $pdo->prepare("SELECT * FROM $table WHERE (user_id = :user_id OR uye = :user_id OR uye = :username) $whereSql ORDER BY tarih DESC");
        $stmt->execute($params);
        $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log('Query failed: ' . $e->getMessage());
    }
} else {
    // HEPSİ seçili ise her iki tablodan da kayıtları çek ve birleştir
    try {
        $allRecords = [];
        foreach (['parayatir', 'paracek'] as $tbl) {
            $stmt = $pdo->prepare("SELECT * FROM $tbl WHERE (user_id = :user_id OR uye = :user_id OR uye = :username) $whereSql");
            $stmt->execute($params);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            // Tür bilgisini ekleyelim
            foreach ($rows as &$r) { $r['__type'] = ($tbl === 'parayatir') ? 'Yatırım' : 'Çekim'; }
            unset($r);
            $allRecords = array_merge($allRecords, $rows);
        }
        // Tarihe göre azalan sırala
        usort($allRecords, function($a, $b) {
            $ta = isset($a['tarih']) ? strtotime($a['tarih']) : 0;
            $tb = isset($b['tarih']) ? strtotime($b['tarih']) : 0;
            return $tb <=> $ta;
        });
        $records = $allRecords;
    } catch (PDOException $e) {
        error_log('Query failed: ' . $e->getMessage());
    }
}
?>

<div _ngcontent-gdo-c54="" class="col-md-12 col-lg-11 tableFilter">
    <form method="GET" action="" id="filterForm">
        <div _ngcontent-gdo-c54="" class="form-group ng-star-inserted" id="sscroll">
            <label _ngcontent-gdo-c54="" class="col-form-label">İşlem Türü</label>
            <select name="transactionType" _ngcontent-gdo-c54="" class="form-control form-control-sm">
                <option _ngcontent-gdo-c54="" value="ALL" class="ng-star-inserted" <?= $transactionType === 'ALL' ? 'selected' : '' ?>>HEPSİ</option>
                <option _ngcontent-gdo-c54="" value="DEPOSIT" class="ng-star-inserted" <?= $transactionType === 'DEPOSIT' ? 'selected' : '' ?>>YATIRIM</option>
                <option _ngcontent-gdo-c54="" value="WITHDRAW" class="ng-star-inserted" <?= $transactionType === 'WITHDRAW' ? 'selected' : '' ?>>ÇEKİM</option>
            </select>
        </div>
        <div _ngcontent-gdo-c54="" class="form-group ng-star-inserted">
            <label _ngcontent-gdo-c54="" class="col-form-label">Durum</label>
            <select name="status" _ngcontent-gdo-c54="" class="form-control form-control-sm">
                <option _ngcontent-gdo-c54="" value="ALL" class="ng-star-inserted" <?= $status === 'ALL' ? 'selected' : '' ?>>HEPSİ</option>
                <option _ngcontent-gdo-c54="" value="PENDING" class="ng-star-inserted" <?= $status === 'PENDING' ? 'selected' : '' ?>>İŞLEMDE</option>
                <option _ngcontent-gdo-c54="" value="APPROVED" class="ng-star-inserted" <?= $status === 'APPROVED' ? 'selected' : '' ?>>ONAYLANDI</option>
                <option _ngcontent-gdo-c54="" value="REJECTED" class="ng-star-inserted" <?= $status === 'REJECTED' ? 'selected' : '' ?>>REDDEDİLDİ</option>
            </select>
        </div>
        
    </form>
    <script>
    document.addEventListener('DOMContentLoaded', function(){
        var form = document.querySelector('.tableFilter form#filterForm');
        if(!form) return;
        var selects = form.querySelectorAll('select[name="transactionType"], select[name="status"]');
        selects.forEach(function(sel){ sel.addEventListener('change', function(){ form.submit(); }); });
    });
    </script>
</div>

<div _ngcontent-gdo-c54="" class="col-12">
    <div _ngcontent-gdo-c54="" class="table-responsive mt-2 mt-lg-4">
        <style>
            .statement-wrapper { 
                width: 100%; 
                margin: 0; 
                max-width: none;
            }
            .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: 12px; font-weight: 600; letter-spacing: .2px;
                color: var(--white-color); background: var(--primary);
                padding: 8px 12px; white-space: nowrap;
            }
            .statement-table tbody td {
                font-size: 12px; color: var(--white-color); padding: 8px 12px; 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-pending { background: var(--primary-rgb3); color: var(--primary); }
            .chip-approved { background: rgba(34,197,94,.15); color: #22c55e; border-color: rgba(34,197,94,.35); }
            .chip-rejected { background: rgba(239,68,68,.15); color: #ef4444; border-color: rgba(239,68,68,.35); }
            .col-type{ width:18%; }
            .col-date{ width:34%; }
            .col-amount{ width:28%; }
            .col-status{ width:20%; }
            
            /* Responsive table container */
            .table-responsive {
                width: 100%;
                overflow-x: auto;
                margin: 0 0 24px 0;
                padding: 0 0 24px 0;
                background:#000;
            }
            
            /* Full width container */
            .col-12 {
                width: 100%;
                padding: 0;
                margin: 0;
            }
        </style>
        <div _ngcontent-gdo-c54="" class="statement-wrapper">
            <table _ngcontent-gdo-c54="" class="statement-table">
                <thead>
                    <tr>
                        <th class="col-type">Tür</th>
                        <th class="col-date">Tarih</th>
                        <th class="col-amount text-right">Tutar</th>
                        <th class="col-status">Durum</th>
                        <th class="col-status">Açıklama</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($records)): ?>
                        <tr>
                            <td class="dataTables_empty border-0" colspan="5" valign="top">
                                <h6 class="nodatafound mt-5 pt-5">Gösterilecek kayıt bulunamadı</h6>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($records as $record): ?>
                            <tr>
                                <td><?= htmlspecialchars($record['__type'] ?? ($transactionType === 'DEPOSIT' ? 'Yatırım' : ($transactionType === 'WITHDRAW' ? 'Çekim' : ''))); ?></td>
                                <td><?= htmlspecialchars(date('m-d H:i', strtotime($record['tarih']))); ?></td>
                                <td class="text-right"><?php $amount = isset($record['miktar']) ? (float)$record['miktar'] : 0; echo number_format($amount, 2, ',', '.'); echo ' ₺'; ?></td>
                                <td>
                                    <?php
                                        switch ($record['durum']) {
                                            case 0: echo '<span class="chip chip-pending">İşlemde</span>'; break;
                                            case 1: echo '<span class="chip chip-approved">Onay.</span>'; break;
                                            case 2: echo '<span class="chip chip-rejected">Redd.</span>'; break;
                                        }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        $desc = isset($record['aciklama']) ? trim($record['aciklama']) : '';
                                        if ((int)$record['durum'] === 2 && $desc !== '') {
                                            echo htmlspecialchars($desc);
                                        } else {
                                            echo '-';
                                        }
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
                </div>




                    </div>
                </div>