<!-- Page Header -->
<div class="page-header">
    <div>
        <h1>Categories</h1>
        <p>Manage menu categories and their icons.</p>
    </div>
    <?php if (\Core\Auth::can('category.create')): ?>
    <a href="<?= url('categories/create') ?>" class="btn btn-accent">
        <i class="bi bi-plus-lg me-1"></i> Add Category
    </a>
    <?php endif; ?>
</div>

<!-- Stats Bar -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background:#fff4ee;color:#f97316;"><i class="bi bi-tags-fill"></i></div>
            <div>
                <div class="stat-value"><?= $total ?></div>
                <div class="stat-label">Total Categories</div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background:#f0fdf4;color:#22c55e;"><i class="bi bi-check-circle-fill"></i></div>
            <div>
                <div class="stat-value"><?= count(array_filter($categories, fn($c) => $c['is_active'])) ?></div>
                <div class="stat-label">Active</div>
            </div>
        </div>
    </div>
</div>

<!-- Table Card -->
<div class="card">
    <div class="card-header">
        <i class="bi bi-tags text-accent"></i>
        <h6 class="card-title">All Categories</h6>
        <div class="ms-auto">
            <div class="input-group input-group-sm" style="width:220px;">
                <span class="input-group-text bg-white"><i class="bi bi-search text-secondary"></i></span>
                <input type="text" class="form-control" id="catSearch" placeholder="Search categories…">
            </div>
        </div>
    </div>

    <div class="card-body p-0">
        <?php if (empty($categories)): ?>
            <div class="text-center py-5 text-secondary">
                <i class="bi bi-tags fs-1 d-block mb-3 opacity-25"></i>
                <h6>No categories yet</h6>
                <p class="mb-3">Start by adding your first menu category.</p>
                <a href="<?= url('categories/create') ?>" class="btn btn-accent btn-sm">
                    <i class="bi bi-plus-lg me-1"></i> Add Category
                </a>
            </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table fd-table mb-0" data-search="catSearch">
                <thead>
                    <tr>
                        <th style="width:60px;">#</th>
                        <th style="width:80px;">Icon</th>
                        <th>Name</th>
                        <th>Slug</th>
                        <th class="text-center">Items</th>
                        <th class="text-center">Sort</th>
                        <th class="text-center">Status</th>
                        <th class="text-center" style="width:140px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $i => $cat): ?>
                    <tr>
                        <td class="text-secondary"><?= (($page - 1) * ITEMS_PER_PAGE) + $i + 1 ?></td>
                        <td>
                            <?php if ($cat['icon_image']): ?>
                                <img src="<?= e(upload_url($cat['icon_image'])) ?>"
                                     alt="<?= e($cat['name']) ?>"
                                     class="img-preview"
                                     style="width:48px;height:48px;object-fit:cover;border-radius:10px;">
                            <?php else: ?>
                                <div class="d-flex align-items-center justify-content-center bg-light rounded-2"
                                     style="width:48px;height:48px;">
                                    <i class="bi bi-image text-secondary"></i>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="fw-600"><?= e($cat['name']) ?></span>
                        </td>
                        <td><code class="text-secondary" style="font-size:.78rem;"><?= e($cat['slug']) ?></code></td>
                        <td class="text-center">
                            <span class="badge bg-light text-dark border"><?= $cat['item_count'] ?></span>
                        </td>
                        <td class="text-center">
                            <input type="number" class="form-control form-control-sm sort-input mx-auto text-center"
                                   style="width:72px;"
                                   value="<?= (int)$cat['sort_order'] ?>"
                                   min="0" step="1"
                                   data-url="<?= url('categories/' . $cat['id'] . '/sort') ?>"
                                   title="Edit order and press Enter">
                        </td>
                        <td class="text-center">
                            <div class="form-check form-switch d-flex justify-content-center mb-0">
                                <input class="form-check-input toggle-status"
                                       type="checkbox"
                                       role="switch"
                                       <?= $cat['is_active'] ? 'checked' : '' ?>
                                       data-url="<?= url('categories/' . $cat['id'] . '/toggle') ?>"
                                       <?= !\Core\Auth::can('category.edit') ? 'disabled' : '' ?>>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="d-flex gap-1 justify-content-center">
                                <?php if (\Core\Auth::can('category.edit')): ?>
                                <a href="<?= url('categories/' . $cat['id'] . '/edit') ?>"
                                   class="btn btn-sm btn-outline-primary" title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <?php endif; ?>
                                <?php if (\Core\Auth::can('category.delete')): ?>
                                <form method="POST" action="<?= url('categories/' . $cat['id'] . '/delete') ?>">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-sm btn-outline-danger"
                                            title="Delete"
                                            data-confirm="Delete category '<?= e($cat['name']) ?>'? This cannot be undone.">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total > ITEMS_PER_PAGE): ?>
        <div class="d-flex justify-content-between align-items-center px-4 py-3 border-top">
            <small class="text-secondary">
                Showing <?= count($categories) ?> of <?= $total ?> categories
            </small>
            <?= paginate($total, $page, ITEMS_PER_PAGE, url('categories')) ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.sort-input').forEach(function (inp) {
        var last = inp.value;
        function save() {
            var val = parseInt(inp.value || '0', 10);
            if (isNaN(val) || val < 0) { val = 0; inp.value = 0; }
            if (String(val) === String(last)) return;   // unchanged
            var csrf = document.querySelector('meta[name="csrf-token"]');
            csrf = csrf ? csrf.content : '';
            inp.disabled = true;
            fetch(inp.dataset.url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': csrf,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: '_csrf_token=' + encodeURIComponent(csrf) + '&sort_order=' + val
            })
            .then(function (r) { return r.json(); })
            .then(function (d) {
                inp.disabled = false;
                if (d && d.success) {
                    last = String(val);
                    inp.classList.remove('is-invalid');
                    inp.classList.add('is-valid');
                    setTimeout(function () { inp.classList.remove('is-valid'); }, 900);
                } else {
                    inp.classList.add('is-invalid');
                }
            })
            .catch(function () { inp.disabled = false; inp.classList.add('is-invalid'); });
        }
        inp.addEventListener('change', save);
        inp.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); inp.blur(); }
        });
    });
});
</script>
