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

require_permission('bonus_manage');
event_log('view', 'Bonus talepleri görüntülendi', ['admin' => $_SESSION['admin_user'] ?? 'unknown']);

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

$stmt = $pdo->query("SELECT * FROM bonus_talepleri");
$bonuslar = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Viewport ekledik, mobil uyumlu için -->
    <title>Bonus Talepleri</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">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            height: 100vh; /* Yüksekliği tam sayfa yap */
        }

        /* Mobilde tabloyu yatay kaydırılabilir yapma */
        @media (max-width: 767px) {
            .table-responsive {
                overflow-x: auto;
            }
        }

        /* Genel stil düzenlemeleri */
        .container-fluid {
            padding: 0;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <div class="col-md-10 p-4 mt-5">
                <h2 class="mb-4 text-warning">Bonus Talepleri</h2>
                <!-- Hızlı Araçlar: Hızlı Arama, Sütunlar, Görünüm Kaydet/Yükle, CSV -->
                <div class="d-flex align-items-center gap-2 mb-3">
                    <input type="text" id="quickSearch" class="form-control" placeholder="Tabloda hızlı arama..." style="max-width:300px">
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Sütunlar</button>
                        <div class="dropdown-menu p-3" id="columnMenu" style="min-width:260px"></div>
                    </div>
                    <button class="btn btn-outline-primary" id="saveViewBtn">Görünümü Kaydet</button>
                    <button class="btn btn-outline-secondary" id="loadViewBtn">Görünümü Yükle</button>
                    <button class="btn btn-outline-success" id="exportCsvBtn">CSV Dışa Aktar</button>
                </div>

                <!-- Tabloyu responsive yapalım -->
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Üye ID</th>
                                <th>Bonus Türü</th>
                                <th>Miktar</th>
                                <th>Tarih</th>
                                <th>Durum</th>
                                <th>Açıklama</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bonuslar as $bonus): ?>
                            <tr>
                                <td><?= htmlspecialchars($bonus['id']) ?></td>
                                <td><?= htmlspecialchars($bonus['uye_id']) ?></td>
                                <td><?= htmlspecialchars($bonus['bonus_turu']) ?></td>
                                <td><?= htmlspecialchars($bonus['miktar']) ?></td>
                                <td><?= htmlspecialchars($bonus['tarih']) ?></td>
                                <td><?= htmlspecialchars($bonus['durum']) ?></td>
                                <td><?= htmlspecialchars($bonus['aciklama']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Bonus talepleri tablo geliştirmeleri: hızlı arama, sütun görünürlüğü, görünüm kaydı, CSV export
    (function(){
      const table = document.querySelector('.table.table-striped');
      if(!table) return;
      const pageKey = 'bonus_view_v1';
      const quickSearch = document.getElementById('quickSearch');
      const columnMenu = document.getElementById('columnMenu');
      const saveBtn = document.getElementById('saveViewBtn');
      const loadBtn = document.getElementById('loadViewBtn');
      const exportBtn = document.getElementById('exportCsvBtn');

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

      // Sütun menüsü oluştur
      const initialVisible = ths.map(() => true);
      columnMenu.innerHTML = ths.map((th, idx) => {
        const label = th.textContent.trim() || ('Sütun ' + (idx+1));
        return `<div class="form-check">
          <input class="form-check-input column-toggle" type="checkbox" data-col="${idx}" id="col_${idx}" checked>
          <label class="form-check-label" for="col_${idx}">${label}</label>
        </div>`;
      }).join('');

      function setColumnVisible(index, visible){
        const display = visible ? '' : 'none';
        const header = ths[index];
        if (header) header.style.display = display;
        rows.forEach(row => {
          const cells = row.children;
          if (cells[index]) cells[index].style.display = display;
        });
      }

      // Toggle olayları
      columnMenu.addEventListener('change', (e)=>{
        const input = e.target.closest('.column-toggle');
        if(!input) return;
        const idx = parseInt(input.dataset.col,10);
        setColumnVisible(idx, input.checked);
      });

      // Hızlı arama
      function normalize(t){ return (t||'').toLowerCase(); }
      function rowMatches(row, term){
        if(!term) return true;
        const txt = normalize(row.textContent);
        return txt.includes(term);
      }
      quickSearch && quickSearch.addEventListener('input', ()=>{
        const term = normalize(quickSearch.value);
        rows.forEach(row => {
          row.style.display = rowMatches(row, term) ? '' : 'none';
        });
      });

      // Görünümü kaydet/yükle
      saveBtn && saveBtn.addEventListener('click', ()=>{
        const visibles = Array.from(columnMenu.querySelectorAll('.column-toggle')).map(inp => inp.checked);
        const data = { search: quickSearch ? quickSearch.value : '', visible: visibles };
        localStorage.setItem(pageKey, JSON.stringify(data));
      });
      loadBtn && loadBtn.addEventListener('click', ()=>{
        const raw = localStorage.getItem(pageKey);
        if(!raw) return;
        try{
          const data = JSON.parse(raw);
          if(quickSearch) {
            quickSearch.value = data.search || '';
            const term = normalize(quickSearch.value);
            rows.forEach(row => { row.style.display = rowMatches(row, term) ? '' : 'none'; });
          }
          const visibles = Array.isArray(data.visible) ? data.visible : initialVisible;
          Array.from(columnMenu.querySelectorAll('.column-toggle')).forEach((inp, i)=>{
            const v = visibles[i] !== false; // default visible
            inp.checked = v;
            setColumnVisible(i, v);
          });
        }catch(err){ /* yoksay */ }
      });

      // CSV dışa aktar (görünür sütunlar)
      exportBtn && exportBtn.addEventListener('click', ()=>{
        const visibleMap = Array.from(columnMenu.querySelectorAll('.column-toggle')).map(inp => inp.checked);
        const headers = ths.map((th,i)=> visibleMap[i] ? th.textContent.trim() : null).filter(Boolean);
        const lines = [];
        lines.push(headers.join(','));
        rows.forEach(row => {
          if(row.style.display==='none') return; // filtrelenmiş satırı atla
          const cells = Array.from(row.children).map((td,i)=> visibleMap[i] ? '"'+(td.textContent.trim().replace(/"/g,'""'))+'"' : null).filter(v=> v!==null);
          lines.push(cells.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 = 'bonus_talepleri.csv';
        document.body.appendChild(a);
        a.click();
        a.remove();
        URL.revokeObjectURL(url);
      });
    })();
    </script>
</body>
</html>
