<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$basePath = '../../';
include '../../includes/header.php';
?>

<div class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3>Category Management</h3>

        <a href="create.php" class="btn btn-primary">
            Add New Category
        </a>
    </div>

    <div class="card shadow-sm mb-3">
        <div class="card-body">

            <div class="row">

                <div class="col-md-8">
                    <input
                        type="text"
                        id="search"
                        class="form-control"
                        placeholder="Search category..."
                    >
                </div>

                <div class="col-md-2">
                    <select id="limit" class="form-select">
                        <option value="10">10 per page</option>
                        <option value="25">25 per page</option>
                        <option value="50">50 per page</option>
                        <option value="100">100 per page</option>
                    </select>
                </div>

                <div class="col-md-2">
                    <button
                        class="btn btn-success w-100"
                        onclick="loadCategories(1)"
                    >
                        Search
                    </button>
                </div>

            </div>

        </div>
    </div>

    <div id="categories-container"></div>

</div>

<script>
loadCategories();

function loadCategories(page = 1)
{
    let search = document.getElementById('search').value;
    let limit = document.getElementById('limit').value;

    fetch(
        `load_categories.php?search=${encodeURIComponent(search)}&limit=${limit}&page=${page}`
    )
    .then(res => res.text())
    .then(data => {
        document.getElementById('categories-container').innerHTML = data;
    });
}

document.getElementById('search').addEventListener('keyup', function () {
    loadCategories(1);
});

document.getElementById('limit').addEventListener('change', function () {
    loadCategories(1);
});
</script>

<?php include '../../includes/footer.php'; ?>