<?php $title=__('categories.categories', 'Categories'); ob_start(); ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">
        <i class="fas fa-layer-group"></i> <?= __('categories.categories', 'Categories') ?>
    </h1>
    <div class="btn-group">
        <a href="/samanta_crm/categories/create" class="btn btn-primary">
            <i class="fas fa-plus"></i> <?= __('common.add', 'Add') ?>
        </a>
    </div>
</div>

<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><?= __('categories.categories', 'Categories') ?></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><?= __('common.name', 'Name') ?></th>
                    <th><?= __('common.description', 'Description') ?></th>
                    <th><?= __('common.sort_order', 'Order') ?></th>
                    <th class="text-end"><?= __('common.actions', 'Actions') ?></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/categories/<?= $c['id'] ?>/edit">
                            <?= __('common.edit', 'Edit') ?>
                        </a>
                        <form method="POST" action="/samanta_crm/categories/<?= $c['id'] ?>/delete" class="d-inline" onsubmit="return confirm('<?= __('categories.confirm_delete', 'Delete?') ?>')">
                            <button class="btn btn-sm btn-outline-danger">
                                <?= __('common.delete', 'Del') ?>
                            </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">
            <?= __('common.total', 'Total') ?>: <?= count($categories) ?> <?= __('common.items', 'items') ?>
        </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/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'; ?>


