<?php
session_start();
error_reporting(0);
include('includes/config.php');
include_once('includes/settings.php');

// Handle Add to Cart
if (isset($_GET['action']) && $_GET['action'] == "add") {
    $id = intval($_GET['id']);
    if (isset($_SESSION['cart'][$id])) {
        $_SESSION['cart'][$id]['quantity']++;
    } else {
        $sql_p = "SELECT * FROM products WHERE id={$id} AND approval_status='approved' AND productAvailability='In Stock' AND stock_quantity > 0";
        $query_p = mysqli_query($con, $sql_p);
        if (mysqli_num_rows($query_p) != 0) {
            $row_p = mysqli_fetch_array($query_p);
            $_SESSION['cart'][$row_p['id']] = array("quantity" => 1, "price" => $row_p['productPrice']);
            echo "<script>alert('Product has been added to the cart')</script>";
            echo "<script type='text/javascript'> document.location ='my-cart.php'; </script>";
        } else {
            $message = "Product ID is invalid";
        }
    }
}

// Handle Wishlist
if (isset($_GET['pid']) && $_GET['action'] == "wishlist") {
    if (strlen($_SESSION['login']) == 0) {
        header('location:login.php');
    } else {
        mysqli_query($con, "insert into wishlist(userId,productId) values('" . $_SESSION['id'] . "','" . $_GET['pid'] . "')");
        echo "<script>alert('Product added to wishlist');</script>";
        header('location:my-wishlist.php');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include('includes/head.php'); ?>

<body class="cnt-home">

    <!-- Header -->
    <header class="header-style-1">
        <?php include('includes/top-header.php'); ?>
        <?php include('includes/main-header.php'); ?>
        <?php include('includes/menu-bar.php'); ?>
    </header>

    <!-- Breadcrumb -->
    <div class="breadcrumb mt-2">
        <div class="container">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                    <li class="breadcrumb-item active">Shop</li>
                </ol>
            </nav>
        </div>
    </div>

    <!-- Shop Banner -->
    <div class="container">
        <div class="category-banner">
            <div class="category-banner-content">
                <h1>Shop All Products</h1>
                <p>Discover our complete collection of quality products</p>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="body-content outer-top-xs">
        <div class='container'>
            <div class='row'>
                <!-- Sidebar Filters -->
                <div class='col-lg-3 col-md-4 mb-4'>
                    <!-- Mobile Filter Toggle -->
                    <button class="mobile-filter-btn d-lg-none mb-3">
                        <i class="fa fa-filter"></i> Filter Products
                    </button>

                    <!-- Sidebar Overlay -->
                    <div class="sidebar-overlay"></div>

                    <div class="shop-sidebar">
                        <!-- Mobile Close Button -->
                        <div class="close-sidebar d-lg-none">
                            <i class="fa fa-times"></i>
                        </div>

                        <h5 class="mb-3">Filter Products</h5>

                        <!-- Category Filter -->
                        <div class="filter-section">
                            <div class="filter-section-title">
                                <span>Categories</span>
                                <i class="fa fa-chevron-down"></i>
                            </div>
                            <div class="filter-options">
                                <div class="filter-option">
                                    <a href="shop.php" class="text-primary font-weight-bold">
                                        All Products
                                    </a>
                                </div>
                                <?php
                                $sql = mysqli_query($con, "select id,categoryName from category");
                                while ($row = mysqli_fetch_array($sql)) {
                                    ?>
                                    <div class="filter-option d-flex align-items-center mb-2">
                                        <input type="checkbox" class="category-filter me-2"
                                            value="<?php echo $row['id']; ?>" id="cat-<?php echo $row['id']; ?>">
                                        <label for="cat-<?php echo $row['id']; ?>" class="mb-0 cursor-pointer">
                                            <?php echo htmlentities($row['categoryName']); ?>
                                        </label>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>

                        <div class="filter-section">
                            <div class="filter-section-title">
                                <span>Price Range (₵)</span>
                                <i class="fa fa-chevron-down"></i>
                            </div>
                            <div class="filter-options">
                                <div class="price-range-slider p-2">
                                    <div class="d-flex gap-2">
                                        <input type="number" id="min-price" placeholder="Min"
                                            class="form-control form-control-sm price-filter">
                                        <input type="number" id="max-price" placeholder="Max"
                                            class="form-control form-control-sm price-filter">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Location Filter -->
                        <div class="filter-section">
                            <div class="filter-section-title">
                                <span>Product Location</span>
                                <i class="fa fa-chevron-down"></i>
                            </div>
                            <div class="filter-options">
                                <?php
                                $locSql = mysqli_query($con, "SELECT * FROM cities ORDER BY city_name ASC");
                                while ($loc = mysqli_fetch_array($locSql)) {
                                    ?>
                                    <div class="filter-option d-flex align-items-center mb-2">
                                        <input type="checkbox" class="location-filter me-2"
                                            value="<?php echo htmlentities($loc['city_name']); ?>"
                                            id="loc-<?php echo $loc['id']; ?>">
                                        <label for="loc-<?php echo $loc['id']; ?>" class="mb-0 cursor-pointer">
                                            <?php echo htmlentities($loc['city_name']); ?>
                                        </label>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>

                        <div class="filter-section">
                            <div class="filter-section-title">
                                <span>Availability</span>
                                <i class="fa fa-chevron-down"></i>
                            </div>
                            <div class="filter-options">
                                <div class="filter-option d-flex align-items-center mb-2">
                                    <input type="checkbox" id="in-stock" class="stock-filter" value="in">
                                    <label for="in-stock" class="ms-2 mb-0 cursor-pointer">In Stock Only</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Product Grid -->
                <div class='col-lg-9 col-md-12'> <!-- Changed to col-md-12 to take full width when sidebar is hidden -->
                    <!-- Toolbar -->
                    <div class="shop-toolbar">
                        <div class="product-count">
                            <span id="product-count">
                                <?php
                                $countQuery = mysqli_query($con, "SELECT COUNT(*) as total FROM products WHERE approval_status='approved'");
                                $countRow = mysqli_fetch_array($countQuery);
                                echo $countRow['total'];
                                ?> Products Found
                            </span>
                        </div>
                        <div class="sort-dropdown">
                            <label for="sort-select">Sort By:</label>
                            <select id="sort-select" class="form-control form-control-sm">
                                <option value="default">Best Match</option>
                                <option value="price-low">Price: Low to High</option>
                                <option value="price-high">Price: High to Low</option>
                                <option value="name">Name: A to Z</option>
                                <option value="newest">Newest First</option>
                            </select>
                        </div>
                    </div>

                    <!-- Product Grid -->
                    <div class="shop-product-grid">
                        <?php
                        $ret = mysqli_query($con, "SELECT * FROM products WHERE approval_status='approved' ORDER BY id DESC");
                        $num = mysqli_num_rows($ret);

                        if ($num > 0) {
                            while ($row = mysqli_fetch_array($ret)) {
                                // Get category name
                                $catQuery = mysqli_query($con, "SELECT categoryName FROM category WHERE id='" . $row['category'] . "'");
                                $catRow = mysqli_fetch_array($catQuery);
                                $categoryName = $catRow['categoryName'];

                                // Calculate discount percentage
                                $discount = 0;
                                if (!empty($row['productPriceBeforeDiscount']) && $row['productPriceBeforeDiscount'] > $row['productPrice']) {
                                    $discount = round((($row['productPriceBeforeDiscount'] - $row['productPrice']) / $row['productPriceBeforeDiscount']) * 100);
                                }
                                ?>
                                <div class="am-card product-item" data-category="<?php echo $row['category']; ?>"
                                    data-price="<?php echo $row['productPrice']; ?>"
                                    data-location="<?php echo htmlentities($row['product_location']); ?>"
                                    data-stock="<?php echo ($row['productAvailability'] == 'In Stock' && $row['stock_quantity'] > 0) ? 'in' : 'out'; ?>"
                                    data-name="<?php echo strtolower(htmlentities($row['productName'])); ?>"
                                    data-id="<?php echo $row['id']; ?>">
                                    <?php if ($discount > 0) { ?>
                                        <div class="discount-tag"><?php echo $discount; ?>% <small>OFF</small></div>
                                    <?php } ?>

                                    <a href="shop.php?pid=<?php echo $row['id']; ?>&action=wishlist" class="btn-wishlist-app"
                                        title="Add to Wishlist">
                                        <i class="fa fa-heart"></i>
                                    </a>

                                    <a href="product-details.php?pid=<?php echo htmlentities($row['id']); ?>"
                                        class="text-decoration-none">
                                        <div class="img-wrap">
                                            <img src="__admin__/productimages/<?php echo htmlentities($row['id']); ?>/<?php echo htmlentities($row['productImage1']); ?>"
                                                alt="<?php echo htmlentities($row['productName']); ?>"
                                                onerror="this.src='assets/images/blank.gif'">
                                        </div>
                                        <div class="p-name"><?php echo htmlentities($row['productName']); ?></div>
                                        <div class="price-wrap">
                                            <span class="p-price">GH₵
                                                <?php echo htmlentities($row['productPrice']); ?></span>
                                            <?php if (!empty($row['productPriceBeforeDiscount']) && $row['productPriceBeforeDiscount'] > $row['productPrice']) { ?>
                                                <span class="p-old-price">GH₵
                                                    <?php echo htmlentities($row['productPriceBeforeDiscount']); ?></span>
                                            <?php } ?>
                                        </div>
                                    </a>

                                    <?php if ($row['productAvailability'] == 'In Stock') { ?>
                                        <a href="shop.php?action=add&id=<?php echo $row['id']; ?>" class="btn-add-cart-app">
                                            <i class="fa fa-shopping-cart"></i>
                                        </a>
                                    <?php } else { ?>
                                        <span class="badge bg-secondary position-absolute" style="bottom:12px; right:12px;">Out of
                                            Stock</span>
                                    <?php } ?>
                                </div>
                                <?php
                            }
                        } else {
                            ?>
                            <div class="col-12">
                                <div class="no-products-found">
                                    <i class="fa fa-inbox"></i>
                                    <h3>No Products Found</h3>
                                    <p>Sorry, we couldn't find any products.</p>
                                    <a href="index.php" class="btn btn-primary mt-3">Back to Homepage</a>
                                </div>
                            </div>
                        <?php } ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($num > 12) { ?>
                        <div class="shop-pagination">
                            <nav aria-label="Product pagination">
                                <ul class="pagination">
                                    <li class="page-item disabled">
                                        <a class="page-link" href="#" tabindex="-1">Previous</a>
                                    </li>
                                    <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                    <li class="page-item"><a class="page-link" href="#">2</a></li>
                                    <li class="page-item"><a class="page-link" href="#">3</a></li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">Next</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>

    <?php include('includes/footer.php'); ?>
    <?php include('includes/foot.php'); ?>

    <!-- Filter Toggle Script -->
    <script>
        $(document).ready(function () {
            // Filter Section Toggle
            $('.filter-section-title').click(function () {
                $(this).closest('.filter-section').toggleClass('collapsed');
            });

            // Mobile Filter Interaction
            $('.mobile-filter-btn').click(function () {
                $('.shop-sidebar').addClass('active');
                $('.sidebar-overlay').addClass('active');
                $('body').css('overflow', 'hidden');
            });

            $('.close-sidebar, .sidebar-overlay').click(function () {
                $('.shop-sidebar').removeClass('active');
                $('.sidebar-overlay').removeClass('active');
                $('body').css('overflow', '');
            });

            // --- Real-time Filtering Logic ---
            const filterProducts = () => {
                const checkedCats = $('.category-filter:checked').map(function () { return $(this).val(); }).get();
                const checkedLocs = $('.location-filter:checked').map(function () { return $(this).val(); }).get();
                const minPrice = parseFloat($('#min-price').val()) || 0;
                const maxPrice = parseFloat($('#max-price').val()) || Infinity;
                const inStockOnly = $('#in-stock').is(':checked');

                let visibleCount = 0;

                $('.product-item').each(function () {
                    const itemCat = $(this).data('category').toString();
                    const itemLoc = $(this).data('location').toString();
                    const itemPrice = parseFloat($(this).data('price'));
                    const itemStock = $(this).data('stock');

                    const catMatch = checkedCats.length === 0 || checkedCats.includes(itemCat);
                    const locMatch = checkedLocs.length === 0 || checkedLocs.includes(itemLoc);
                    const priceMatch = itemPrice >= minPrice && itemPrice <= maxPrice;
                    const stockMatch = !inStockOnly || itemStock === 'in';

                    if (catMatch && locMatch && priceMatch && stockMatch) {
                        $(this).show();
                        visibleCount++;
                    } else {
                        $(this).hide();
                    }
                });

                $('#product-count').text(visibleCount + ' Products Found');

                // Show empty state if none
                if (visibleCount === 0) {
                    if ($('.no-products-found').length === 0) {
                        $('.shop-product-grid').append('<div class="no-products-found w-100 text-center py-5"><h3>No matches found</h3><p>Try adjusting your filters</p></div>');
                    }
                } else {
                    $('.no-products-found').remove();
                }
            };

            // Listen for changes
            $('.category-filter, .location-filter, .stock-filter, .price-filter').on('change input', filterProducts);

            // --- Real-time Sorting Logic ---
            $('#sort-select').on('change', function () {
                const sortBy = $(this).val();
                const grid = $('.shop-product-grid');
                const items = grid.children('.product-item').get();

                items.sort(function (a, b) {
                    const valA = parseFloat($(a).data('price'));
                    const valB = parseFloat($(b).data('price'));
                    const nameA = $(a).data('name');
                    const nameB = $(b).data('name');
                    const idA = parseInt($(a).data('id'));
                    const idB = parseInt($(b).data('id'));

                    if (sortBy === 'price-low') return valA - valB;
                    if (sortBy === 'price-high') return valB - valA;
                    if (sortBy === 'name') return nameA.localeCompare(nameB);
                    if (sortBy === 'newest') return idB - idA;
                    return idB - idA; // default
                });

                $.each(items, function (i, li) {
                    grid.append(li);
                });
            });
        });
    </script>
</body>

</html>