let currentPage = 1;
let totalPages = 1;
let currentSearch = '';
let currentCategory = '';

// Fetch categories for a page 
async function loadCategories(page = 1, search = '', category_id = '') {
    try {
        const params = new URLSearchParams({
            page: page,
            search: search,
            category_id: category_id
        });
        
        const response = await fetch(`Backend/Process/SearchCategories.php?${params}`);
        const json = await response.json();
        console.log(json);
        
        if (json.status) {
            currentPage = page;
            currentSearch = search;
            currentCategory = category_id;
            totalPages = json.total_pages;
            renderCards(json.data);
            renderPagination();
        } else {
            console.error(json.message || "Failed to load categories");
            const container = document.getElementById("cards");
            container.innerHTML = '<div class="col-12 text-center"><p>No categories found</p></div>';
        }
    } catch (err) {
        console.error(err);
        const container = document.getElementById("cards");
        container.innerHTML = '<div class="col-12 text-center"><p>Error loading categories</p></div>';
    }
}

// Search and filter function
function performSearch() {
    const searchInput = document.querySelector('.search-box input');
    const selectedCategory = document.querySelector('.dropdown-btn').dataset.value || '';
    
    currentPage = 1;
    loadCategories(1, searchInput.value.trim(), selectedCategory);
}

// Render cards inside #cards
function renderCards(categories) {
    const container = document.getElementById("cards");
    container.innerHTML = ""; // clear previous cards

    categories.forEach(cat => {
        const col = document.createElement("div");
        col.className = "col-10 col-md-6 col-lg-4  mb-3";
        col.setAttribute("data-aos", "zoom-in");

        col.innerHTML = `
            <div class="card h-100 shadow-sm border-0 custom-card">
                <div class="card-img-top bg-dark overflow-hidden course-image-container">
                    <img src="Backend/${cat.img_path}" class="img-fluid custom-image-style" alt="${cat.title}">
                </div>
                <div class="card-body p-4">
                    <h5 class="card-title fw-bold course-title">${cat.title}</h5>
                    <p class="card-text text-muted small">${cat.description}</p>
                </div>
                <div class="card-footer bg-white border-top-0 p-4 pt-0">
                    <a href="Details.php?id=${cat.id}" class="btn btn-danger w-100 view-button">View Category</a>
                </div>
            </div>
        `;

        container.appendChild(col);
    });

    // If using AOS library for animation
    if (typeof AOS !== "undefined") {
        AOS.refresh();
    }
}

// Render pagination buttons dynamically
function renderPagination() {
    const paginationDiv = document.querySelector(".pagination");
    if (!paginationDiv) return;
    
    // Clear existing pagination and recreate with correct number of pages
    paginationDiv.innerHTML = "";
    
    // Previous button
    const prevBtn = document.createElement("button");
    prevBtn.className = "page-btn";
    prevBtn.innerText = "Previous";
    prevBtn.disabled = currentPage === 1;
    prevBtn.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage > 1) {
            currentPage--;
            loadCategories(currentPage, currentSearch, currentCategory);
        }
    });
    paginationDiv.appendChild(prevBtn);
    
    // Page number buttons
    for (let i = 1; i <= totalPages; i++) {
        const pageBtn = document.createElement("button");
        pageBtn.className = i === currentPage ? "page-number active" : "page-number";
        pageBtn.innerText = i;
        pageBtn.addEventListener('click', (e) => {
            e.preventDefault();
            currentPage = i;
            loadCategories(currentPage, currentSearch, currentCategory);
        });
        paginationDiv.appendChild(pageBtn);
    }
    
    // Next button
    const nextBtn = document.createElement("button");
    nextBtn.className = "page-btn";
    nextBtn.innerText = "Next";
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.addEventListener('click', (e) => {
        e.preventDefault();
        if (currentPage < totalPages) {
            currentPage++;
            loadCategories(currentPage, currentSearch, currentCategory);
        }
    });
    paginationDiv.appendChild(nextBtn);
}

// Initial load
document.addEventListener("DOMContentLoaded", () => {
    loadCategories(currentPage);
});

