<?php
require('connection.inc.php');
require('security.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$wishlist_product_ids = [];

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    $wishlist_sql = "SELECT product_id FROM wishlist WHERE user_id = $user_id";
    $wishlist_result = mysqli_query($conn, $wishlist_sql);
    while ($row = mysqli_fetch_assoc($wishlist_result)) {
        $wishlist_product_ids[] = $row['product_id'];
    }
}

?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
      <meta charset="utf-8">
      <meta http-equiv="x-ua-compatible" content="ie=edge">
      <title>Love Beri</title>
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <!-- Place favicon.ico in the root directory -->
      <link rel="shortcut icon" type="image/x-icon" href="assets/img/allnew/logo.png">

      <!-- CSS here -->
      <link rel="stylesheet" href="assets/css/bootstrap.min.css">
      <link rel="stylesheet" href="assets/css/animate.css">
      <link rel="stylesheet" href="assets/css/swiper-bundle.css">
      <link rel="stylesheet" href="assets/css/slick.css">
      <link rel="stylesheet" href="assets/css/magnific-popup.css">
      <link rel="stylesheet" href="assets/css/spacing.css">
      <link rel="stylesheet" href="assets/css/meanmenu.css">
      <link rel="stylesheet" href="assets/css/nice-select.css">
      <link rel="stylesheet" href="assets/css/fontawesome.min.css">
      <link rel="stylesheet" href="assets/css/icon-dukamarket.css">
      <link rel="stylesheet" href="assets/css/jquery-ui.css">
      <link rel="stylesheet" href="assets/css/main.css">
      <style>
          .form-select.weight-select {
            background-color: #f9f9f9;
            padding: 0px 14px;
            border-radius: 6px;
            font-size: 14px;
        }
      </style>
   </head>
   <body>


      <!-- Scroll-top -->
      <button class="scroll-top scroll-to-target" data-target="html">
         <i class="icon-chevrons-up"></i>
      </button>
      <!-- Scroll-top-end-->

      <!-- header-area-start -->
   <?php 
   include 'header.php'
   ?>
      <!-- header-area-end -->

      <main>

         <!-- breadcrumb-area-start -->
         <div class="breadcrumb__area grey-bg pt-5 pb-5">
            <div class="container">
               <div class="row">
                  <div class="col-lg-12">
                     <div class="tp-breadcrumb__content">
                        <div class="tp-breadcrumb__list">
                           <span class="tp-breadcrumb__active"><a href="index.php">Home</a></span>
                           <span class="dvdr">/</span>
                           <span>Shop</span>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <!-- breadcrumb-area-end -->

         <!-- shop-area-start -->
<?php

// 1. Category filter
$category_filter = '';
if (!empty($_GET['categories'])) {
    $category_ids = array_map('intval', $_GET['categories']);
    $category_filter = " AND p.category_id IN (" . implode(',', $category_ids) . ")";
}

// 2. Sorting
$sort = $_GET['sort'] ?? 'default';
$order_by = 'p.product_id DESC';
if ($sort == 'price_low_high') $order_by = 'pu.unit_price ASC';
if ($sort == 'price_high_low') $order_by = 'pu.unit_price DESC';

// 3. Pagination
$limit = 9;
$page = $_GET['page'] ?? 1;
$offset = ($page - 1) * $limit;

// 4. Count total products
$count_sql = "SELECT COUNT(DISTINCT p.product_id) AS total 
              FROM products p 
              LEFT JOIN product_units pu ON p.product_id = pu.product_id
              WHERE p.deleted_at IS NULL AND p.product_status = 1 $category_filter";
$count_query = mysqli_query($conn, $count_sql);
$total_products = mysqli_fetch_assoc($count_query)['total'];
$total_pages = ceil($total_products / $limit);

// 5. Fetch products
$product_sql = "SELECT DISTINCT p.* 
                FROM products p 
                LEFT JOIN product_units pu ON p.product_id = pu.product_id
                WHERE p.deleted_at IS NULL AND p.product_status = 1 $category_filter
                ORDER BY $order_by
                LIMIT $limit OFFSET $offset";
$product_query = mysqli_query($conn, $product_sql);

$products = [];
while ($row = mysqli_fetch_assoc($product_query)) {
    $products[$row['product_id']] = $row;
}

// 6. Fetch images
$image_sql = "SELECT product_id, MIN(product_img) AS product_img 
              FROM product_imgs 
              WHERE deleted_at IS NULL 
              GROUP BY product_id";
$image_query = mysqli_query($conn, $image_sql);
$product_images = [];
while ($img = mysqli_fetch_assoc($image_query)) {
    $product_images[$img['product_id']] = $img['product_img'];
}

// 7. Fetch units
$unit_sql = "SELECT * FROM product_units WHERE deleted_at IS NULL";
$unit_query = mysqli_query($conn, $unit_sql);
$product_units = [];
while ($unit = mysqli_fetch_assoc($unit_query)) {
    $product_units[$unit['product_id']][] = $unit;
}

// Utility function to build URL with updated query
function build_query($params) {
    return http_build_query(array_merge($_GET, $params));
}
?>

<!-- HTML starts -->
<form method="GET" id="filterForm">
<section class="shop-area-start grey-bg pb-200">
    <div class="container">
        <div class="row">
            <!-- Category Sidebar -->
            <div class="col-xl-2 col-lg-12 col-md-12">
                <div class="tpshop__leftbar">
                    <div class="tpshop__widget mb-30 pb-25">
                        <h4 class="tpshop__widget-title">Product Categories</h4>
                        <?php
                        $cat_sql = "SELECT * FROM categories WHERE deleted_at IS NULL";
                        $cat_res = mysqli_query($conn, $cat_sql);
                        while ($cat = mysqli_fetch_assoc($cat_res)) {
                            $checked = (!empty($_GET['categories']) && in_array($cat['category_id'], $_GET['categories'])) ? "checked" : "";
                            ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="categories[]" value="<?= $cat['category_id'] ?>" <?= $checked ?> onchange="document.getElementById('filterForm').submit();">
                                <label class="form-check-label"><?= htmlspecialchars($cat['category_name']) ?></label>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <!-- Product Content -->
            <div class="col-xl-10 col-lg-12 col-md-12">
                <div class="tpshop__top ml-60">
                    <div class="product__filter-content mb-30">
                        <div class="row align-items-center">
                            <div class="col-sm-4">
                                <div class="product__item-count">
                                    <span>Showing <?= $offset + 1 ?> - <?= min($offset + $limit, $total_products) ?> of <?= $total_products ?> Products</span>
                                </div>
                            </div>
                            <div class="col-sm-4"></div>
                            <div class="col-sm-4">
                                <div class="product__navtabs d-flex justify-content-end align-items-center">
                                    <div class="tp-shop-selector">
                                        <select name="sort" onchange="document.getElementById('filterForm').submit();">
                                            <option value="default" <?= $sort == 'default' ? 'selected' : '' ?>>Default sorting Price</option>
                                            <option value="price_low_high" <?= $sort == 'price_low_high' ? 'selected' : '' ?>>Price: Low to High</option>
                                            <option value="price_high_low" <?= $sort == 'price_high_low' ? 'selected' : '' ?>>Price: High to Low</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Product Grid -->
                    <div class="tab-content" id="nav-tabContent">
                        <div class="tab-pane fade show active whight-product" id="nav-popular">
                            <div class="row row-cols-xxl-3 row-cols-xl-3 row-cols-lg-3 row-cols-md-3 row-cols-sm-2 row-cols-1 tpproduct__shop-item">
                                <?php foreach ($products as $product_id => $product): ?>
                                    <div class="col">
                                        <div class="tpproduct p-relative mb-20">
                                            <div class="tpproduct__thumb p-relative text-center">
                                                <a href="product-details.php/<?= urlencode($product['product_url_name']); ?>">
                                                    <img src="admin/<?= htmlspecialchars($product_images[$product_id] ?? 'default.jpg'); ?>" alt="<?= htmlspecialchars($product['product_name']); ?>">
                                                </a>
                                            </div>
                                            <div class="tpproduct__content">
                                                <h4 class="tpproduct__title">
                                                    <a href="product-details.php/<?= urlencode($product['product_url_name']); ?>">
                                                        <?= htmlspecialchars($product['product_name']); ?>
                                                    </a>
                                                    <div class="tpproduct__shopping">
                                                        <?php
                                                        $is_wishlisted = in_array($product_id, $wishlist_product_ids);
                                                        $wishlist_class = $is_wishlisted ? 'wishlist-active' : '';
                                                        ?>
                                                        <a class="tpproduct__shopping-wishlist <?php echo $wishlist_class; ?>" 
                                                        href="javascript:void(0);" 
                                                        onclick="addOrRemoveFromWishlist(<?php echo $product_id; ?>)">
                                                        <?php if ($is_wishlisted): ?>
                                                        <svg xmlns="http://www.w3.org/2000/svg" class="icon-heart-filled" viewBox="0 0 24 24" fill="red" width="20" height="20">
                                                            <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5
                                                                    2 5.42 4.42 3 7.5 3c1.74 0 3.41 0.81 4.5 2.09
                                                                    C13.09 3.81 14.76 3 16.5 3
                                                                    19.58 3 22 5.42 22 8.5
                                                                    c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                                                        </svg>
                                                        <?php else: ?>
                                                        <i class="icon-heart icons"></i>
                                                        <?php endif; ?>
                                                        </a>
                                                    </div>
                                                </h4>
                                                
                                                        <div class="tpproduct__rating mb-5">
                                                            <a href="#"><i class="icon-star_outline1"></i></a>
                                                            <a href="#"><i class="icon-star_outline1"></i></a>
                                                            <a href="#"><i class="icon-star_outline1"></i></a>
                                                            <a href="#"><i class="icon-star_outline1"></i></a>
                                                            <a href="#"><i class="icon-star_outline1"></i></a>
                                                        </div>
                                                        <div class="mb-10 w-100">
                                                            <label for="weightSelect<?php echo $product_id; ?>" class="form-label fw-semibold mb-2" style="font-size: 14px;">Select Weight</label>
                                                            <select id="weightSelect<?php echo $product_id; ?>" class="form-select weight-select w-100" onchange="updatePrice(this, <?php echo $product_id; ?>)">
                                                            <?php
                                                            if (isset($product_units[$product_id])) {
                                                            foreach ($product_units[$product_id] as $unit) {
                                                            ?>
                                                            <option value="<?php echo htmlspecialchars($unit['unit_id']); ?>"
                                                                data-price="<?php echo htmlspecialchars($unit['unit_price']); ?>"
                                                                data-old="<?php echo htmlspecialchars($unit['unit_price'] * 1.2); ?>">
                                                                <?php echo htmlspecialchars($unit['unit_name']) . ' - ₹' . htmlspecialchars($unit['unit_price']); ?>
                                                            </option>
                                                            <?php
                                                            }
                                                            }
                                                            ?>
                                                            </select>
                                                        </div>

                                                        <?php
                                                        $first_price = isset($product_units[$product_id][0]['unit_price']) ? $product_units[$product_id][0]['unit_price'] : 0;
                                                        ?>
                                                        <div class="tpproduct__price mt-60">
                                                            <span id="currentPrice<?php echo $product_id; ?>" class="current-price">₹<?php echo number_format($first_price, 2); ?></span>
                                                            <del id="oldPrice<?php echo $product_id; ?>" class="old-price">₹<?php echo number_format($first_price * 1.2, 2); ?></del>
                                                        </div>
                   
                                                        
                                                
                                                <div class="tpproduct__hover-btn d-flex justify-content-center mb-10">
                                                    <a class="tp-btn-2" href="javascript:void(0);" onclick="addToCart(this, <?php echo $product_id; ?>)">
                                                            Add to cart
                                                        </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Pagination -->
                    <div class="basic-pagination text-center mt-35">
                        <nav>
                            <ul>
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li>
                                        <?php if ($i == $page): ?>
                                            <span class="current"><?= $i; ?></span>
                                        <?php else: ?>
                                            <a href="?<?= build_query(['page' => $i]) ?>"><?= $i; ?></a>
                                        <?php endif; ?>
                                    </li>
                                <?php endfor; ?>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</form>

<!-- JS to update price on dropdown change -->
<script>
function updatePrice(select, productId) {
    let price = select.options[select.selectedIndex].getAttribute('data-price');
    let old = select.options[select.selectedIndex].getAttribute('data-old');
    document.getElementById('currentPrice' + productId).innerText = '₹' + parseFloat(price).toFixed(2);
    document.getElementById('oldPrice' + productId).innerText = '₹' + parseFloat(old).toFixed(2);
}
</script>

         <!-- shop-area-end -->

         
         <!-- feature-area-start -->
        <?php 
        include 'footer.php'
        ?>
         <!-- feature-area-end -->

      </main>

      <!-- footer-area-start -->
      
      <!-- footer-area-end -->
      
<script>
   $(document).ready(function () {
      $('.weight-select').on('change', function () {
         const selected = $(this).find(':selected');
         const newPrice = selected.data('price');
         const newOldPrice = selected.data('old');

         const productBox = $(this).closest('.tpproduct');
         productBox.find('.current-price').text(`₹${newPrice}.00`);
         productBox.find('.old-price').text(`₹${newOldPrice}.00`);
      });
   });
</script>
 <script>
        function updatePrice(selectElement, productId) {
            var selectedOption = selectElement.options[selectElement.selectedIndex];
            var newPrice = selectedOption.getAttribute('data-price');
            var newOldPrice = selectedOption.getAttribute('data-old');
        
            // Find the price elements and update
            var currentPriceElement = document.querySelector('#currentPrice' + productId);
            var oldPriceElement = document.querySelector('#oldPrice' + productId);
        
            if (currentPriceElement && oldPriceElement) {
                currentPriceElement.textContent = '₹' + parseFloat(newPrice).toFixed(2);
                oldPriceElement.textContent = '₹' + parseFloat(newOldPrice).toFixed(2);
            }
        }
</script>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- add to cart script -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function addToCart(button, productId) {
    const parent = button.closest('.tpproduct'); // or appropriate wrapper if class is different
    const selectEl = parent.querySelector(`#weightSelect${productId}`);
    const unitId = selectEl ? selectEl.value : null;

    console.log("Selected unit ID:", unitId);

    if (!unitId) {
        Swal.fire({
            icon: 'warning',
            title: 'Please select a unit',
            text: 'You must choose a unit to add the product to cart.',
        });
        return;
    }

    fetch("add-to-cart.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: `product_id=${productId}&unit_id=${unitId}`
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            Swal.fire({
                icon: 'success',
                title: 'Added to cart!',
                text: 'Product has been added to your cart.',
                timer: 2000,
                showConfirmButton: false
            });
        } else if (data.status === 'login_required') {
            // Redirect to login with message parameter
            window.location.href = "log-in.php?message=login_required";
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Something went wrong. Please try again.',
            });
        }
    });
}

</script>

<!-- add to wishlist script -->

<script>
function addOrRemoveFromWishlist(productId) {
    fetch('add-to-wishlist.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'product_id=' + encodeURIComponent(productId)
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'added') {
            Swal.fire('Added!', 'Product added to wishlist.', 'success').then(() => {
                location.reload();
            });
        } else if (data.status === 'removed') {
            Swal.fire('Removed!', 'Product removed from wishlist.', 'success').then(() => {
                location.reload();
            });
        } else if (data.status === 'login_required') {
            // Redirect to login with message parameter
            window.location.href = "log-in.php?message=login_required";
        } else {
            Swal.fire('Error', 'Something went wrong.', 'error');
            return;
        }

        // Toggle heart icon style
        document.querySelectorAll(`[onclick="addOrRemoveFromWishlist(${productId})"]`).forEach(el => {
            el.classList.toggle('wishlist-active');
        });
    })
    .catch(err => {
        console.error(err);
        Swal.fire('Error', 'Network error. Try again later.', 'error');
    });
}

</script>




      <!-- JS here -->
      <script src="assets/js/jquery.js"></script>
      <script src="assets/js/waypoints.js"></script>
      <script src="assets/js/bootstrap.bundle.min.js"></script>
      <script src="assets/js/swiper-bundle.js"></script>
      <script src="assets/js/nice-select.js"></script>
      <script src="assets/js/slick.js"></script>
      <script src="assets/js/magnific-popup.js"></script>
      <script src="assets/js/counterup.js"></script>
      <script src="assets/js/wow.js"></script>
      <script src="assets/js/isotope-pkgd.js"></script>
      <script src="assets/js/imagesloaded-pkgd.js"></script>
      <script src="assets/js/countdown.js"></script>
      <script src="assets/js/ajax-form.js"></script>
      <script src="assets/js/jquery-ui.js"></script>
      <script src="assets/js/meanmenu.js"></script>
      <script src="assets/js/main.js"></script>
   </body>
</html>
