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

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

// Handle POST request for updating firm details
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate input
    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
    $firma_adi = trim($_POST['firma_adi']);
    $firma_key = trim($_POST['firma_key']);

    if ($id && $firma_adi && $firma_key) {
        // Prepared statement for updating firm details
        $stmt = $pdo->prepare("UPDATE firma SET firma_adi = :firma_adi, firma_key = :firma_key WHERE id = :id");
        $stmt->bindParam(':firma_adi', $firma_adi);
        $stmt->bindParam(':firma_key', $firma_key);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        
        if ($stmt->execute()) {
            echo "<script>Swal.fire('Başarılı', 'Firma güncellendi', 'success');</script>";
        } else {
            echo "<script>Swal.fire('Hata', 'Firma güncellenirken bir hata oluştu', 'error');</script>";
        }
    } else {
        echo "<script>Swal.fire('Hata', 'Geçersiz giriş verileri', 'error');</script>";
    }
}

// Fetch all firms
$stmt = $pdo->query("SELECT * FROM firma");
$firmalar = $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>Firma Kodları</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>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            height: 100vh; /* Yüksekliği tam sayfa yap */
        }
        .container-fluid {
            padding: 0;
        }
        .table td, .table th {
            vertical-align: middle;
        }

        /* Responsive adjustments for smaller screens */
        @media (max-width: 767px) {
            .form-inline input {
                width: 100%;
                margin-bottom: 10px;
            }
            .btn {
                width: 100%;
            }
            .form-group {
                width: 100%;
            }
            /* Form alanlarını alt alta göstermek için */
            .form-inline {
                flex-direction: column;
                align-items: stretch;
            }
            .btn {
                margin-top: 10px;
            }
            /* İşlemler kısmı için mobil uyumlu düzenleme */
            .table td {
                word-break: break-word;
            }
        }
    </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">Firma Kodları</h2>

                <!-- Araç Çubuğu: Hızlı Arama, Sütun Görünürlüğü, 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="firmaToolbar">
                    <input type="text" class="form-control" id="quickSearchFirma" placeholder="Hızlı arama..." style="max-width: 220px;">
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="columnToggleFirma" data-bs-toggle="dropdown" aria-expanded="false">
                            Sütun Görünürlüğü
                        </button>
                        <ul class="dropdown-menu p-2" aria-labelledby="columnToggleFirma" id="columnListFirma" style="min-width: 220px;"></ul>
                    </div>
                    <button class="btn btn-outline-primary" id="saveViewFirma" title="Mevcut sütun görünürlüğünü ve sıralamayı kaydet">Görünümü Kaydet</button>
                    <button class="btn btn-outline-primary" id="loadViewFirma" title="Kaydedilmiş görünümü yükle">Görünümü Yükle</button>
                    <button class="btn btn-outline-success" id="exportCsvFirma" title="Tabloyu CSV olarak dışa aktar">CSV Dışa Aktar</button>
                </div>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Firma Adı</th>
                            <th>Firma Key</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($firmalar as $firma): ?>
                        <tr>
                            <td><?= htmlspecialchars($firma['id']) ?></td>
                            <td><?= htmlspecialchars($firma['firma_adi']) ?></td>
                            <td><?= htmlspecialchars($firma['firma_key']) ?></td>
                            <td>
                                <form method="post" class="d-flex flex-column flex-sm-row align-items-center">
                                    <input type="hidden" name="id" value="<?= htmlspecialchars($firma['id']) ?>">
                                    <input type="text" name="firma_adi" value="<?= htmlspecialchars($firma['firma_adi']) ?>" class="form-control me-2 mb-2 mb-sm-0" required>
                                    <input type="text" name="firma_key" value="<?= htmlspecialchars($firma['firma_key']) ?>" class="form-control me-2 mb-2 mb-sm-0" required>
                                    <button type="submit" class="btn btn-primary btn-sm w-100 w-sm-auto">Kaydet</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    (function() {
        const table = document.querySelector('.table.table-striped');
        if (!table) return;
        const pageKey = 'firma';
        const quickSearch = document.getElementById('quickSearchFirma');
        const columnList = document.getElementById('columnListFirma');
        const saveBtn = document.getElementById('saveViewFirma');
        const loadBtn = document.getElementById('loadViewFirma');
        const exportBtn = document.getElementById('exportCsvFirma');

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

        // Sütun listesi oluştur
        headers.forEach((th, idx) => {
            const li = document.createElement('li');
            li.className = 'dropdown-item';
            const id = `firma-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) {
            headers[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
        if (quickSearch) {
            quickSearch.addEventListener('input', () => {
                const q = quickSearch.value.toLowerCase();
                rows.forEach(tr => {
                    const text = tr.textContent.toLowerCase();
                    tr.style.display = text.includes(q) ? '' : 'none';
                });
            });
        }

        // Görünüm kaydet/yükle
        function getViewState() {
            const columns = headers.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));
            // Checkboxes 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', () => {
            const state = getViewState();
            localStorage.setItem('tableView_' + pageKey, JSON.stringify(state));
            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
        exportBtn.addEventListener('click', () => {
            const visibleCols = headers.map((h, i) => ({ i, txt: h.textContent.trim() })).filter(c => headers[c.i].style.display !== 'none');
            const lines = [];
            lines.push(visibleCols.map(c => '"' + c.txt.replace(/"/g, '""') + '"').join(','));
            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 = 'firma_kodlari.csv';
            a.click();
            URL.revokeObjectURL(url);
        });
    })();
    </script>
</body>
</html>
