<?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;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());
}

// Sayfalama parametreleri
$recordsPerPage = 10; // Sayfa başına gösterilecek kayıt sayısı
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $recordsPerPage;

// Toplam kayıt sayısını bulma
$totalRecordsStmt = $pdo->query("SELECT COUNT(*) FROM transactions");
$totalRecords = $totalRecordsStmt->fetchColumn();
$totalPages = ceil($totalRecords / $recordsPerPage);

// Bahis geçmişini çekme
$stmt = $pdo->prepare("
    SELECT 
        t.id, 
        t.user_id, 
        t.amount, 
        t.type, 
        t.created_at, 
        g.game_name, 
        g.provider_game, 
        u.username
    FROM transactions t
    LEFT JOIN games g ON t.game = g.game_code
    LEFT JOIN kullanicilar u ON t.user_id = u.id
    ORDER BY t.created_at DESC
    LIMIT :limit OFFSET :offset
");
$stmt->bindValue(':limit', $recordsPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();

$betHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Sayfa aralığını hesaplama
$maxVisiblePages = 5; // Aynı anda gösterilecek maksimum sayfa sayısı
$startPage = max(1, $page - intval($maxVisiblePages / 2));
$endPage = min($totalPages, $startPage + $maxVisiblePages - 1);

if ($endPage - $startPage + 1 < $maxVisiblePages) {
    $startPage = max(1, $endPage - $maxVisiblePages + 1);
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bahis Geçmişi</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">

</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <div class="col-md-10 p-4">
    <div class="container">
        <h1 class="text-center text-primary mt-4">Bahis Geçmişi</h1>
        <!-- Araç Çubuğu: Hızlı Arama, Sütun Görünürlüğü, Görünüm Kaydet/Yükle, CSV Dışa Aktar -->
        <div class="d-flex flex-wrap align-items-center gap-2 mb-3" id="gecmisToolbar">
            <input type="text" class="form-control" id="quickSearchGecmis" placeholder="Hızlı arama..." style="max-width: 240px;">
            <div class="dropdown">
                <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="columnToggleGecmis" data-bs-toggle="dropdown" aria-expanded="false">
                    Sütun Görünürlüğü
                </button>
                <ul class="dropdown-menu p-2" aria-labelledby="columnToggleGecmis" id="columnListGecmis" style="min-width: 220px;"></ul>
            </div>
            <button class="btn btn-outline-primary" id="saveViewGecmis">Görünümü Kaydet</button>
            <button class="btn btn-outline-primary" id="loadViewGecmis">Görünümü Yükle</button>
            <button class="btn btn-outline-success" id="exportCsvGecmis">CSV Dışa Aktar</button>
        </div>
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Kullanıcı</th>
                        <th>Tutar</th>
                        <th>Oyun</th>
                        <th>Sağlayıcı</th>
                        <th>Tarih</th>
                        <th>Tür</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($betHistory)): ?>
                        <?php foreach ($betHistory as $bet): ?>
                            <tr>
                                <td><?= htmlspecialchars($bet['id']) ?></td>
                                <td><?= htmlspecialchars($bet['username']) ?></td>
                                <td><?= htmlspecialchars($bet['amount']) ?></td>
                                <td><?= htmlspecialchars($bet['game_name'] ?: 'Bilinmiyor') ?></td>
                                <td><?= htmlspecialchars($bet['provider_game'] ?: 'Bilinmiyor') ?></td>
                                <td><?= htmlspecialchars($bet['created_at']) ?></td>
                                <td><?= htmlspecialchars($bet['type']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center">Kayıt bulunamadı.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Sayfalama -->
        <nav>
            <ul class="pagination">
                <!-- İlk Sayfa -->
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=1">&laquo; İlk</a>
                    </li>
                <?php endif; ?>

                <!-- Önceki Sayfa -->
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?= $page - 1 ?>">&lsaquo; Önceki</a>
                    </li>
                <?php endif; ?>

                <!-- Sayfa Aralıkları -->
                <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>

                <!-- Sonraki Sayfa -->
                <?php if ($page < $totalPages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?= $page + 1 ?>">Sonraki &rsaquo;</a>
                    </li>
                <?php endif; ?>

                <!-- Son Sayfa -->
                <?php if ($page < $totalPages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?= $totalPages ?>">Son &raquo;</a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    (function() {
        const table = document.querySelector('.table.table-striped.table-bordered');
        if (!table) return;
        const pageKey = 'gecmis';
        const quickSearch = document.getElementById('quickSearchGecmis');
        const columnList = document.getElementById('columnListGecmis');
        const saveBtn = document.getElementById('saveViewGecmis');
        const loadBtn = document.getElementById('loadViewGecmis');
        const exportBtn = document.getElementById('exportCsvGecmis');

        const headers = Array.from(table.querySelectorAll('thead th'));
        const rows = Array.from(table.querySelectorAll('tbody tr'));

        // Sütun listesi
        headers.forEach((th, idx) => {
            const li = document.createElement('li');
            li.className = 'dropdown-item';
            const id = `gecmis-col-${idx}`;
            li.innerHTML = `<div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"${id}\" data-col-index=\"${idx}\" checked><label class=\"form-check-label\" for=\"${id}\">${th.textContent.trim()}</label></div>`;
            columnList.appendChild(li);
        });

        function setColumnVisible(colIndex, visible) {
            headers[colIndex].style.display = visible ? '' : 'none';
            rows.forEach(tr => {
                const cells = tr.children;
                if (cells[colIndex]) cells[colIndex].style.display = visible ? '' : 'none';
            });
        }

        columnList.addEventListener('change', (e) => {
            const input = e.target.closest('input[data-col-index]');
            if (!input) return;
            const idx = parseInt(input.dataset.colIndex, 10);
            setColumnVisible(idx, input.checked);
        });

        // Hızlı arama
        quickSearch.addEventListener('input', () => {
            const q = quickSearch.value.toLowerCase();
            rows.forEach(tr => {
                const text = tr.textContent.toLowerCase();
                tr.style.display = text.includes(q) ? '' : 'none';
            });
        });

        // Görünüm kaydet/yükle
        function getViewState() {
            const columns = headers.map((th, idx) => ({ name: th.textContent.trim(), visible: th.style.display !== 'none', idx }));
            return { columns };
        }
        function applyViewState(state) {
            if (!state || !state.columns) return;
            state.columns.forEach(col => setColumnVisible(col.idx, col.visible));
            // Checkboxlar
            columnList.querySelectorAll('input[data-col-index]').forEach(input => {
                const col = state.columns.find(c => c.idx === parseInt(input.dataset.colIndex, 10));
                if (col) input.checked = col.visible;
            });
        }
        saveBtn.addEventListener('click', () => {
            localStorage.setItem('tableView_' + pageKey, JSON.stringify(getViewState()));
            saveBtn.textContent = 'Kaydedildi';
            setTimeout(() => saveBtn.textContent = 'Görünümü Kaydet', 1200);
        });
        loadBtn.addEventListener('click', () => {
            const raw = localStorage.getItem('tableView_' + pageKey);
            if (!raw) return;
            try { applyViewState(JSON.parse(raw)); } catch (e) {}
        });

        // CSV dışa aktar
        exportBtn.addEventListener('click', () => {
            const visibleCols = headers.map((h, i) => ({ i, txt: h.textContent.trim() })).filter(c => headers[c.i].style.display !== 'none');
            const lines = [];
            lines.push(visibleCols.map(c => '"' + c.txt.replace(/"/g, '""') + '"').join(','));
            rows.forEach(tr => {
                if (tr.style.display === 'none') return; // Filtrelenenleri atla
                const cells = Array.from(tr.children);
                const vals = visibleCols.map(c => cells[c.i] ? cells[c.i].innerText.trim() : '');
                lines.push(vals.map(v => '"' + v.replace(/"/g, '""') + '"').join(','));
            });
            const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'bahis_gecmisi.csv';
            a.click();
            URL.revokeObjectURL(url);
        });
    })();
    </script>
            </div>
        </div>
    </div>
</body>
</html>
