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

<?php
$catSearch = $search ?? '';
$catSort   = $sort   ?? '';
$catOrder  = $order  ?? 'asc';
function catSortUrl($f, $cs, $co, $s) {
    $o = ($cs === $f && $co === 'asc') ? 'desc' : 'asc';
    return '?sort='.$f.'&order='.$o.($s !== '' ? '&search='.urlencode($s) : '');
}
function catSortIcon($f, $cs, $co) {
    if ($cs !== $f) return '<i class="fa fa-sort" style="opacity:.3;font-size:10px;"></i>';
    return $co === 'asc'
        ? '<i class="fa fa-sort-asc" style="color:var(--primary);font-size:11px;"></i>'
        : '<i class="fa fa-sort-desc" style="color:var(--primary);font-size:11px;"></i>';
}
?>

<div class="page-toolbar">
    <form method="GET" action="<?php echo $baseUrl; ?>/admin/categories" id="category-search-form" class="search-bar" style="max-width:440px;">
        <i class="fa fa-search search-icon"></i>
        <input type="text" name="search" id="category-search-input"
               value="<?php echo htmlspecialchars($catSearch); ?>"
               placeholder="Kategori adı ara..."
               autocomplete="off">
        <?php if ($catSearch !== ''): ?>
        <a href="<?php echo $baseUrl; ?>/admin/categories" class="search-clear-btn"><i class="fa fa-times"></i></a>
        <?php endif; ?>
    </form>
    <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;">

<?php
$currentParentSlug = $_GET['parent'] ?? null;
$isDrillDown = ($catSearch === '' && $catSort === '');

$childrenCountMap = [];
$currentParentObj = null;

foreach ($categories as $c) {
    if (!empty($c->parent_slug)) {
        if (!isset($childrenCountMap[$c->parent_slug])) $childrenCountMap[$c->parent_slug] = 0;
        $childrenCountMap[$c->parent_slug]++;
    }
    if ($currentParentSlug && $c->slug === $currentParentSlug) {
        $currentParentObj = $c;
    }
}

$displayCategories = [];
if (!$isDrillDown) {
    $displayCategories = $categories;
} else {
    foreach ($categories as $c) {
        if ($currentParentSlug) {
            if ($c->parent_slug === $currentParentSlug) {
                $displayCategories[] = $c;
            }
        } else {
            if (empty($c->parent_slug)) {
                $displayCategories[] = $c;
            }
        }
    }
}
$categories = $displayCategories;
?>

    <?php if ($isDrillDown && $currentParentSlug && $currentParentObj): ?>
    <div style="padding:16px 16px 0 16px;">
        <a href="<?php echo $baseUrl; ?>/admin/categories<?php echo empty($currentParentObj->parent_slug) ? '' : '?parent='.urlencode($currentParentObj->parent_slug); ?>" 
           class="admin-btn" style="background:var(--surface-2);color:var(--text-1); border:1px solid var(--border);">
            <i class="fa fa-arrow-left"></i> Geri Dön (<?php echo htmlspecialchars($currentParentObj->name); ?>)
        </a>
    </div>
    <?php endif; ?>

    <?php if (!empty($categories)): ?>

    <!-- Desktop Table -->
    <div class="admin-table-wrap desktop-only" style="border:none;border-radius:0;">
        <table class="admin-table">
            <thead>
                <tr>
                    <th><a href="<?php echo catSortUrl('name', $catSort, $catOrder, $catSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Kategori Adı <?php echo catSortIcon('name', $catSort, $catOrder); ?></a></th>
                    <th><a href="<?php echo catSortUrl('slug', $catSort, $catOrder, $catSearch); ?>" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:5px;">Slug <?php echo catSortIcon('slug', $catSort, $catOrder); ?></a></th>
                    <th>Üst Kategori</th>
                    <th style="text-align:right;width:100px;">İşlemler</th>
                </tr>
            </thead>
            <tbody id="draggable-tbody">
                <?php foreach ($categories as $cat): ?>
                <?php $parent = $cat->getParent(); ?>
                <tr class="draggable-row" draggable="<?php echo $isDrillDown ? 'true' : 'false'; ?>" data-id="<?php echo $cat->id; ?>" style="<?php echo $isDrillDown ? '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); ?>
                        <span style="font-size:11px;color:var(--text-3);font-weight:normal;margin-left:6px;">(<?php echo count($cat->getProducts()); ?> Ürün)</span>
                        <?php if ($isDrillDown && isset($childrenCountMap[$cat->slug])): ?>
                            <a href="?parent=<?php echo urlencode($cat->slug); ?>" style="display:inline-block;margin-left:8px;font-size:11px;background:var(--surface-2);color:var(--primary);padding:2px 8px;border-radius:12px;text-decoration:none;border:1px solid var(--border);">
                                <i class="fa fa-sitemap"></i> Alt Kategoriler (<?php echo $childrenCountMap[$cat->slug]; ?>)
                            </a>
                        <?php endif; ?>
                    </td>
                    <td>
                        <code style="background:var(--surface-2);border:1px solid var(--border);padding:3px 9px;border-radius:5px;font-size:11.5px;color:var(--text-2);">/<?php echo htmlspecialchars($cat->slug); ?></code>
                    </td>
                    <td style="color:var(--text-3);">
                        <?php echo $parent ? '<i class="fa fa-level-up" style="margin-right:5px;"></i>'.htmlspecialchars($parent->name) : '<span style="color:var(--text-3);">Ana kategori</span>'; ?>
                    </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>
                            <button onclick="confirmDelete('<?php echo $baseUrl; ?>/admin/categories/delete/<?php echo $cat->id; ?>')" class="admin-action-btn delete"><i class="fa fa-trash"></i></button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Mobile Cards -->
    <div class="mobile-only" id="draggable-cards" style="padding:12px;">
        <?php foreach ($categories as $cat): ?>
        <?php $parent = $cat->getParent(); ?>
        <div class="m-card draggable-card" draggable="<?php echo $isDrillDown ? 'true' : 'false'; ?>" data-id="<?php echo $cat->id; ?>" style="<?php echo $isDrillDown ? 'cursor: move;' : ''; ?>">
            <div class="m-card-header">
                <div class="m-card-title-wrap">
                    <div class="m-card-icon"><i class="fa fa-folder"></i></div>
                    <div style="overflow:hidden;">
                        <h3 class="m-card-title" style="font-size: 13px;"><?php echo htmlspecialchars($cat->name); ?></h3>
                        <p class="m-card-subtitle">
                            <?php echo $parent ? '<i class="fa fa-level-up"></i> '.htmlspecialchars($parent->name) : 'Ana Kategori'; ?>
                            &bull; <?php echo count($cat->getProducts()); ?> Ürün
                        </p>
                    </div>
                </div>
            </div>
            <div class="m-card-footer">
                <span class="m-badge m-badge-dark">/<?php echo htmlspecialchars($cat->slug); ?></span>
                
                <?php if ($isDrillDown && isset($childrenCountMap[$cat->slug])): ?>
                <a href="?parent=<?php echo urlencode($cat->slug); ?>" style="font-size:11px;background:var(--surface-2);color:var(--primary);padding:4px 8px;border-radius:12px;text-decoration:none;border:1px solid var(--border);">
                    <i class="fa fa-sitemap"></i> Alt K. (<?php echo $childrenCountMap[$cat->slug]; ?>)
                </a>
                <?php endif; ?>

                <div class="m-card-actions">
                    <a href="<?php echo $baseUrl; ?>/admin/categories/edit/<?php echo $cat->id; ?>" class="m-action-btn edit"><i class="fa fa-pencil"></i></a>
                    <button onclick="confirmDelete('<?php echo $baseUrl; ?>/admin/categories/delete/<?php echo $cat->id; ?>')" class="m-action-btn delete"><i class="fa fa-trash"></i></button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <?php else: ?>
    <div style="text-align:center;padding:64px 20px;color:var(--text-3);">
        <i class="fa fa-tags" style="font-size:56px;opacity:0.15;display:block;margin-bottom:18px;"></i>
        <p style="font-size:15px;"><?php echo $catSearch ? '"'.htmlspecialchars($catSearch).'" için sonuç bulunamadı.' : 'Henüz kategori eklenmemiş.'; ?></p>
        <a href="<?php echo $baseUrl; ?>/admin/categories/create" class="admin-btn admin-btn-primary" style="margin-top:16px;">
            <i class="fa fa-plus-circle"></i> Kategori Ekle
        </a>
    </div>
    <?php endif; ?>

</div>

<script>
initAutoSearch('category-search-input', 'category-search-form', 400);
function confirmDelete(url) {
    adminConfirm('Bu kategoriyi silmek istiyor musunuz?', function() { window.location.href = url; });
}
</script>

<?php if ($isDrillDown): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    function setupDragAndDrop(containerId, itemClass, reorderUrl) {
        const container = document.getElementById(containerId);
        if (!container) return;

        let dragEl = null;

        container.addEventListener('dragstart', function(e) {
            const item = e.target.closest('.' + itemClass);
            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('.' + itemClass);
            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('.' + itemClass);
            if (!item) return;
            item.classList.remove('dragging');
            
            // Collect new order of IDs
            const ids = [];
            container.querySelectorAll('.' + itemClass).forEach(el => {
                ids.push(el.getAttribute('data-id'));
            });

            // Send reorder request
            fetch(reorderUrl, {
                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: ' + (data.error || 'Bilinmeyen hata'), 'error');
                }
            })
            .catch(() => {
                showToast('Sunucu hatası oluştu.', 'error');
            });
        });

        // Touch support for mobile
        container.addEventListener('touchstart', function(e) {
            const item = e.target.closest('.' + itemClass);
            if (!item) return;
            dragEl = item;
            item.classList.add('dragging');
            const touch = e.touches[0];
            dragEl.dataset.startY = touch.clientY;
        }, { passive: true });

        container.addEventListener('touchmove', function(e) {
            if (!dragEl) return;
            const touch = e.touches[0];
            
            // Temporarily hide dragEl to allow elementFromPoint to find the target element underneath
            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('.' + itemClass);
            if (!item || item === dragEl) return;

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

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

            // Collect new order of IDs and send
            const ids = [];
            container.querySelectorAll('.' + itemClass).forEach(el => {
                ids.push(el.getAttribute('data-id'));
            });

            fetch(reorderUrl, {
                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: ' + (data.error || 'Bilinmeyen hata'), 'error');
                }
            })
            .catch(() => {
                showToast('Sunucu hatası oluştu.', 'error');
            });
        });
    }

    setupDragAndDrop('draggable-tbody', 'draggable-row', '<?php echo $baseUrl; ?>/admin/categories/reorder');
    setupDragAndDrop('draggable-cards', 'draggable-card', '<?php echo $baseUrl; ?>/admin/categories/reorder');
});
</script>
<style>
.draggable-row.dragging, .draggable-card.dragging {
    opacity: 0.5;
    background: var(--surface-hover) !important;
}
</style>
<?php endif; ?>

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