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

// Cart Logic
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']);
		} else {
			$message = "Product ID is invalid";
		}
	}
	echo "<script>alert('Product has been added to the cart')</script>";
	echo "<script type='text/javascript'> document.location ='my-cart.php'; </script>";
}

// Wishlist Logic
if (isset($_GET['pid']) && isset($_GET['action']) && $_GET['action'] == "wishlist") {
	if (strlen($_SESSION['login']) == 0) {
		header('location:login.php');
	} else {
		$pid = intval($_GET['pid']);
		mysqli_query($con, "insert into wishlist(userId,productId) values('" . $_SESSION['id'] . "','$pid')");
		echo "<script>alert('Product added in 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>

	<!-- Main Body Wrapper -->
	<div class="body-content outer-top-xs mt-0" id="top-banner-and-menu">
		<div class="container">

			<!-- ==============================================
				 HERO SECTION (3 Cols)
				 ============================================== -->
			<div class="hero-wrapper">

				<!-- Col 1: Categories Sidebar -->
				<div class="hero-sidebar d-none d-lg-block">
					<div class="sidebar-menu-wrapper">
						<?php
						$sql = mysqli_query($con, "SELECT id, categoryName FROM category LIMIT 10");
						$catCount = mysqli_num_rows($sql);
						if ($catCount > 0):
							while ($row = mysqli_fetch_array($sql)):
								$catId = $row['id'];
								// Fetch subcategories for megamenu flyout
								$subSql = mysqli_query($con, "SELECT id, subcategory FROM subcategory WHERE categoryid = '$catId' LIMIT 8");
								$subcategories = [];
								while ($subRow = mysqli_fetch_array($subSql)) {
									$subcategories[] = $subRow;
								}

								// Icon mapping
								$icon = "fa-tag";
								$name = strtolower($row['categoryName']);
								if (strpos($name, 'phone') !== false || strpos($name, 'mobile') !== false)
									$icon = "fa-mobile";
								elseif (strpos($name, 'laptop') !== false || strpos($name, 'computer') !== false)
									$icon = "fa-desktop";
								elseif (strpos($name, 'tv') !== false || strpos($name, 'television') !== false)
									$icon = "fa-television";
								elseif (strpos($name, 'fashion') !== false || strpos($name, 'cloth') !== false)
									$icon = "fa-shopping-bag";
								elseif (strpos($name, 'home') !== false || strpos($name, 'appliance') !== false)
									$icon = "fa-home";
								elseif (strpos($name, 'beauty') !== false || strpos($name, 'health') !== false)
									$icon = "fa-heart";
								elseif (strpos($name, 'electronics') !== false)
									$icon = "fa-plug";
								elseif (strpos($name, 'sport') !== false)
									$icon = "fa-futbol-o";
								elseif (strpos($name, 'baby') !== false || strpos($name, 'kid') !== false)
									$icon = "fa-child";
								elseif (strpos($name, 'gaming') !== false)
									$icon = "fa-gamepad";
								?>
								<div class="category-item">
									<a href="category.php?cid=<?php echo $row['id']; ?>" class="nav-link">
										<i class="fa <?php echo $icon; ?>"></i>
										<span><?php echo htmlentities($row['categoryName']); ?></span>
										<?php if (!empty($subcategories)): ?>
											<i class="fa fa-angle-right float-right menu-chevron"></i>
										<?php endif; ?>
									</a>
									<?php if (!empty($subcategories)): ?>
										<div class="category-flyout">
											<div class="flyout-header"><?php echo htmlentities($row['categoryName']); ?></div>
											<div class="flyout-divider"></div>
											<div class="flyout-links-grid">
												<?php foreach ($subcategories as $sub): ?>
													<a href="sub-category.php?scid=<?php echo $sub['id']; ?>" class="flyout-item">
														<span class="bullet-dot"></span>
														<span class="flyout-text"><?php echo htmlentities($sub['subcategory']); ?></span>
													</a>
												<?php endforeach; ?>
											</div>
										</div>
									<?php endif; ?>
								</div>
								<?php
							endwhile;
						else:
							?>
							<div class="p-3 text-muted text-center">No categories yet</div>
						<?php endif; ?>
						<a href="shop-categories.php" class="nav-link see-all-link">
							<i class="fa fa-th-large"></i>
							<span>See All Categories</span>
						</a>
					</div>
				</div>

				<!-- Col 2: Main Slider -->
				<div class="hero-slider" style="position: relative;">
					<div id="hero-carousel" class="owl-carousel owl-theme">
						<?php
						$banner_query = mysqli_query($con, "SELECT * FROM sliders WHERE status=1 ORDER BY id DESC");
						if (mysqli_num_rows($banner_query) > 0):
							while ($row = mysqli_fetch_array($banner_query)):
								?>
								<div class="item">
									<a href="<?php echo $row['link'] ? htmlentities($row['link']) : '#'; ?>">
										<img src="assets/images/sliders/<?php echo htmlentities($row['image']); ?>"
											alt="<?php echo htmlentities($row['title']); ?>">
									</a>
								</div>
								<?php
							endwhile;
						else:
							// Fallback to glob if no DB banners
							$sliderImages = glob("assets/images/sliders/*.{jpg,png,gif}", GLOB_BRACE);
							if (!empty($sliderImages)):
								foreach (array_slice($sliderImages, 0, 5) as $img):
									?>
									<div class="item">
										<img src="<?php echo $img; ?>" alt="Promo Banner">
									</div>
									<?php
								endforeach;
							else:
								?>
								<div class="item"
									style="background: linear-gradient(135deg, var(--am-primary), #00b300); display:flex; align-items:center; justify-content:center; height:100%;">
									<div class="text-center text-white p-4">
										<h2>Welcome to Awesome Mall</h2>
										<p>Best deals on Electronics, Fashion & More!</p>
									</div>
								</div>
							<?php endif;
						endif; ?>
					</div>

					<!-- Overlay Shop Button -->
					<div class="slider-overlay-btn">
						<a href="shop.php" class="btn-shop-now">
							<i class="fa fa-shopping-bag mr-2"></i> Shop Now
						</a>
					</div>
				</div>

				<!-- Col 3: Right CTA -->
				<div class="hero-right d-none d-lg-flex">
					<a href="track-orders.php" class="cta-box">
						<div class="cta-icon"><i class="fa fa-truck"></i></div>
						<div class="cta-text">
							<h6>Track Your Order</h6>
							<p>Stay up to date</p>
						</div>
					</a>
					<a href="my-account.php" class="cta-box">
						<div class="cta-icon"><i class="fa fa-user-circle"></i></div>
						<div class="cta-text">
							<h6>My Account</h6>
							<p>Manage profile</p>
						</div>
					</a>
					<a href="contact-us.php" class="cta-box">
						<div class="cta-icon"><i class="fa fa-headphones"></i></div>
						<div class="cta-text">
							<h6>Need Help?</h6>
							<p>Contact support</p>
						</div>
					</a>
				</div>

			</div>
			<!-- /.hero-wrapper -->


			<!-- ==============================================
				 FLASH SALES / DEALS SECTION
				 ============================================== -->
			<?php
			// Get products with discounts
			$flashQuery = mysqli_query($con, "SELECT * FROM products WHERE productPriceBeforeDiscount > productPrice AND approval_status='approved' ORDER BY id DESC LIMIT 12");
			$flashCount = mysqli_num_rows($flashQuery);

			// Fallback to recent products if no discounts
			if ($flashCount == 0) {
				$flashQuery = mysqli_query($con, "SELECT * FROM products WHERE approval_status='approved' ORDER BY id DESC LIMIT 12");
				$flashCount = mysqli_num_rows($flashQuery);
			}

			if ($flashCount > 0):
				?>
				<div class="flash-sales-container">
					<div class="flash-header">
						<div class="title">
							<i class="fa fa-bolt"></i> HOT DEALS
						</div>

						<a href="search-result.php" class="see-all">SEE ALL <i class="fa fa-angle-right ml-1"></i></a>
					</div>

					<div class="flash-products">
						<div class="owl-carousel home-owl-carousel custom-carousel owl-theme" data-item="6">
							<?php
							while ($row = mysqli_fetch_array($flashQuery)):
								$disc = 0;
								if ($row['productPriceBeforeDiscount'] > 0 && $row['productPriceBeforeDiscount'] > $row['productPrice']) {
									$disc = round((($row['productPriceBeforeDiscount'] - $row['productPrice']) / $row['productPriceBeforeDiscount']) * 100);
								}
								?>
								<div class="item item-carousel">
									<div class="am-card">
										<?php if ($disc > 0): ?>
											<div class="discount-tag"><?php echo $disc; ?>% <small>OFF</small></div>
										<?php endif; ?>

										<a href="index.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 htmlspecialchars(html_entity_decode($row['productName'], ENT_QUOTES)); ?>"
													onerror="this.src='assets/images/blank.gif'">
											</div>
											<div class="p-name"><?php echo html_entity_decode($row['productName'], ENT_QUOTES); ?></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>

										<!-- Add to Cart Button -->
										<?php if ($row['productAvailability'] == 'In Stock'): ?>
											<a href="index.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="btn-out-stock">Out of Stock</span>
										<?php endif; ?>
									</div>
								</div>
							<?php endwhile; ?>
						</div>
					</div>
				</div>
			<?php endif; ?>


			<!-- ==============================================
				 NEW ARRIVALS
				 ============================================== -->
			<?php
			$newQuery = mysqli_query($con, "SELECT * FROM products WHERE approval_status='approved' ORDER BY id DESC LIMIT 12");
			$newCount = mysqli_num_rows($newQuery);

			if ($newCount > 0):
				?>
				<div class="white-box">
					<div class="section-header-plain">
						<span><i class="fa fa-star mr-2"></i>New Arrivals</span>
						<a href="search-result.php" class="see-all-link">See All ></a>
					</div>
					<div class="p-3">
						<div class="owl-carousel home-owl-carousel custom-carousel owl-theme" data-item="6">
							<?php while ($row = mysqli_fetch_array($newQuery)): ?>
								<div class="item item-carousel">
									<div class="am-card">
										<a href="index.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 htmlspecialchars(html_entity_decode($row['productName'], ENT_QUOTES)); ?>"
													onerror="this.src='assets/images/blank.gif'">
											</div>
											<div class="p-name"><?php echo html_entity_decode($row['productName'], ENT_QUOTES); ?></div>
											<div class="price-wrap">
												<span class="p-price">Ghs.
													<?php echo number_format($row['productPrice'], 2); ?></span>
											</div>
										</a>
										<?php if ($row['productAvailability'] == 'In Stock'): ?>
											<a href="index.php?action=add&id=<?php echo $row['id']; ?>" class="btn-add-cart-app">
												<i class="fa fa-shopping-cart"></i>
											</a>
										<?php endif; ?>
									</div>
								</div>
							<?php endwhile; ?>
						</div>
					</div>
				</div>
			<?php endif; ?>


			<!-- ==============================================
				 PRODUCTS BY CATEGORY (Dynamic)
				 ============================================== -->
			<?php
			// Get first 3 categories with products
			$catQuery = mysqli_query($con, "SELECT DISTINCT c.id, c.categoryName FROM category c 
											INNER JOIN products p ON p.category = c.id 
											WHERE p.approval_status = 'approved'
											LIMIT 3");

			while ($cat = mysqli_fetch_array($catQuery)):
				$catId = $cat['id'];
				$catName = $cat['categoryName'];
				$prodQuery = mysqli_query($con, "SELECT * FROM products WHERE category = '$catId' AND approval_status='approved' LIMIT 6");
				$prodCount = mysqli_num_rows($prodQuery);

				if ($prodCount > 0):
					?>
					<div class="white-box">
						<div class="section-header-plain">
							<span><?php echo htmlentities($catName); ?></span>
							<a href="category.php?cid=<?php echo $catId; ?>" class="see-all-link">See All ></a>
						</div>
						<div class="p-3">
							<div class="row">
								<?php while ($row = mysqli_fetch_array($prodQuery)): ?>
									<div class="col-6 col-md-4 col-lg-2 mb-3">
										<div class="am-card h-100">
											<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 htmlspecialchars(html_entity_decode($row['productName'], ENT_QUOTES)); ?>"
														onerror="this.src='assets/images/blank.gif'">
												</div>
												<div class="p-name"><?php echo html_entity_decode($row['productName'], ENT_QUOTES); ?></div>
												<div class="price-wrap">
													<span class="p-price">Ghs.
														<?php echo number_format($row['productPrice'], 2); ?></span>
												</div>
											</a>
										</div>
									</div>
								<?php endwhile; ?>
							</div>
						</div>
					</div>
					<?php
				endif;
			endwhile;
			?>


			<!-- ==============================================
				 ALL PRODUCTS GRID
				 ============================================== -->
			<?php
			$allQuery = mysqli_query($con, "SELECT * FROM products WHERE approval_status='approved' ORDER BY RAND() LIMIT 18");
			$allCount = mysqli_num_rows($allQuery);

			if ($allCount > 0):
				?>
				<div class="white-box">
					<div class="section-header-plain">
						<span><i class="fa fa-th mr-2"></i>Explore Products</span>
						<a href="search-result.php" class="see-all-link">View All ></a>
					</div>
					<div class="p-3">
						<div class="row">
							<?php while ($row = mysqli_fetch_array($allQuery)): ?>
								<div class="col-6 col-md-4 col-lg-2 mb-3">
									<div class="am-card h-100">
										<?php
										$disc = 0;
										if ($row['productPriceBeforeDiscount'] > 0 && $row['productPriceBeforeDiscount'] > $row['productPrice']) {
											$disc = round((($row['productPriceBeforeDiscount'] - $row['productPrice']) / $row['productPriceBeforeDiscount']) * 100);
										}
										if ($disc > 0):
											?>
											<div class="discount-tag"><?php echo $disc; ?>% <small>OFF</small></div>
										<?php endif; ?>

										<a href="index.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 htmlspecialchars(html_entity_decode($row['productName'], ENT_QUOTES)); ?>"
													onerror="this.src='assets/images/blank.gif'">
											</div>
											<div class="p-name"><?php echo html_entity_decode($row['productName'], ENT_QUOTES); ?></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="index.php?action=add&id=<?php echo $row['id']; ?>" class="btn-add-cart-app">
												<i class="fa fa-shopping-cart"></i>
											</a>
										<?php endif; ?>
									</div>
								</div>
							<?php endwhile; ?>
						</div>
					</div>
				</div>
			<?php endif; ?>


			<!-- Empty State if No Products -->
			<?php
			$totalProducts = mysqli_query($con, "SELECT COUNT(*) as total FROM products WHERE approval_status='approved'");
			$total = mysqli_fetch_array($totalProducts)['total'];

			if ($total == 0):
				?>
				<div class="white-box text-center py-5">
					<i class="fa fa-shopping-bag fa-4x text-muted mb-3"></i>
					<h4>No Products Yet</h4>
					<p class="text-muted">Products will appear here once they are added to the store.</p>
				</div>
			<?php endif; ?>

		</div><!-- /.awesome-container -->
	</div><!-- /.body-content -->

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

	<!-- Countdown Timer Script -->
	<!-- Countdown Timer Script Removed -->

</body>

</html>