<?php
session_start();
error_reporting(0);
include('includes/config.php');
include_once('includes/settings.php');
$cid = intval($_GET['scid']);
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";
		}
	}
}
// COde for 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 aaded in wishlist');</script>";
		header('location:my-wishlist.php');

	}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include('includes/head.php'); ?>

<body class="cnt-home">

	<header class="header-style-1">

		<!-- ============================================== TOP MENU ============================================== -->
		<?php include('includes/top-header.php'); ?>
		<!-- ============================================== TOP MENU : END ============================================== -->
		<?php include('includes/main-header.php'); ?>
		<!-- ============================================== NAVBAR ============================================== -->
		<?php include('includes/menu-bar.php'); ?>
		<!-- ============================================== NAVBAR : END ============================================== -->

	</header>
	<!-- ============================================== HEADER : END ============================================== -->
	</div><!-- /.breadcrumb -->
	<div class="body-content outer-top-xs">
		<div class='container'>
			<div class='row outer-bottom-sm'>
				<div class='col-lg-3 col-md-4 mb-4 sidebar d-none d-md-block'>
					<!-- 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>

						<!-- 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><!-- /.sidebar -->
				<div class='col-lg-9 col-md-12'>
					<!-- ========================================== SECTION – HERO ========================================= -->


					<!-- Toolbar -->
					<div class="shop-toolbar mb-4">
						<div class="product-count">
							<span id="product-count">
								<?php echo $num_rows = mysqli_num_rows(mysqli_query($con, "SELECT * FROM products where subCategory='$cid' AND approval_status='approved'")); ?>
								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>

					<div class="tab-pane fade show active" id="all">
						<div class="product-slider-container">
							<div class="shop-product-grid">
								<?php
								$ret = mysqli_query($con, "SELECT * FROM products where subCategory='$cid' AND approval_status='approved'");
								$num = mysqli_num_rows($ret);
								if ($num > 0) {
									while ($row = mysqli_fetch_array($ret)) {
										// Calculate discount
										$disc = 0;
										if ($row['productPriceBeforeDiscount'] > 0 && $row['productPriceBeforeDiscount'] > $row['productPrice']) {
											$disc = round((($row['productPriceBeforeDiscount'] - $row['productPrice']) / $row['productPriceBeforeDiscount']) * 100);
										}
										?>
										<div class="am-card product-item wow fadeInUp"
											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 ($disc > 0): ?>
												<div class="discount-tag"><?php echo $disc; ?>% <small>OFF</small></div>
											<?php endif; ?>

											<a href="sub-category.php?pid=<?php echo htmlentities($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">Ghs. <?php echo number_format($row['productPrice'], 2); ?></span>
													<?php if ($disc > 0): ?>
														<span class="p-old-price">Ghs. <?php echo number_format($row['productPriceBeforeDiscount'], 2); ?></span>
													<?php endif; ?>
												</div>
											</a>

											<?php if ($row['productAvailability'] == 'In Stock'): ?>
												<a href="sub-category.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 endif; ?>
										</div>
									<?php }
								} else { ?>
									<div class="no-products-found w-100 text-center py-5" style="grid-column: 1 / -1;">
										<i class="fa fa-inbox"></i>
										<h3>No Products Found</h3>
									</div>
								<?php } ?>
							</div>

						</div>
					</div>
				</div>

			</div>
		</div>
		<script>
			$(document).ready(function () {
				// 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', '');
				});

				$('.filter-section-title').click(function () {
					$(this).closest('.filter-section').toggleClass('collapsed');
				});

				// Real-time Filtering Logic
				const filterProducts = () => {
					const checkedLocs = $('.location-filter:checked').map(function () { return $(this).val(); }).get();
					const inStockOnly = $('#in-stock').is(':checked');

					let visibleCount = 0;

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

						const locMatch = checkedLocs.length === 0 || checkedLocs.includes(itemLoc);
						const stockMatch = !inStockOnly || itemStock === 'in';

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

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

				$('.location-filter, .stock-filter').on('change', 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;
					});

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

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

</body>

</html>