<?php $title='Kategorie Menu'; ob_start(); ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2><i class="fas fa-layer-group me-2"></i>Kategorie Menu</h2>
        <p class="text-muted">Zarządzaj kategoriami menu lokali</p>
    </div>
    <div class="btn-group">
        <a href="/samanta_crm/menu/items" class="btn btn-secondary">
            <i class="fas fa-arrow-left me-2"></i>Powrót do Menu
        </a>
        <a href="/samanta_crm/menu/categories/create" class="btn btn-primary">
            <i class="fas fa-plus"></i> Dodaj Kategorię
        </a>
    </div>
</div>

<?php if (isset($_SESSION['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fas fa-check-circle me-2"></i><?= $_SESSION['success']; unset($_SESSION['success']); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <i class="fas fa-exclamation-circle me-2"></i><?= $_SESSION['error']; unset($_SESSION['error']); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header py-2 d-flex justify-content-between align-items-center">
        <span class="small fw-bold"><i class="fas fa-table me-1"></i>Kategorie Menu</span>
        <span class="badge bg-info text-dark"><i class="fas fa-arrows-alt-v me-1"></i>Przeciągnij aby zmienić kolejność</span>
    </div>
    <div class="card-body pt-0">
        <table class="table table-sm table-hover align-middle data-table mb-0">
            <thead>
                <tr>
                    <th width="30"><i class="fas fa-grip-vertical text-muted"></i></th>
                    <th>Nazwa</th>
                    <th>Opis</th>
                    <th>Kolejność</th>
                    <th class="text-end">Akcje</th>
                </tr>
            </thead>
            <tbody id="sortable-categories">
                <?php foreach($categories as $c): ?>
                <tr data-id="<?= $c['id'] ?>" style="cursor: move;">
                    <td class="drag-handle"><i class="fas fa-grip-vertical text-muted"></i></td>
                    <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
                    <td class="text-muted small"><?= htmlspecialchars($c['description'] ?? '') ?></td>
                    <td><?= (int)$c['sort_order'] ?></td>
                    <td class="text-end">
                        <a class="btn btn-sm btn-outline-primary" href="/samanta_crm/menu/categories/<?= $c['id'] ?>/edit">
                            <i class="fas fa-edit"></i> Edytuj
                        </a>
                        <form method="POST" action="/samanta_crm/menu/categories/<?= $c['id'] ?>/delete" class="d-inline" onsubmit="return confirm('Czy na pewno chcesz usunąć tę kategorię?')">
                            <button class="btn btn-sm btn-outline-danger">
                                <i class="fas fa-trash"></i> Usuń
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="card-footer py-2 d-flex justify-content-between align-items-center">
        <span></span>
        <div class="small text-muted">
            Razem: <?= count($categories) ?> kategorii
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const tbody = document.getElementById('sortable-categories');
    
    if (tbody) {
        const sortable = new Sortable(tbody, {
            handle: '.drag-handle',
            animation: 150,
            ghostClass: 'bg-light',
            onEnd: function(evt) {
                // Get new order
                const rows = tbody.querySelectorAll('tr[data-id]');
                const order = Array.from(rows).map(row => row.dataset.id);
                
                // Save to server
                fetch('/samanta_crm/menu/categories/reorder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ order: order })
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('HTTP error ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Server response:', data);
                    if (data.success) {
                        // Update sort_order display
                        rows.forEach((row, index) => {
                            const orderCell = row.cells[3]; // 4th column (0-indexed, after grip column)
                            orderCell.textContent = index;
                        });
                    } else {
                        console.error('Server error:', data.error);
                        alert('Błąd zapisywania kolejności: ' + (data.error || 'Unknown error'));
                        location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Błąd zapisywania kolejności: ' + error.message);
                    location.reload();
                });
            }
        });
    }
});
</script>

<?php $content=ob_get_clean(); include '../app/Views/layout.php'; ?>
