/**
 * Products Page JavaScript
 * Handles dynamic product loading, search, filtering, and pagination
 */

(function () {
    // Private Scope
    let currentPage = 1;
    let searchTimeout = null;

    // Load products on page load
    document.addEventListener('DOMContentLoaded', function () {
        loadProducts();

        // Search functionality
        const searchInput = document.getElementById('searchProducts');
        if (searchInput) {
            searchInput.addEventListener('input', function () {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    currentPage = 1;
                    loadProducts();
                }, 500);
            });
        }

        // Status filter
        const statusFilter = document.getElementById('statusFilter');
        if (statusFilter) {
            statusFilter.addEventListener('change', function () {
                currentPage = 1;
                loadProducts();
            });
        }
    });

    /**
     * Load products from API
     */
    async function loadProducts(page = 1) {
        currentPage = page;

        // Show loading state
        const loadingState = document.getElementById('loadingState');
        const tableContainer = document.getElementById('productsTableContainer');
        const paginationContainer = document.getElementById('paginationContainer');

        if (loadingState) loadingState.style.display = 'block';
        if (tableContainer) tableContainer.style.display = 'none';
        if (paginationContainer) paginationContainer.style.display = 'none';

        // Get filter values
        const search = document.getElementById('searchProducts')?.value || '';
        const status = document.getElementById('statusFilter')?.value || '';

        // Build query string
        const params = new URLSearchParams({
            page: currentPage,
            limit: 10,
            search: search,
            status: status
        });

        try {
            const response = await fetch(`api/products.php?${params.toString()}`);
            const data = await response.json();

            if (data.success) {
                renderProducts(data.data);
                renderPagination(data.pagination);

                // Hide loading, show table
                if (loadingState) loadingState.style.display = 'none';
                if (tableContainer) tableContainer.style.display = 'block';
                if (paginationContainer) paginationContainer.style.display = 'block';
            } else {
                showError(data.message || 'Failed to load products');
            }
        } catch (error) {
            console.error('Error loading products:', error);
            showError('An error occurred while loading products');
        }
    }

    /**
     * Render products in table
     */
    function renderProducts(products) {
        const tbody = document.getElementById('productsTableBody');
        if (!tbody) return;

        if (products.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="9" class="text-center py-5">
                        <i class="las la-box fs-1 text-muted"></i>
                        <p class="text-muted mt-2">No products found</p>
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = products.map((product, index) => {
            const safeTitle = escapeHtml(product.title).replace(/'/g, "\\'");
            return `
            <tr>
                <td style="width: 16px;">
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="check" id="customCheck${index}">
                    </div>
                </td>
                <td class="ps-0">
                    <a href="product-detail.php?slug=${encodeURIComponent(product.slug)}" class="text-decoration-none text-dark d-flex align-items-center">
                        <img src="${product.image}" alt="" height="40" class="rounded me-2">
                        <span class="d-inline-block align-middle">${escapeHtml(product.title)}</span>
                    </a>
                </td>
                <td>
                    <span class="badge ${getStatusBadgeClass(product.status)}">${capitalizeFirst(product.status)}</span>
                </td>
                <td>$${product.price}</td>
                <td>${product.sku || 'N/A'}</td>
                <td>${escapeHtml(product.collections)}</td>
                <td>${product.variant_count > 0 ? product.variant_count + ' variants' : 'No variants'}</td>
                <td>${product.created_at}</td>
                <td>
                    <a href="edit-product.php?slug=${encodeURIComponent(product.slug)}"><i class="las la-pen text-secondary fs-18"></i></a>
                    <a href="javascript:void(0);" 
                       data-bs-toggle="modal" 
                       data-bs-target="#deleteConfirmationModal"
                       data-id="${product.id}"
                       data-title="${safeTitle}"
                       class="text-decoration-none ms-1">
                       <i class="las la-trash-alt text-secondary fs-18"></i>
                    </a>
                </td>
            </tr>
        `;
        }).join('');
    }

    /**
     * Render pagination
     */
    function renderPagination(pagination) {
        const paginationList = document.getElementById('paginationList');
        if (!paginationList) return;

        if (pagination.total_pages <= 1) {
            paginationList.innerHTML = '';
            return;
        }

        let html = '';

        // Previous button
        html += `
            <li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="loadProducts(${currentPage - 1}); return false;" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
        `;

        // Page numbers
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(pagination.total_pages, currentPage + 2);

        if (startPage > 1) {
            html += `<li class="page-item"><a class="page-link" href="#" onclick="loadProducts(1); return false;">1</a></li>`;
            if (startPage > 2) {
                html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            html += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="loadProducts(${i}); return false;">${i}</a>
                </li>
            `;
        }

        if (endPage < pagination.total_pages) {
            if (endPage < pagination.total_pages - 1) {
                html += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
            html += `<li class="page-item"><a class="page-link" href="#" onclick="loadProducts(${pagination.total_pages}); return false;">${pagination.total_pages}</a></li>`;
        }

        // Next button
        html += `
            <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="loadProducts(${currentPage + 1}); return false;" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        `;

        paginationList.innerHTML = html;
    }

    /**
     * Get status badge class
     */
    function getStatusBadgeClass(status) {
        switch (status) {
            case 'active':
                return 'bg-success-subtle text-success';
            case 'draft':
                return 'bg-warning-subtle text-warning';
            case 'archived':
                return 'bg-secondary-subtle text-secondary';
            default:
                return 'bg-secondary-subtle text-secondary';
        }
    }

    /**
     * Capitalize first letter
     */
    function capitalizeFirst(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

    /**
     * Escape HTML
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Show error message
     */
    function showError(message) {
        const loadingState = document.getElementById('loadingState');
        if (loadingState) {
            loadingState.innerHTML = `
                <div class="alert alert-danger" role="alert">
                    <i class="las la-exclamation-triangle me-2"></i>${message}
                </div>
            `;
        }
    }

    // --- Expose Globals ---
    window.loadProducts = loadProducts;

    // --- Delete Functionality with Modal ---
    let productToDeleteId = null;

    // 1. Capture ID when Modal Opens
    const deleteModal = document.getElementById('deleteConfirmationModal');
    if (deleteModal) {
        deleteModal.addEventListener('show.bs.modal', function (event) {
            // Button that triggered the modal
            const button = event.relatedTarget;
            // Extract info from data-* attributes
            productToDeleteId = button.getAttribute('data-id');
            const productTitle = button.getAttribute('data-title');

            // Update the modal's content.
            const modalTitle = deleteModal.querySelector('#deleteProductName');
            if (modalTitle) modalTitle.textContent = productTitle;
        });
    }

    // 2. Handle Confirm Click
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    if (confirmDeleteBtn) {
        confirmDeleteBtn.addEventListener('click', function () {
            if (!productToDeleteId) return;

            // Simple URL-encoded data
            const params = new URLSearchParams();
            params.append('action', 'delete');
            params.append('id', productToDeleteId);

            console.log('Sending delete request via Modal:', params.toString());

            fetch('api/products.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: params
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        // Hide Modal manually
                        const modalInstance = bootstrap.Modal.getInstance(deleteModal);
                        modalInstance.hide();

                        // Logic to handle empty page
                        const rows = document.querySelectorAll('#productsTableBody tr');
                        if (rows.length === 1 && currentPage > 1) {
                            currentPage--;
                        }
                        loadProducts(currentPage);
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('An error occurred while deleting.');
                });
        });
    }
})();
