<?php
session_start();
include 'config.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: index.php");
    exit;
}

// betleri çekiyoruz
$stmt = $pdo->query("SELECT * FROM bets ORDER BY username, bet_description");
$bets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Kullanıcı betsini gruplamak
$groupedBets = [];
foreach ($bets as $bahis) {
    $groupedBets[$bahis['username']][$bahis['bet_description']][] = $bahis;
}

// Maç durumu veya grup işlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['match_id']) && isset($_POST['match_action'])) {
        // Tekli maç için durum güncellemesi
        $matchId = $_POST['match_id'];
        $action = $_POST['match_action'];

        // Tekli maç durumu güncelleniyor
        $stmt = $pdo->prepare("UPDATE bets SET status = :status WHERE id = :id");
        $stmt->execute(['status' => $action, 'id' => $matchId]);
    } elseif (isset($_POST['username']) && isset($_POST['bet_description']) && isset($_POST['group_action'])) {
        // Grup seviyesi işlem (Kazandı -> bakiye ekleme)
        $username = $_POST['username'];
        $betType = $_POST['bet_description'];
        $action = $_POST['group_action'];

        if ($action === 'Kazandı') {
            // Kullanıcıya ait tüm bahislerin "Kazandı" olup olmadığını kontrol et
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM bets WHERE username = :username AND bet_description = :bet_description AND status != 'Kazandı' AND group_status IS NULL");
            $stmt->execute(['username' => $username, 'bet_description' => $betType]);
            $pendingCount = $stmt->fetchColumn();

            if ($pendingCount == 0) {
                // Potansiyel kazançları toplama
                $stmt = $pdo->prepare("SELECT SUM(potential_winnings) AS total_winnings FROM bets WHERE username = :username AND bet_description = :bet_description");
                $stmt->execute(['username' => $username, 'bet_description' => $betType]);
                $totalWinnings = $stmt->fetchColumn();

                // Kullanıcı bakiyesine ekleme
                $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye + :total_winnings WHERE username = :username");
                $stmt->execute(['total_winnings' => $totalWinnings, 'username' => $username]);

                // Grup durumu güncelleme
                $stmt = $pdo->prepare("UPDATE bets SET group_status = 'Kazandı' WHERE username = :username AND bet_description = :bet_description AND group_status IS NULL");
                $stmt->execute(['username' => $username, 'bet_description' => $betType]);
            }
        } elseif ($action === 'Kaybetti') {
            // Grup kontrolü: Eğer bir bahis Kaybetti olarak işaretlendiyse, grup kaybetti yapılacak
            $stmt = $pdo->prepare("UPDATE bets SET group_status = 'Kaybetti' WHERE username = :username AND bet_description = :bet_description AND group_status IS NULL");
            $stmt->execute(['username' => $username, 'bet_description' => $betType]);

            // Eğer grup kaybetti olarak işaretlendiyse, o gruptaki bahisler admin panelinde gizlenecek
            $stmt = $pdo->prepare("UPDATE bets SET group_status = 'Kaybetti' WHERE username = :username AND bet_description = :bet_description");
            $stmt->execute(['username' => $username, 'bet_description' => $betType]);
        }
    }

    header("Location: bahis.php"); // Sayfayı yenile
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bahis Yönetimi</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 mt-5">
        <div class="d-flex justify-content-between mb-4">
            <h2 class="text-warning">Bahis Yönetimi</h2>
            <a href="index.php" class="back-to-home d-flex align-items-center">
                <i class="bi bi-house-door-fill me-2"></i> Ana Sayfaya Dön
            </a>
        </div>

        <!-- Araç Çubuğu: Hızlı Arama, Sütun Görünürlüğü (tüm tablolara), 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="bahisToolbar">
            <input type="text" class="form-control" id="quickSearchBahis" placeholder="Hızlı arama..." style="max-width: 260px;">
            <div class="dropdown">
                <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="columnToggleBahis" data-bs-toggle="dropdown" aria-expanded="false">
                    Sütun Görünürlüğü
                </button>
                <ul class="dropdown-menu p-2" aria-labelledby="columnToggleBahis" id="columnListBahis" style="min-width: 240px;"></ul>
            </div>
            <button class="btn btn-outline-primary" id="saveViewBahis">Görünümü Kaydet</button>
            <button class="btn btn-outline-primary" id="loadViewBahis">Görünümü Yükle</button>
            <button class="btn btn-outline-success" id="exportCsvBahis">CSV Dışa Aktar</button>
        </div>

        <!-- Hata veya Başarı Mesajları -->
        <?php if (isset($errorMessage)): ?>
            <div class="alert <?= strpos($errorMessage, 'kazandı') !== false ? 'alert-success' : 'alert-danger'; ?>" role="alert">
                <?= htmlspecialchars($errorMessage) ?>
            </div>
        <?php endif; ?>

        <?php foreach ($groupedBets as $username => $betsByType): ?>
            <?php
                // Eğer tüm grup bahisleri "Kazandı" veya "Kaybetti" ise, kullanıcıyı gizle
                $hasActiveBets = false;
                foreach ($betsByType as $betType => $bets) {
                    foreach ($bets as $bet) {
                        if ($bet['group_status'] !== 'Kazandı' && $bet['group_status'] !== 'Kaybetti') {
                            $hasActiveBets = true;
                            break 2; // Eğer aktif bahis varsa, kullanıcıyı göstereceğiz
                        }
                    }
                }

                // Eğer aktif bahis yoksa, kullanıcıyı gizle
                if (!$hasActiveBets) {
                    continue;
                }
            ?>

            <div class="user-container mb-4">
                <h4 class="text-primary">Kullanıcı: <?= htmlspecialchars($username) ?></h4>

                <?php foreach ($betsByType as $betType => $bets): ?>
                    <div class="bet-container mb-3 p-3">
                        <h5 class="text-success"><?= htmlspecialchars($betType) ?></h5>
                        <div class="match-area">
                           <table class="table table-striped">
    <thead>
        <tr>
            <th>ID</th>
            <th>Etkinlik</th>
            <th>Oran</th>
            <th>Miktar</th>
            <th>Olası Kazanç</th>
            <th>Durum</th>
            <th>Seçilen Oran</th>
            <th>Pazar</th>
            <th>Etkinlik Tarihi</th>
            <th>Bahis Tarihi</th>
            <th>İşlem</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($bets as $bet): ?>
            <?php if ($bet['group_status'] == 'Kaybetti' || $bet['group_status'] == 'Kazandı') continue; ?>
            <tr>
                <td><?= htmlspecialchars($bet['id']) ?></td>
                <td><?= htmlspecialchars($bet['event_name']) ?></td>
                <td><?= htmlspecialchars($bet['odd_value']) ?></td>
                <td><?= htmlspecialchars($bet['stake_amount']) ?></td>
                <td><?= htmlspecialchars($bet['potential_winnings']) ?></td>
                <td><?= htmlspecialchars($bet['status']) ?></td>
                <td><?= htmlspecialchars($bet['selected_odd_label']) ?></td>
                <td><?= htmlspecialchars($bet['market_name']) ?></td>
                <td><?= htmlspecialchars($bet['event_date']) ?></td>
                <td><?= htmlspecialchars($bet['bet_date']) ?></td>
                <td>
                    <form method="post" class="d-inline">
                        <input type="hidden" name="match_id" value="<?= htmlspecialchars($bet['id']) ?>">
                        <button type="submit" name="match_action" value="Kazandı" class="btn btn-success btn-sm">Kazandı</button>
                        <button type="submit" name="match_action" value="Kaybetti" class="btn btn-danger btn-sm">Kaybetti</button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

                        </div>

                        <!-- Grup Kazandı / Kaybetti Butonları -->
                        <form method="post" class="d-flex justify-content-end mt-2">
                            <input type="hidden" name="username" value="<?= htmlspecialchars($username) ?>">
                            <input type="hidden" name="bet_description" value="<?= htmlspecialchars($betType) ?>">

                            <?php 
                            // Grup durumu kontrolü
                            $groupLost = false;
                            $allWon = true; // Varsayılan olarak grup "Kazandı" kabul edilir

                            foreach ($bets as $bet) {
                                if ($bet['status'] === 'Kaybetti') {
                                    $groupLost = true;
                                    $allWon = false;
                                    break;
                                }
                            }
                            ?>

                            <!-- Eğer grup bahislerinde "Kaybetti" varsa, Grup Kazandı butonu devre dışı bırakılacak -->
                            <button type="submit" name="group_action" value="Kazandı" class="btn btn-primary me-2" <?= $groupLost ? 'disabled' : '' ?> <?= !$allWon ? 'disabled' : '' ?>>
                                Grup Kazandı
                            </button>
                            <button type="submit" name="group_action" value="Kaybetti" class="btn btn-secondary" <?= !$allWon ? 'disabled' : '' ?> <?= $groupLost ? 'disabled' : '' ?> >
                                Grup Kaybetti
                            </button>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    (function() {
        const pageKey = 'bahis';
        const tables = Array.from(document.querySelectorAll('.match-area table'));
        if (!tables.length) return;

        const quickSearch = document.getElementById('quickSearchBahis');
        const columnList = document.getElementById('columnListBahis');
        const saveBtn = document.getElementById('saveViewBahis');
        const loadBtn = document.getElementById('loadViewBahis');
        const exportBtn = document.getElementById('exportCsvBahis');

        // İlk tablodan sütun yapısını al ve kontrol listesini oluştur
        const refHeaders = Array.from(tables[0].querySelectorAll('thead th'));
        refHeaders.forEach((th, idx) => {
            const li = document.createElement('li');
            li.className = 'dropdown-item';
            const id = `bahis-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) {
            tables.forEach(tbl => {
                const heads = Array.from(tbl.querySelectorAll('thead th'));
                const rows = Array.from(tbl.querySelectorAll('tbody tr'));
                if (heads[colIndex]) heads[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 tüm tablolara uygula
        quickSearch.addEventListener('input', () => {
            const q = quickSearch.value.toLowerCase();
            tables.forEach(tbl => {
                const rows = Array.from(tbl.querySelectorAll('tbody tr'));
                rows.forEach(tr => {
                    const txt = tr.textContent.toLowerCase();
                    tr.style.display = txt.includes(q) ? '' : 'none';
                });
            });
        });

        // Görünüm kaydet/yükle
        function getViewState() {
            const columns = refHeaders.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));
            // Checkbox'ları güncelle
            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 (tüm tablolardan birleşik)
        exportBtn.addEventListener('click', () => {
            const visibleCols = refHeaders.map((h, i) => ({ i, txt: h.textContent.trim() })).filter(c => refHeaders[c.i].style.display !== 'none');
            const lines = [];
            lines.push(visibleCols.map(c => '"' + c.txt.replace(/"/g, '""') + '"').join(','));
            tables.forEach(tbl => {
                const rows = Array.from(tbl.querySelectorAll('tbody tr'));
                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_listesi.csv';
            a.click();
            URL.revokeObjectURL(url);
        });
    })();
    </script>
