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

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

// CRUD İşlemleri
$action = $_POST['action'] ?? $_GET['action'] ?? null;

if ($action === 'create') {
    $banka_adi = $_POST['banka_adi'] ?? '';
    $iban = $_POST['iban'] ?? '';
    $adsoyad = $_POST['adsoyad'] ?? '';

    if ($banka_adi && $iban && $adsoyad) {
        $stmt = $pdo->prepare("INSERT INTO bankalar (banka_adi, iban, adsoyad) VALUES (:banka_adi, :iban, :adsoyad)");
        $stmt->execute(['banka_adi' => $banka_adi, 'iban' => $iban, 'adsoyad' => $adsoyad]);
        header('Location: bankalar.php?success=1');
        exit;
    }
}

if ($action === 'update') {
    $id = $_POST['id'] ?? null;
    $banka_adi = $_POST['banka_adi'] ?? '';
    $iban = $_POST['iban'] ?? '';
    $adsoyad = $_POST['adsoyad'] ?? '';

    if ($id && $banka_adi && $iban && $adsoyad) {
        $stmt = $pdo->prepare("UPDATE bankalar SET banka_adi = :banka_adi, iban = :iban, adsoyad = :adsoyad WHERE id = :id");
        $stmt->execute(['banka_adi' => $banka_adi, 'iban' => $iban, 'adsoyad' => $adsoyad, 'id' => $id]);
        header('Location: bankalar.php?success=1');
        exit;
    }
}

if ($action === 'delete') {
    $id = $_POST['id'] ?? null;
    if ($id) {
        $stmt = $pdo->prepare("DELETE FROM bankalar WHERE id = :id");
        $stmt->execute(['id' => $id]);
        header('Location: bankalar.php?success=1');
        exit;
    }
}

// Listeyi çek
$stmt = $pdo->query("SELECT id, banka_adi, iban, adsoyad FROM bankalar ORDER BY id DESC");
$bankalar = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bankalar (IBAN) 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 mt-5">
                <h2 class="mb-4 text-warning">Bankalar (IBAN) Yönetimi</h2>

                <!-- Ekleme Formu -->
                <div class="card mb-4">
                    <div class="card-header">Yeni Banka Ekle</div>
                    <div class="card-body">
                        <form method="post">
                            <input type="hidden" name="action" value="create">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Banka Adı</label>
                                    <input type="text" name="banka_adi" class="form-control" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">IBAN</label>
                                    <input type="text" name="iban" class="form-control" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Ad Soyad</label>
                                    <input type="text" name="adsoyad" class="form-control" required>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button type="submit" class="btn btn-success">Ekle</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Liste -->
                <!-- 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>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Banka Adı</th>
                                <th>IBAN</th>
                                <th>Ad Soyad</th>
                                <th>İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bankalar as $b): ?>
                                <tr>
                                    <td><?= htmlspecialchars($b['id']) ?></td>
                                    <td><?= htmlspecialchars($b['banka_adi']) ?></td>
                                    <td><?= htmlspecialchars($b['iban']) ?></td>
                                    <td><?= htmlspecialchars($b['adsoyad']) ?></td>
                                    <td>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= $b['id'] ?>">
                                            <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Silmek istediğinize emin misiniz?');">Sil</button>
                                        </form>
                                        <!-- Düzenle Modal Tetikleyici -->
                                        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editModal<?= $b['id'] ?>">Düzenle</button>

                                        <!-- Düzenle Modal -->
                                        <div class="modal fade" id="editModal<?= $b['id'] ?>" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title">Bankayı Düzenle</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <form method="post">
                                                            <input type="hidden" name="action" value="update">
                                                            <input type="hidden" name="id" value="<?= $b['id'] ?>">
                                                            <div class="mb-3">
                                                                <label class="form-label">Banka Adı</label>
                                                                <input type="text" name="banka_adi" class="form-control" value="<?= htmlspecialchars($b['banka_adi']) ?>" required>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label class="form-label">IBAN</label>
                                                                <input type="text" name="iban" class="form-control" value="<?= htmlspecialchars($b['iban']) ?>" required>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label class="form-label">Ad Soyad</label>
                                                                <input type="text" name="adsoyad" class="form-control" value="<?= htmlspecialchars($b['adsoyad']) ?>" required>
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Kapat</button>
                                                                <button type="submit" class="btn btn-primary">Kaydet</button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </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>
    // Bankalar 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 = 'bankalar_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 = 'bankalar.csv';
        document.body.appendChild(a);
        a.click();
        a.remove();
        URL.revokeObjectURL(url);
      });
    })();
    </script>
</body>
</html>