<?php
$pageTitle = 'Manage Categories';
ob_start();
?>

<div class="bg-dark rounded-lg shadow-lg p-6">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
        <h2 class="text-2xl font-bold mb-4 md:mb-0">Manage Categories</h2>
        
        <button id="addCategoryBtn" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded">
            <i class="fas fa-plus mr-2"></i> Add Category
        </button>
    </div>
    
    <!-- Search Bar -->
    <div class="mb-6">
        <div class="relative">
            <input type="text" id="categorySearch" placeholder="Search categories..." 
                   class="w-full bg-gray-800 text-white border border-gray-700 rounded-lg px-4 py-2 pl-10 focus:outline-none focus:border-primary">
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
        </div>
    </div>
    
    <?php if (!empty($success)): ?>
        <div class="bg-green-800 text-white p-4 rounded-md mb-6">
            <i class="fas fa-check-circle mr-2"></i> <?= htmlspecialchars($success) ?>
        </div>
    <?php endif; ?>
    
    <?php if (!empty($error)): ?>
        <div class="bg-red-800 text-white p-4 rounded-md mb-6">
            <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>
    
    <!-- Add Category Modal -->
    <div id="addCategoryModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
        <div class="bg-dark rounded-lg shadow-lg p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">Add New Category</h3>
                <button id="closeAddModal" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form action="/admin/categories/add" method="POST">
                <div class="mb-4">
                    <label for="name" class="block text-sm font-medium text-gray-400 mb-1">Category Name</label>
                    <input 
                        type="text" 
                        id="name" 
                        name="name" 
                        required
                        class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                </div>
                
                <div class="mb-4">
                    <label for="slug" class="block text-sm font-medium text-gray-400 mb-1">Slug (Optional)</label>
                    <input 
                        type="text" 
                        id="slug" 
                        name="slug" 
                        class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                    <p class="text-xs text-gray-500 mt-1">Leave empty to generate automatically from name.</p>
                </div>
                
                <div class="mb-4">
                    <label for="sort_order" class="block text-sm font-medium text-gray-400 mb-1">Sort Order</label>
                    <input 
                        type="number" 
                        id="sort_order" 
                        name="sort_order" 
                        value="0"
                        class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                    <p class="text-xs text-gray-500 mt-1">Lower numbers appear first.</p>
                </div>
                
                <div class="flex justify-end">
                    <button type="button" id="cancelAddBtn" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded mr-2">
                        Cancel
                    </button>
                    <button type="submit" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded">
                        Add Category
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Edit Category Modal -->
    <div id="editCategoryModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
        <div class="bg-dark rounded-lg shadow-lg p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">Edit Category</h3>
                <button id="closeEditModal" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form action="/admin/categories/edit" method="POST">
                <input type="hidden" id="edit_id" name="id">
                
                <div class="mb-4">
                    <label for="edit_name" class="block text-sm font-medium text-gray-400 mb-1">Category Name</label>
                    <input 
                        type="text" 
                        id="edit_name" 
                        name="name" 
                        required
                        class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                </div>
                
                <div class="mb-4">
                    <label for="edit_slug" class="block text-sm font-medium text-gray-400 mb-1">Slug</label>
                    <input 
                        type="text" 
                        id="edit_slug" 
                        name="slug" 
                        class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                    <p class="text-xs text-gray-500 mt-1">Leave empty to generate automatically from name.</p>
                </div>
                
                <div class="mb-4">
                    <label for="edit_sort_order" class="block text-sm font-medium text-gray-400 mb-1">Sort Order</label>
                    <input 
                        type="number" 
                        id="edit_sort_order" 
                        name="sort_order" 
                        class="bg-sidebar-bg border border-gray-700 rounded px-4 py-2 w-full focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                    <p class="text-xs text-gray-500 mt-1">Lower numbers appear first.</p>
                </div>
                
                <div class="flex justify-end">
                    <button type="button" id="cancelEditBtn" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded mr-2">
                        Cancel
                    </button>
                    <button type="submit" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded">
                        Update Category
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <?php if (empty($categories)): ?>
        <div class="bg-gray-800 rounded-lg p-6 text-center">
            <p class="text-gray-400">No categories found.</p>
        </div>
    <?php else: ?>
        <div class="overflow-x-auto">
            <table class="min-w-full bg-dark rounded-lg overflow-hidden">
                <thead class="bg-gray-800">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Order</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">ID</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Name</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Slug</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Games</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-800">
                    <?php foreach ($categories as $category): ?>
                        <tr class="hover:bg-gray-800">
                            <td class="px-4 py-3 whitespace-nowrap text-center">
                                <span class="text-sm text-gray-400"><?= $category['sort_order'] !== null ? $category['sort_order'] : 'Auto' ?></span>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap"><?= $category['id'] ?></td>
                            <td class="px-4 py-3">
                                <div class="text-sm font-medium"><?= htmlspecialchars($category['name']) ?></div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="text-sm text-gray-400"><?= htmlspecialchars($category['slug']) ?></div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-700 text-gray-300">
                                    <?= $category['game_count'] ?> games
                                </span>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                                <button 
                                    class="text-primary hover:text-secondary mr-3 edit-category-btn" 
                                    data-id="<?= $category['id'] ?>"
                                    data-name="<?= htmlspecialchars($category['name']) ?>"
                                    data-slug="<?= htmlspecialchars($category['slug']) ?>"
                                    data-sort-order="<?= $category['sort_order'] ?? '' ?>"
                                >
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                
                                <form action="/admin/categories/delete" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this category? All games in this category will be set to no category.');">
                                    <input type="hidden" name="category_id" value="<?= $category['id'] ?>">
                                    <button type="submit" class="text-red-500 hover:text-red-400">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Pagination -->
<?php if (isset($totalPages) && $totalPages > 1): ?>
    <div class="mt-6 flex justify-center">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
            <?php if ($page > 1): ?>
                <a href="/admin/categories?page=<?= $page - 1 ?>" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-700 bg-sidebar-bg text-sm font-medium text-gray-300 hover:bg-gray-700">
                    <span class="sr-only">Previous</span>
                    <i class="fas fa-chevron-left"></i>
                </a>
            <?php endif; ?>
            
            <?php
            $startPage = max(1, $page - 2);
            $endPage = min($totalPages, $startPage + 4);
            
            if ($endPage - $startPage < 4 && $startPage > 1) {
                $startPage = max(1, $endPage - 4);
            }
            
            for ($i = $startPage; $i <= $endPage; $i++):
            ?>
                <a href="/admin/categories?page=<?= $i ?>" class="relative inline-flex items-center px-4 py-2 border border-gray-700 <?= $i === $page ? 'bg-gray-700 text-white' : 'bg-sidebar-bg text-gray-300 hover:bg-gray-700' ?> text-sm font-medium">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
                <a href="/admin/categories?page=<?= $page + 1 ?>" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-700 bg-sidebar-bg text-sm font-medium text-gray-300 hover:bg-gray-700">
                    <span class="sr-only">Next</span>
                    <i class="fas fa-chevron-right"></i>
                </a>
            <?php endif; ?>
        </nav>
    </div>
<?php endif; ?>

<script>
    // Add Category Modal
    const addCategoryBtn = document.getElementById('addCategoryBtn');
    const addCategoryModal = document.getElementById('addCategoryModal');
    const closeAddModal = document.getElementById('closeAddModal');
    const cancelAddBtn = document.getElementById('cancelAddBtn');
    
    addCategoryBtn.addEventListener('click', () => {
        addCategoryModal.classList.remove('hidden');
    });
    
    closeAddModal.addEventListener('click', () => {
        addCategoryModal.classList.add('hidden');
    });
    
    cancelAddBtn.addEventListener('click', () => {
        addCategoryModal.classList.add('hidden');
    });
    
    // Edit Category Modal
    const editCategoryModal = document.getElementById('editCategoryModal');
    const closeEditModal = document.getElementById('closeEditModal');
    const cancelEditBtn = document.getElementById('cancelEditBtn');
    const editButtons = document.querySelectorAll('.edit-category-btn');
    
    editButtons.forEach(button => {
        button.addEventListener('click', () => {
            const id = button.getAttribute('data-id');
            const name = button.getAttribute('data-name');
            const slug = button.getAttribute('data-slug');
            const sortOrder = button.getAttribute('data-sort-order');
            
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_slug').value = slug;
            document.getElementById('edit_sort_order').value = sortOrder;
            
            editCategoryModal.classList.remove('hidden');
        });
    });
    
    closeEditModal.addEventListener('click', () => {
        editCategoryModal.classList.add('hidden');
    });
    
    cancelEditBtn.addEventListener('click', () => {
        editCategoryModal.classList.add('hidden');
    });
    
    // Close modals when clicking outside
    window.addEventListener('click', (e) => {
        if (e.target === addCategoryModal) {
            addCategoryModal.classList.add('hidden');
        }
        if (e.target === editCategoryModal) {
            editCategoryModal.classList.add('hidden');
        }
    });
    
    // Search functionality
    const searchInput = document.getElementById('categorySearch');
    const tableRows = document.querySelectorAll('tbody tr');
    
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        
        tableRows.forEach(row => {
            const categoryName = row.querySelector('td:nth-child(3)').textContent.toLowerCase();
            const categorySlug = row.querySelector('td:nth-child(4)').textContent.toLowerCase();
            
            if (categoryName.includes(searchTerm) || categorySlug.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });


</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>