<?php include __DIR__ . '/../layout/header.php'; ?>

<div class="page-toolbar">
    <div class="header-spacer"></div>
    <a href="<?php echo $baseUrl; ?>/admin/categories/create" class="admin-btn admin-btn-primary">
        <i class="fa fa-plus-circle"></i> Yeni Kategori
    </a>
</div>

<div class="admin-card" style="padding:0;overflow:hidden;">
    <div class="admin-table-wrap">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>Kategori Adı</th>
                    <th>Slug</th>
                    <th>Üst Kategori</th>
                    <th style="text-align:right;width:120px;">İşlemler</th>
                </tr>
            </thead>
            <tbody id="draggable-tbody">
                <?php foreach ($categories as $cat): ?>
                <?php $parent = $cat->getParent(); ?>
                <tr class="draggable-row" draggable="true" data-id="<?php echo $cat->id; ?>" style="cursor: move;">
                    <td style="font-weight:600;color:var(--text-1);">
                        <i class="fa fa-<?php echo $parent ? 'circle' : 'folder'; ?>" style="color:var(--primary);margin-right:8px;opacity:0.7;font-size:12px;"></i>
                        <?php echo htmlspecialchars($cat->name); ?>
                    </td>
                    <td><code>/<?php echo htmlspecialchars($cat->slug); ?></code></td>
                    <td style="color:var(--text-3);">
                        <?php echo $parent ? htmlspecialchars($parent->name) : 'Ana Kategori'; ?>
                    </td>
                    <td style="text-align:right;">
                        <div style="display:flex;justify-content:flex-end;gap:4px;">
                            <a href="<?php echo $baseUrl; ?>/admin/categories/edit/<?php echo $cat->id; ?>" class="admin-action-btn edit"><i class="fa fa-pencil"></i></a>
                            <a href="<?php echo $baseUrl; ?>/admin/categories/delete/<?php echo $cat->id; ?>" onclick="return confirm('Bu kategoriyi silmek istediğinize emin misiniz?')" class="admin-action-btn delete"><i class="fa fa-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const container = document.getElementById('draggable-tbody');
    if (!container) return;

    let dragEl = null;

    container.addEventListener('dragstart', function(e) {
        const item = e.target.closest('.draggable-row');
        if (!item) return;
        dragEl = item;
        item.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
    });

    container.addEventListener('dragover', function(e) {
        e.preventDefault();
        const item = e.target.closest('.draggable-row');
        if (!item || item === dragEl) return;

        const rect = item.getBoundingClientRect();
        const next = (e.clientY - rect.top) / (rect.bottom - rect.top) > 0.5;
        container.insertBefore(dragEl, next ? item.nextSibling : item);
    });

    container.addEventListener('dragend', function(e) {
        const item = e.target.closest('.draggable-row');
        if (!item) return;
        item.classList.remove('dragging');
        
        const ids = [];
        container.querySelectorAll('.draggable-row').forEach(el => {
            ids.push(el.getAttribute('data-id'));
        });

        fetch('<?php echo $baseUrl; ?>/admin/categories/reorder', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ids: ids })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('Sıralama başarıyla güncellendi.', 'success');
            } else {
                showToast('Sıralama güncellenemedi.', 'error');
            }
        });
    });

    // Mobile touch events
    container.addEventListener('touchstart', function(e) {
        const item = e.target.closest('.draggable-row');
        if (!item) return;
        dragEl = item;
        item.classList.add('dragging');
    }, { passive: true });

    container.addEventListener('touchmove', function(e) {
        if (!dragEl) return;
        const touch = e.touches[0];
        
        const prevDisplay = dragEl.style.display;
        dragEl.style.display = 'none';
        const target = document.elementFromPoint(touch.clientX, touch.clientY);
        dragEl.style.display = prevDisplay;
        
        if (!target) return;
        const item = target.closest('.draggable-row');
        if (!item || item === dragEl) return;

        const rect = item.getBoundingClientRect();
        const next = (touch.clientY - rect.top) / (touch.clientY - rect.top) > 0.5; // fallback check
        const isNext = (touch.clientY - rect.top) / (rect.bottom - rect.top) > 0.5;
        container.insertBefore(dragEl, isNext ? item.nextSibling : item);
        
        if (e.cancelable) e.preventDefault();
    }, { passive: false });

    container.addEventListener('touchend', function(e) {
        if (!dragEl) return;
        dragEl.classList.remove('dragging');
        dragEl = null;

        const ids = [];
        container.querySelectorAll('.draggable-row').forEach(el => {
            ids.push(el.getAttribute('data-id'));
        });

        fetch('<?php echo $baseUrl; ?>/admin/categories/reorder', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ids: ids })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('Sıralama başarıyla güncellendi.', 'success');
            } else {
                showToast('Sıralama güncellenemedi.', 'error');
            }
        });
    });
});
</script>

<style>
.draggable-row.dragging {
    opacity: 0.5;
    background: var(--surface-hover) !important;
}
</style>

<?php include __DIR__ . '/../layout/footer.php'; ?>
