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

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

// Pagination setup
$itemsPerPage = 100;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $itemsPerPage;

// Search functionality
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Query for fetching games with optional search
$query = "SELECT * FROM games";
$params = [];
if ($search) {
    $query .= " WHERE game_name LIKE :search OR provider_id LIKE :search";
    $params['search'] = '%' . $search . '%';
}
$query .= " LIMIT :offset, :itemsPerPage";
$stmt = $pdo->prepare($query);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':itemsPerPage', $itemsPerPage, PDO::PARAM_INT);
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
$stmt->execute();
$games = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch total records for pagination
$totalQuery = "SELECT COUNT(*) FROM games";
if ($search) {
    $totalQuery .= " WHERE game_name LIKE :search OR provider_id LIKE :search";
    $totalStmt = $pdo->prepare($totalQuery);
    $totalStmt->execute(['search' => '%' . $search . '%']);
} else {
    $totalStmt = $pdo->query($totalQuery);
}
$totalItems = $totalStmt->fetchColumn();
$totalPages = ceil($totalItems / $itemsPerPage);
?><!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oyun 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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <div class="col-md-10 p-4">
                <h2>Oyun Yönetimi</h2>
                <form class="mb-3" method="GET" action="">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control" placeholder="Oyun Ara..." value="<?= htmlspecialchars($search) ?>">
                        <button type="submit" class="btn btn-primary">Ara</button>
                    </div>
                </form>
                <!-- 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>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Provider ID</th>
                            <th>Game ID</th>
                            <th>Game Code</th>
                            <th>Game Type</th>
                            <th>Cover</th>
                            <th>Provider Game</th>
                            <th>Banner</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($games as $game): ?>
                        <tr>
                            <td><?= htmlspecialchars($game['id']) ?></td>
                             <td><?= htmlspecialchars($game['game_name']) ?></td>
                            <td><?= htmlspecialchars($game['provider_id']) ?></td>
                            <td><?= htmlspecialchars($game['game_id']) ?></td>
                            <td><?= htmlspecialchars($game['game_code']) ?></td>
                            <td><?= htmlspecialchars($game['game_type']) ?></td>
                            <td><?= htmlspecialchars($game['cover']) ?></td>
                            <td><?= htmlspecialchars($game['provider_game']) ?></td>
                            <td><?= htmlspecialchars($game['banner']) ?></td>
                            <td>
                                <button class="btn btn-primary btn-sm edit-btn" 
                                        data-id="<?= $game['id'] ?>" 
                                        data-game="<?= htmlspecialchars(json_encode($game)) ?>">Düzenle</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <!-- Pagination -->
                <nav>
                    <ul class="pagination justify-content-center">
                        <!-- Önceki Sayfa -->
                        <li class="page-item <?= $page == 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">Önceki</a>
                        </li>

                        <!-- İlk Sayfa (Her zaman gösterilir) -->
                        <?php if ($page > 3): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=1&search=<?= urlencode($search) ?>">1</a>
                            </li>
                            <?php if ($page > 4): ?>
                                <li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>
                            <?php endif; ?>
                        <?php endif; ?>

                        <!-- Yakın Sayfalar -->
                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                            <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>

                        <!-- Sonraki Sayfa -->
                        <?php if ($page < $totalPages - 2): ?>
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $totalPages ?>&search=<?= urlencode($search) ?>"><?= $totalPages ?></a>
                            </li>
                        <?php endif; ?>

                        <li class="page-item <?= $page == $totalPages ? 'disabled' : '' ?>">
                            <a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Sonraki</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- Sayfa scriptleri -->
    <script>
        // SweetAlert2 Edit Button Logic
        document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', function() {
                const game = JSON.parse(this.getAttribute('data-game'));

                Swal.fire({
                    title: 'Oyun Düzenle',
                    html: `
                        <form id="edit-form">
                            <input type="hidden" name="id" value="${game.id}">
                            <div class="mb-2">
                                <label for="provider_id">Provider ID</label>
                                <input class="form-control" name="provider_id" value="${game.provider_id}" placeholder="Provider ID">
                            </div>
                            <div class="mb-2">
                                <label for="game_id">Game ID</label>
                                <input class="form-control" name="game_id" value="${game.game_id}" placeholder="Game ID">
                            </div>
                            <div class="mb-2">
                                <label for="game_code">Game Code</label>
                                <input class="form-control" name="game_code" value="${game.game_code}" placeholder="Game Code">
                            </div>
                            <div class="mb-2">
                                <label for="game_type">Game Type</label>
                                <input class="form-control" name="game_type" value="${game.game_type}" placeholder="Game Type">
                            </div>
                            <div class="mb-2">
                                <label for="cover">Cover</label>
                                <input class="form-control" name="cover" value="${game.cover}" placeholder="Cover">
                            </div>
                            <div class="mb-2">
                                <label for="provider_game">Provider Game</label>
                                <input class="form-control" name="provider_game" value="${game.provider_game}" placeholder="Provider Game">
                            </div>
                            <div class="mb-2">
                                <label for="banner">Banner</label>
                                <input class="form-control" name="banner" value="${game.banner}" placeholder="Banner">
                            </div>
                        </form>
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'Kaydet',
                    preConfirm: () => {
                        const form = document.getElementById('edit-form');
                        const formData = new FormData(form);

                        return fetch('update_game.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (!data.success) {
                                throw new Error(data.message || 'Güncelleme başarısız oldu');
                            }
                        })
                        .catch(error => Swal.showValidationMessage(`Hata: ${error}`));
                    }
                }).then(result => {
                    if (result.isConfirmed) {
                        Swal.fire('Başarılı!', 'Oyun güncellendi.', 'success')
                            .then(() => location.reload());
                    }
                });
            });
        });
    </script>
    <script>
    // Games 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 = 'games_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 = 'oyunlar.csv';
        document.body.appendChild(a);
        a.click();
        a.remove();
        URL.revokeObjectURL(url);
      });
    })();
    </script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
