<?php
session_start();
require_once __DIR__ . '/auth.php';
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/logger.php';

$today = date('Y-m-d');
$defaultStart = date('Y-m-d', strtotime('-30 days'));
$start = isset($_GET['start']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['start']) ? $_GET['start'] : $defaultStart;
$end = isset($_GET['end']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['end']) ? $_GET['end'] : $today;

$txnTotals = $gameTotals = $betsTotals = [];
$txnError = $betsError = '';

// Sunucu tarafı CSV/XLSX export (RBAC: reports_export)
try {
    $export = isset($_GET['export']) ? strtolower(trim($_GET['export'])) : '';
    $etype = isset($_GET['type']) ? strtolower(trim($_GET['type'])) : '';
    if ($export && in_array($export, ['csv','xlsx'], true) && in_array($etype, ['txn','game','bets'], true)) {
        require_permission('reports_export');
        // Veri sorguları
        if ($etype === 'txn') {
            $stmt = $pdo->prepare("SELECT type AS label, COUNT(*) AS cnt, SUM(amount) AS total FROM transactions WHERE DATE(created_at) BETWEEN :start AND :end GROUP BY type ORDER BY total DESC");
            $stmt->execute(['start' => $start, 'end' => $end]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $filenameBase = 'rapor_casino_turleri_' . $start . '_to_' . $end;
            $headers = ['Tür','Adet','Toplam Tutar'];
            $mapRow = function($r){ return [ $r['label'] ?? '-', (int)$r['cnt'], (float)$r['total'] ]; };
        } elseif ($etype === 'game') {
            $stmt = $pdo->prepare("SELECT COALESCE(g.game_name, t.game) AS label, COUNT(*) AS cnt, SUM(amount) AS total FROM transactions t LEFT JOIN games g ON t.game = g.game_code WHERE DATE(t.created_at) BETWEEN :start AND :end GROUP BY COALESCE(g.game_name, t.game) ORDER BY cnt DESC");
            $stmt->execute(['start' => $start, 'end' => $end]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $filenameBase = 'rapor_casino_oyunlari_' . $start . '_to_' . $end;
            $headers = ['Oyun','Adet','Toplam Tutar'];
            $mapRow = function($r){ return [ $r['label'] ?: 'Bilinmiyor', (int)$r['cnt'], (float)$r['total'] ]; };
        } else { // bets
            $stmt = $pdo->prepare("SELECT status AS label, COUNT(*) AS cnt, SUM(stake_amount) AS stake_sum, SUM(potential_winnings) AS win_sum FROM bets WHERE DATE(bet_date) BETWEEN :start AND :end GROUP BY status ORDER BY cnt DESC");
            $stmt->execute(['start' => $start, 'end' => $end]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $filenameBase = 'rapor_bahis_ozet_' . $start . '_to_' . $end;
            $headers = ['Durum','Adet','Toplam Miktar','Potansiyel Kazanç'];
            $mapRow = function($r){ return [ $r['label'] ?? '-', (int)$r['cnt'], (float)$r['stake_sum'], (float)$r['win_sum'] ]; };
        }

        // Logla
        event_log('export', 'reports_export', ['type' => $etype, 'format' => $export, 'start' => $start, 'end' => $end, 'rows' => count($rows)]);

        if ($export === 'csv') {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filenameBase . '.csv"');
            $out = fopen('php://output', 'w');
            fputcsv($out, $headers);
            foreach ($rows as $r) {
                fputcsv($out, $mapRow($r));
            }
            fclose($out);
            exit;
        } else { // xlsx (Excel 2003 XML)
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment; filename="' . $filenameBase . '.xls"');
            echo "<?xml version=\"1.0\"?>\n";
            echo "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
            echo "<Worksheet ss:Name=\"Rapor\"><Table>";
            echo "<Row>"; foreach ($headers as $h) { echo "<Cell><Data ss:Type=\"String\">".htmlspecialchars($h)."</Data></Cell>"; } echo "</Row>";
            foreach ($rows as $r) {
                $data = $mapRow($r);
                echo "<Row>";
                foreach ($data as $i => $val) {
                    $type = is_numeric($val) ? 'Number' : 'String';
                    echo "<Cell><Data ss:Type=\"$type\">".htmlspecialchars((string)$val)."</Data></Cell>";
                }
                echo "</Row>";
            }
            echo "</Table></Worksheet></Workbook>";
            exit;
        }
    }
} catch (Throwable $e) {
    // Export hatası kullanıcıya düzgün iletilsin
    header('Content-Type: text/plain; charset=utf-8');
    http_response_code(500);
    echo 'Export hata: ' . htmlspecialchars($e->getMessage());
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT type, COUNT(*) cnt, SUM(amount) total FROM transactions WHERE DATE(created_at) BETWEEN :start AND :end GROUP BY type ORDER BY total DESC");
    $stmt->execute(['start' => $start, 'end' => $end]);
    $txnTotals = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("SELECT COALESCE(g.game_name, t.game) game_name, COUNT(*) cnt, SUM(amount) total FROM transactions t LEFT JOIN games g ON t.game = g.game_code WHERE DATE(t.created_at) BETWEEN :start AND :end GROUP BY COALESCE(g.game_name, t.game) ORDER BY cnt DESC");
    $stmt->execute(['start' => $start, 'end' => $end]);
    $gameTotals = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $txnError = $e->getMessage(); }

try {
    $stmt = $pdo->prepare("SELECT status, COUNT(*) cnt, SUM(stake_amount) stake_sum, SUM(potential_winnings) win_sum FROM bets WHERE DATE(bet_date) BETWEEN :start AND :end GROUP BY status ORDER BY cnt DESC");
    $stmt->execute(['start' => $start, 'end' => $end]);
    $betsTotals = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $betsError = $e->getMessage(); }
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>İşlem Raporları</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">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <?php include __DIR__ . '/sidebar.php'; ?>
        <div class="col-md-10 p-4">
            <?php include __DIR__ . '/topbar.php'; ?>
            <div class="d-flex align-items-center justify-content-between mb-3">
                <div>
                    <h1>İşlem Raporları</h1>
                    <p class="text-muted">Tarih aralığına göre Casino ve Bahis özetleri.</p>
                </div>
                <form class="d-flex gap-2 align-items-end" method="GET" action="reports.php" id="filterForm">
                    <input type="date" name="start" class="form-control" value="<?= htmlspecialchars($start) ?>">
                    <input type="date" name="end" class="form-control" value="<?= htmlspecialchars($end) ?>">
                    <button type="submit" class="btn btn-primary">Filtrele</button>
                    <div class="btn-group ms-2">
                        <button type="button" class="btn btn-outline-dark" data-preset="7">Son 7 Gün</button>
                        <button type="button" class="btn btn-outline-dark" data-preset="30">Son 30 Gün</button>
                        <button type="button" class="btn btn-outline-dark" data-preset="mtd">Bu Ay</button>
                        <button type="button" class="btn btn-outline-dark" data-preset="ytd">Bu Yıl</button>
                    </div>
                    <button type="button" class="btn btn-secondary ms-2" id="printBtn"><i class="bi bi-printer"></i> Yazdır</button>
                    <div class="btn-group ms-2" role="group" aria-label="Sunucu Export">
                        <a class="btn btn-outline-success" href="reports.php?start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>&type=txn&export=csv">Casino Türleri CSV</a>
                        <a class="btn btn-outline-success" href="reports.php?start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>&type=txn&export=xlsx">Casino Türleri XLSX</a>
                        <a class="btn btn-outline-primary" href="reports.php?start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>&type=game&export=csv">Oyunlar CSV</a>
                        <a class="btn btn-outline-primary" href="reports.php?start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>&type=game&export=xlsx">Oyunlar XLSX</a>
                        <a class="btn btn-outline-dark" href="reports.php?start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>&type=bets&export=csv">Bahisler CSV</a>
                        <a class="btn btn-outline-dark" href="reports.php?start=<?= urlencode($start) ?>&end=<?= urlencode($end) ?>&type=bets&export=xlsx">Bahisler XLSX</a>
                    </div>
                </form>
            </div>

            <?php
              $txn_sum = 0; $txn_count = 0; foreach($txnTotals as $r){ $txn_sum += (float)($r['total'] ?? 0); $txn_count += (int)($r['cnt'] ?? 0); }
              $bet_sum = 0; $bet_win = 0; foreach($betsTotals as $b){ $bet_sum += (float)($b['stake_sum'] ?? 0); $bet_win += (float)($b['win_sum'] ?? 0); }
              $profit = $bet_win - $bet_sum;
              $dateBadge = '';
              if(!empty($start) || !empty($end)){
                $dateBadge = "<span class='badge bg-dark'>Tarih: ".htmlspecialchars($start)." → ".htmlspecialchars($end)."</span>";
              }
            ?>
            <div class="row g-3 mb-3">
              <div class="col-md-3"><div class="card bg-dark text-white"><div class="card-body"><div class="small">Toplam İşlem</div><div class="fs-5">₺<?= number_format($txn_sum,2,',','.') ?></div><div class="text-muted">Adet: <?= $txn_count ?></div></div></div></div>
              <div class="col-md-3"><div class="card bg-dark text-white"><div class="card-body"><div class="small">Toplam Bahis</div><div class="fs-5">₺<?= number_format($bet_sum,2,',','.') ?></div><div class="text-muted">Kazanç: ₺<?= number_format($bet_win,2,',','.') ?></div></div></div></div>
              <div class="col-md-3"><div class="card bg-dark text-white"><div class="card-body"><div class="small">Kâr/Zarar</div><div class="fs-5">₺<?= number_format($profit,2,',','.') ?></div><div class="text-muted">(Kazanç − Bahis)</div></div></div></div>
              <div class="col-md-3"><div class="card bg-dark text-white"><div class="card-body"><div class="small">Aktif Filtre</div><div class="fs-6"><?= $dateBadge ?: '<span class="text-muted">—</span>' ?></div></div></div></div>
            </div>

            <div class="card mb-4">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <h5 class="card-title mb-0">Casino İşlem Türleri</h5>
                        <div class="d-flex gap-2">
                            <input type="text" class="form-control" id="searchTxn" placeholder="Ara..." style="max-width: 220px;">
                            <button class="btn btn-outline-success" id="csvTxn">CSV</button>
                        </div>
                    </div>
                    <?php if ($txnError): ?><div class="alert alert-danger mt-2">Hata: <?= htmlspecialchars($txnError) ?></div><?php endif; ?>
                    <div class="table-responsive mt-2">
                        <table class="table table-sm table-striped table-sticky" id="txnTable">
                            <thead><tr><th>Tür</th><th>Adet</th><th>Toplam Tutar</th></tr></thead>
                            <tbody>
                            <?php foreach ($txnTotals as $r): ?>
                                <tr>
                                    <td><?= htmlspecialchars($r['type'] ?? '-') ?></td>
                                    <td><?= (int)$r['cnt'] ?></td>
                                    <td><?= number_format((float)$r['total'], 2) ?> ₺</td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                            <tfoot><tr><th>Toplam</th><th id="txnCntFoot">0</th><th id="txnSumFoot">0 ₺</th></tr></tfoot>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <h5 class="card-title mb-0">Oyun Bazlı Casino İşlemleri</h5>
                        <div class="d-flex gap-2">
                            <input type="text" class="form-control" id="searchGame" placeholder="Ara..." style="max-width: 220px;">
                            <button class="btn btn-outline-success" id="csvGame">CSV</button>
                        </div>
                    </div>
                    <div class="table-responsive mt-2">
                        <table class="table table-sm table-striped table-sticky" id="gameTable">
                            <thead><tr><th>Oyun</th><th>Adet</th><th>Toplam Tutar</th></tr></thead>
                            <tbody>
                            <?php foreach ($gameTotals as $g): ?>
                                <tr>
                                    <td><?= htmlspecialchars($g['game_name'] ?: 'Bilinmiyor') ?></td>
                                    <td><?= (int)$g['cnt'] ?></td>
                                    <td><?= number_format((float)$g['total'], 2) ?> ₺</td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                            <tfoot><tr><th>Toplam</th><th id="gameCntFoot">0</th><th id="gameSumFoot">0 ₺</th></tr></tfoot>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-body">
                    <div class="d-flex align-items-center justify-content-between">
                        <h5 class="card-title mb-0">Bahis Durumlarına Göre Özet</h5>
                        <div class="d-flex gap-2">
                            <input type="text" class="form-control" id="searchBets" placeholder="Ara..." style="max-width: 220px;">
                            <button class="btn btn-outline-success" id="csvBets">CSV</button>
                        </div>
                    </div>
                    <?php if ($betsError): ?><div class="alert alert-danger mt-2">Hata: <?= htmlspecialchars($betsError) ?></div><?php endif; ?>
                    <div class="table-responsive mt-2">
                        <table class="table table-sm table-striped table-sticky" id="betsTable">
                            <thead><tr><th>Durum</th><th>Adet</th><th>Toplam Miktar</th><th>Potansiyel Kazanç</th></tr></thead>
                            <tbody>
                            <?php foreach ($betsTotals as $b): ?>
                                <tr>
                                    <td><?= htmlspecialchars($b['status'] ?? '-') ?></td>
                                    <td><?= (int)$b['cnt'] ?></td>
                                    <td><?= number_format((float)$b['stake_sum'], 2) ?> ₺</td>
                                    <td><?= number_format((float)$b['win_sum'], 2) ?> ₺</td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                            <tfoot><tr><th>Toplam</th><th id="betsCntFoot">0</th><th id="betsStakeFoot">0 ₺</th><th id="betsWinFoot">0 ₺</th></tr></tfoot>
                        </table>
                    </div>
                </div>
            </div>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function setupSearch(inputId, tableId){
  const inp=document.getElementById(inputId); const rows=[...document.querySelectorAll(`#${tableId} tbody tr`)];
  inp.addEventListener('input',()=>{const q=inp.value.toLowerCase(); rows.forEach(r=>{r.style.display = q? (r.textContent.toLowerCase().includes(q)?'':'none'):'';});});
}
function exportCsv(btnId, tableId, name){
  document.getElementById(btnId).addEventListener('click',()=>{
    const t=document.getElementById(tableId); const headers=[...t.querySelectorAll('thead th')].map(h=>`"${h.textContent.trim().replace(/"/g,'""')}"`).join(',');
    const rows=[...t.querySelectorAll('tbody tr')].filter(r=>r.style.display!=='none').map(r=>[...r.children].map(td=>`"${td.textContent.trim().replace(/"/g,'""')}"`).join(',')).join('\n');
    const csv=headers+'\n'+rows; const blob=new Blob([csv],{type:'text/csv;charset=utf-8;'}); const url=URL.createObjectURL(blob);
    const a=document.createElement('a'); a.href=url; a.download=name+'.csv'; a.click(); URL.revokeObjectURL(url);
  });
}
setupSearch('searchTxn','txnTable'); exportCsv('csvTxn','txnTable','casino_turleri');
setupSearch('searchGame','gameTable'); exportCsv('csvGame','gameTable','casino_oyunlari');
setupSearch('searchBets','betsTable'); exportCsv('csvBets','betsTable','bahis_ozet');
// Görünen satırlara göre toplamları hesapla
function recalcFoot(tableId, colIdxs){
  const t=document.getElementById(tableId); if(!t) return;
  const rows=[...t.querySelectorAll('tbody tr')].filter(r=>r.style.display!=='none');
  const sums = colIdxs.map(()=>0);
  rows.forEach(r=>{
    colIdxs.forEach((ci,k)=>{
      const cell=r.children[ci]; if(!cell) return;
      const num=parseFloat((cell.textContent||'').replace(/[^0-9.-]/g,'')); if(!isNaN(num)) sums[k]+=num;
    });
  });
  // Yaz
  if(tableId==='txnTable'){ document.getElementById('txnCntFoot').textContent = rows.reduce((a,r)=> a + (parseInt(r.children[1].textContent)||0), 0); document.getElementById('txnSumFoot').textContent = (sums[0]||0).toLocaleString('tr-TR', {minimumFractionDigits:2}) + ' ₺'; }
  if(tableId==='gameTable'){ document.getElementById('gameCntFoot').textContent = rows.reduce((a,r)=> a + (parseInt(r.children[1].textContent)||0), 0); document.getElementById('gameSumFoot').textContent = (sums[0]||0).toLocaleString('tr-TR', {minimumFractionDigits:2}) + ' ₺'; }
  if(tableId==='betsTable'){ document.getElementById('betsCntFoot').textContent = rows.reduce((a,r)=> a + (parseInt(r.children[1].textContent)||0), 0); document.getElementById('betsStakeFoot').textContent = (sums[0]||0).toLocaleString('tr-TR', {minimumFractionDigits:2}) + ' ₺'; document.getElementById('betsWinFoot').textContent = (sums[1]||0).toLocaleString('tr-TR', {minimumFractionDigits:2}) + ' ₺'; }
}
// İlk hesap
recalcFoot('txnTable',[2]); recalcFoot('gameTable',[2]); recalcFoot('betsTable',[2,3]);
// Arama değişince güncelle
['searchTxn','searchGame','searchBets'].forEach((id,idx)=>{
  const el=document.getElementById(id); if(!el) return;
  el.addEventListener('input',()=>{ if(idx===0) recalcFoot('txnTable',[2]); else if(idx===1) recalcFoot('gameTable',[2]); else recalcFoot('betsTable',[2,3]); });
});
// Preset tarih aralıkları
(function(){
  const form=document.getElementById('filterForm'); if(!form) return;
  const s=form.querySelector('input[name="start"]'); const e=form.querySelector('input[name="end"]');
  function format(d){const y=d.getFullYear();const m=String(d.getMonth()+1).padStart(2,'0');const day=String(d.getDate()).padStart(2,'0');return `${y}-${m}-${day}`;}
  form.querySelectorAll('[data-preset]').forEach(btn=>{
    btn.addEventListener('click',()=>{
      const p=btn.getAttribute('data-preset'); const now=new Date(); let sd, ed=new Date(now);
      if(p==='7'){ sd=new Date(now); sd.setDate(sd.getDate()-7); }
      else if(p==='30'){ sd=new Date(now); sd.setDate(sd.getDate()-30); }
      else if(p==='mtd'){ sd=new Date(now.getFullYear(), now.getMonth(), 1); }
      else if(p==='ytd'){ sd=new Date(now.getFullYear(), 0, 1); }
      if(sd){ s.value=format(sd); } e.value=format(ed); form.requestSubmit();
    });
  });
})();
// Yazdırma
document.getElementById('printBtn')?.addEventListener('click', ()=> window.print());
</script>
</body>
</html>