<?php
$errors = session()->getFlashdata('errors') ?? [];
?>
<div class="space-y-6 max-w-5xl">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-1">
            <div class="glass rounded-2xl p-6 shadow-sm border border-slate-200/60 sticky top-6">
                <div class="flex items-center gap-3 mb-5">
                    <div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                        </svg>
                    </div>
                    <div>
                        <h4 class="text-sm font-bold text-slate-800">Add Category</h4>
                        <p class="text-xs text-slate-500">Create document category</p>
                    </div>
                </div>

                <?php if (!empty($errors)): ?>
                    <div class="mb-5 rounded-xl border border-red-200/70 bg-red-50/50 p-4">
                        <ul class="list-disc list-inside text-xs text-red-700 space-y-0.5">
                            <?php foreach ($errors as $e): ?>
                                <li><?= esc($e) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?= form_open('/admin/categories', ['class' => 'space-y-4']) ?>
                <?= csrf_field() ?>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Name *</label>
                    <input type="text" name="name" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Description</label>
                    <textarea name="description" rows="3" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition resize-y"></textarea>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Sort Order</label>
                    <input type="number" name="sort_order" value="0" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                </div>
                <button type="submit" class="w-full inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md hover:shadow-lg transition-all">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" /></svg>
                    Add Category
                </button>
                </form>
            </div>
        </div>
        <div class="lg:col-span-2">
            <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden">
                <div class="px-6 py-4 bg-slate-50/50 border-b border-slate-200/60">
                    <h4 class="text-sm font-bold text-slate-800">Categories (<?= count($categories ?? []) ?>)</h4>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead><tr class="bg-white/30 border-b border-slate-100">
                            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Name</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Description</th>
                            <th class="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase w-24">Order</th>
                            <th class="px-6 py-3 text-right text-xs font-semibold text-slate-500 uppercase w-32">Actions</th>
                        </tr></thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php if (empty($categories)): ?>
                                <tr><td colspan="4" class="px-6 py-12 text-center text-sm text-slate-500">No categories yet</td></tr>
                            <?php else: ?>
                                <?php foreach ($categories as $c): ?>
                                    <tr class="hover:bg-slate-50/40 transition">
                                        <td class="px-6 py-4 text-sm font-semibold text-slate-700"><?= esc($c['name']) ?></td>
                                        <td class="px-6 py-4 text-sm text-slate-500"><?= !empty($c['description']) ? esc($c['description']) : '—' ?></td>
                                        <td class="px-6 py-4"><span class="inline-flex items-center justify-center min-w-[2rem] h-8 px-2 rounded-lg bg-slate-100 text-xs font-semibold text-slate-700"><?= esc($c['sort_order'] ?? 0) ?></span></td>
                                        <td class="px-6 py-4">
                                            <div class="flex items-center justify-end gap-1">
                                                <button type="button" class="edit-cat-btn p-2 rounded-lg text-blue-600 hover:bg-blue-50 transition"
                                                    data-id="<?= (int) $c['id'] ?>"
                                                    data-name="<?= esc($c['name']) ?>"
                                                    data-description="<?= esc($c['description'] ?? '') ?>"
                                                    data-sort-order="<?= esc($c['sort_order'] ?? 0) ?>"
                                                    title="Edit">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                    </svg>
                                                </button>
                                                <form method="get" action="<?= site_url('/admin/categories/delete/' . $c['id']) ?>" onsubmit="return confirm('Delete this category? Documents in this category will not be deleted.');" class="inline">
                                                    <button type="submit" class="p-2 rounded-lg text-red-500 hover:bg-red-50 transition" title="Delete">
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="editCatModal" class="fixed inset-0 z-50 hidden items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
    <div class="glass w-full max-w-md rounded-2xl shadow-2xl border border-slate-200/60 p-6 fade-in">
        <div class="flex items-center justify-between mb-5">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                </div>
                <div>
                    <h4 class="text-sm font-bold text-slate-800">Edit Category</h4>
                    <p class="text-xs text-slate-500">Update category details</p>
                </div>
            </div>
            <button type="button" id="closeCatModal" class="p-2 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-600 transition">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>

        <?= form_open('', ['id' => 'editCatForm', 'class' => 'space-y-4']) ?>
        <?= csrf_field() ?>

        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Name *</label>
            <input type="text" id="edit_cat_name" name="name" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" required>
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Description</label>
            <textarea id="edit_cat_description" name="description" rows="3" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition resize-y"></textarea>
        </div>
        <div>
            <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Sort Order</label>
            <input type="number" id="edit_cat_sort_order" name="sort_order" class="w-full px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
        </div>

        <div class="flex items-center justify-end gap-3 pt-2">
            <button type="button" id="cancelCatBtn" class="px-4 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold transition">
                Cancel
            </button>
            <button type="submit" class="inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md hover:shadow-lg transition-all">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                </svg>
                Save Changes
            </button>
        </div>

        </form>
    </div>
</div>

<script>
(function () {
    const modal = document.getElementById('editCatModal');
    const form = document.getElementById('editCatForm');
    const editName = document.getElementById('edit_cat_name');
    const editDesc = document.getElementById('edit_cat_description');
    const editSortOrder = document.getElementById('edit_cat_sort_order');
    const closeBtn = document.getElementById('closeCatModal');
    const cancelBtn = document.getElementById('cancelCatBtn');

    function openModal(data) {
        editName.value = data.name;
        editDesc.value = data.description;
        editSortOrder.value = data.sortOrder;
        form.action = <?= json_encode(site_url('/admin/categories/update/')) ?> + data.id;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        setTimeout(() => editName.focus(), 50);
    }

    function closeModal() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    document.querySelectorAll('.edit-cat-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openModal({
                id: btn.getAttribute('data-id'),
                name: btn.getAttribute('data-name'),
                description: btn.getAttribute('data-description'),
                sortOrder: btn.getAttribute('data-sort-order'),
            });
        });
    });

    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', function (e) {
        if (e.target === modal) closeModal();
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && !modal.classList.contains('hidden')) closeModal();
    });
})();
</script>
