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

// Optional: enable MySQLi error reporting for easier debugging
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Get the product URL name from the URL
$url = $_SERVER['REQUEST_URI'];
$parts = explode('/', trim($url, '/'));
$product_slug = explode('?', end($parts))[0];


// Fetch product details with category name
$query = "SELECT p.*, c.category_name 
          FROM products p 
          JOIN categories c ON p.category_id = c.category_id 
          WHERE p.product_url_name = ?";

$stmt = $conn->prepare($query);
if (!$stmt) {
    die("Product query prepare failed: " . $conn->error);
}
$stmt->bind_param("s", $product_slug);
$stmt->execute();
$product_result = $stmt->get_result();
$product = $product_result->fetch_assoc();

if (!$product) {
   echo json_encode(['status' => 'error', 'message' => 'Product not found.']);
   exit;
   
}

// Fetch product images
$product_id = $product['product_id'];
$img_query = "SELECT * FROM product_imgs WHERE product_id = ?";
$stmt = $conn->prepare($img_query);
if (!$stmt) {
    die("Image query prepare failed: " . $conn->error);
}
$stmt->bind_param("i", $product_id);
$stmt->execute();
$img_result = $stmt->get_result();
$images = $img_result->fetch_all(MYSQLI_ASSOC);

// Fetch product units
$unit_query = "SELECT * FROM product_units WHERE product_id = ?";
$stmt = $conn->prepare($unit_query);
if (!$stmt) {
    die("Unit query prepare failed: " . $conn->error);
}
$stmt->bind_param("i", $product_id);
$stmt->execute();
$unit_result = $stmt->get_result();
$units = $unit_result->fetch_all(MYSQLI_ASSOC);

// Fetch related products (same category, different product)
$related_stmt = $conn->prepare("
    SELECT p.product_id, p.product_name, p.product_url_name, 
           pu.unit_price, pi.product_img
    FROM products p
    LEFT JOIN (
        SELECT product_id, MIN(unit_price) as unit_price 
        FROM product_units 
        GROUP BY product_id
    ) pu ON pu.product_id = p.product_id
    LEFT JOIN (
        SELECT product_id, MIN(product_img) as product_img 
        FROM product_imgs 
        GROUP BY product_id
    ) pi ON pi.product_id = p.product_id
    WHERE p.category_id = ? AND p.product_id != ?
    ORDER BY p.product_id DESC
    LIMIT 2
");


if (!$related_stmt) {
    die("Related products query prepare failed: " . $conn->error);
}
$related_stmt->bind_param("ii", $product['category_id'], $product['product_id']);
$related_stmt->execute();
$related_result = $related_stmt->get_result();
$related_products = $related_result->fetch_all(MYSQLI_ASSOC);

$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'];
    }
}

$review_stmt = $conn->prepare("SELECT name, rating, message, created_at FROM product_reviews WHERE product_id = ?");
$review_stmt->bind_param("i", $product_id);
$review_stmt->execute();
$review_result = $review_stmt->get_result();
$reviews = $review_result->fetch_all(MYSQLI_ASSOC);

// Calculate average
$total = 0;
$count = count($reviews);
foreach ($reviews as $r) {
    $total += (int) $r['rating'];
}
$average_rating = $count ? round($total / $count, 1) : 0;


// Close the connection
$conn->close();
?>


<!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">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
      
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
   </head>
   <body>
<style>
   .icon-heart.active {
    color: red;
}

.icon-star_outline1.filled {
   color: #fbb040; /* or any gold color */
}


.icon-star_outline1{
    font-size: 25px !important;
}

    .product__details-btn a {
    font-family: var(--tp-ff-jost);
    font-weight: 600;
    font-size: 13px;
    text-align: center;
    text-transform: uppercase;
    color: var(--tp-common-white);
    background-color: var(--tp-heading-secondary);
    padding: 13px 70px !important;
    border-radius: 30px;
    display: inline-block;
}

    .dropdown-menu {
        display: none;
        position: absolute;
        background-color: #fff;
        border: 1px solid #ccc;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        z-index: 1000;
    }

    .dropdown-item {
        padding: 10px;
        text-decoration: none;
        color: #333;
        display: block;
    }

    .dropdown-item:hover {
        background-color: #f1f1f1;
    }


    .unit-box {
   border: 1px solid #ddd;
   padding: 8px 12px;
   border-radius: 8px;
   cursor: pointer;
   background: #f9f9f9;
   transition: all 0.2s ease;
}
.unit-box.active,
.unit-box:hover {
   background: #222;
   color: #fff;
   border-color: #222;
}
.unit-box input {
   display: none;
}

.swal2-select{
    display: none !important;
}

.icon-star {
    color: #ccc; /* empty star color */
}

.icon-star.filled {
    color: #fbb040; /* filled star color */
}

</style>

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


<header>
   <div class="header__top theme-bg-1 d-none d-md-block ps-5 pe-5">
      <div class="container-fluid">
         <div class="row align-items-center">
            <div class="col-lg-6 col-md-12">
               <div class="header__top-left">
                  <span>Best quality berries? Let us be your first and last stop for it.</span>
               </div> 
            </div>
            <div class="col-lg-6 col-md-12">
            <div class="d-flex justify-content-end align-items-center">
               <div class="text-white me-2">
               <?php
               if (isset($_SESSION['username'])) {
                  echo '<a href="../index.php">Welcome, ' . htmlspecialchars($_SESSION['username']) . '</a>';
               } else {
                  echo '<a href="../log-in.php">Login/Register</a>';
               }
               ?>
               </div>
               <div class="header__top-right d-flex align-items-center gap-3">
                  <a href="https://facebook.com" target="_blank" class="text-white"><i class="fab fa-facebook-f"></i></a>
                  <a href="https://twitter.com" target="_blank" class="text-white"><i class="fab fa-twitter"></i></a>
                  <a href="https://youtube.com" target="_blank" class="text-white"><i class="fab fa-youtube"></i></a>
                  <a href="https://instagram.com" target="_blank" class="text-white"><i class="fab fa-instagram"></i></a>
               </div>
         </div>
      </div>

   </div>
   </div>
   </div>
         <div id="header-sticky" class="header__main-area d-none d-xl-block p-2">
            <div class="container-fluid">
               <div class="header__for-megamenu p-relative">
                  <div class="row align-items-center">
                     <div class="col-xl-3">
                        <div class="header__logo ps-5">
                           <a href="../index.php"><img src="../assets/img/allnew/logo.png" alt="logo"></a>
                        </div>
                     </div>
                     <div class="col-xl-4">
                        <div class="header__menu main-menu text-center">
                           <nav id="mobile-menu">
                              <ul>
                                 <li >
                                    <a href="../index.php">Home</a>
                                 </li>
                                 <li><a href="../product.php">Shop</a></li>
                                 <li><a href="../about.php">About Us</a></li>
                                 <li><a href="..contact.php">Contact Us</a></li>
                                 <li>
                                    <a href="../blog.php">Blog</a>
                                 </li>
                              </ul>
                           </nav>
                        </div>
                     </div>
                     <div class="col-xl-5">
                        <div class="header__info d-flex align-items-center pe-5">
                          <div class="header__info-user tpcolor__yellow ml-10">
                            <?php if (isset($_SESSION['username'])): ?>
                            <a href="javascript:void(0)" class="user-icon" onclick="toggleDropdown()">
                                <i class="icon-user"></i>
                            </a>
                            <?php endif; ?>
                            <div id="dropdownMenu" class="dropdown-menu">
                                <a href="../order.php" class="dropdown-item">Order Page</a>
                                <a href="../logout.php" class="dropdown-item">Logout</a>
                            </div>
                        </div>

                          
                           <div class="header__info-cart tpcolor__oasis ml-10 tp-cart-toggle">
                                <a href="../cart.php"><i><img src="../assets/img/icon/cart-1.svg" alt=""></i></a>
                                <span>5</span>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>

         <!-- header-search -->
         <div class="tpsearchbar tp-sidebar-area">
            <button class="tpsearchbar__close"><i class="icon-x"></i></button>
            <div class="search-wrap text-center">
                <div class="container">
                    <div class="row justify-content-center">
                        <div class="col-6 pt-100 pb-100">
                            <h2 class="tpsearchbar__title">What Are You Looking For?</h2>
                            <div class="tpsearchbar__form">
                                <form action="#">
                                    <input type="text" name="search" placeholder="Search Product...">
                                    <button class="tpsearchbar__search-btn"><i class="icon-search"></i></button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
         </div>
         <div class="search-body-overlay"></div>
         <!-- header-search-end -->

         <!-- header-cart-start -->
        
         <div class="cartbody-overlay"></div>
         <!-- header-cart-end -->

         <!-- mobile-menu-area -->
         <div id="header-sticky-2" class="tpmobile-menu d-xl-none">
            <div class="container-fluid">
               <div class="row align-items-center">
                  <div class="col-lg-4 col-md-4 col-3 col-sm-3">
                     <div class="mobile-menu-icon">
                        <button class="tp-menu-toggle"><i class="icon-menu1"></i></button>
                     </div>
                  </div>
                  <div class="col-lg-4 col-md-4 col-6 col-sm-4">
                     <div class="header__logo text-center">
                        <a href="index.php"><img src="../assets/img/allnew/logo.png" alt="logo"></a>
                     </div>
                  </div>
                  <div class="col-lg-4 col-md-4 col-3 col-sm-5">
                     <div class="header__info d-flex align-items-center">
                        <div class="header__info-search tpcolor__purple ml-10 d-none d-sm-block">
                           <button class="tp-search-toggle"><i class="icon-search"></i></button>
                        </div>
                        <div class="header__info-user tpcolor__yellow ml-10 d-none d-sm-block">
                           <a href="#"><i class="icon-user"></i></a>
                        </div>
                       
                        <div class="header__info-cart tpcolor__oasis ml-10 tp-cart-toggle">
                           <button><i><img src="../assets/img/icon/cart-1.svg" alt=""></i>
                            
                           </button>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <div class="body-overlay"></div>
         <!-- mobile-menu-area-end -->

         <!-- sidebar-menu-area -->
         <div class="tpsideinfo">
            <button class="tpsideinfo__close">Close<i class="fal fa-times ml-10"></i></button>
            <div class="tpsideinfo__search text-center pt-35">
               <span class="tpsideinfo__search-title mb-20">What Are You Looking For?</span>
               <form action="#">
                  <input type="text" placeholder="Search Products...">
                  <button><i class="icon-search"></i></button>
               </form>
            </div>
            <div class="tpsideinfo__nabtab">
               
                <div class="tab-content" id="pills-tabContent">
                  <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab" tabindex="0">
                     <div class="mobile-menu"></div>
                  </div>
                  <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab" tabindex="0">
                     <div class="tpsidebar-categories">
                        <ul>
                           <li><a href="shop-details.php">Dairy Farm</a></li>
                           <li><a href="shop-details.php">Healthy Foods</a></li>
                           <li><a href="shop-details.php">Lifestyle</a></li>
                           <li><a href="shop-details.php">Organics</a></li>
                           <li><a href="shop-details.php">Photography</a></li>
                           <li><a href="shop-details.php">Shopping</a></li>
                           <li><a href="shop-details.php">Tips & Tricks</a></li>
                        </ul>
                     </div>
                  </div>
                </div>
            </div>
            <div class="tpsideinfo__account-link">							
               <a href="../log-in.php"><i class="icon-user icons"></i> Login / Register</a>
            </div>
            
         </div> 
         <!-- sidebar-menu-area-end -->
</header>

      <main>
          
          <?php if (isset($_GET['review']) && $_GET['review'] == 'not_logged_in'): ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
  icon: 'warning',
  title: 'Login Required',
  text: 'Please log in to submit a review.',
  confirmButtonText: 'OK'
}).then(function() {
                        window.location.href = '../log-in.php';
                    });
</script>
<?php endif; ?>

         <!-- 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><?= htmlspecialchars($product['product_name']) ?></span>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <!-- breadcrumb-area-end -->

         <!-- shop-details-area-start -->
         <section class="shopdetails-area grey-bg pb-50">
            <div class="container">
                 <?php if (isset($_GET['review']) && $_GET['review'] == 'success'): ?>
                                       <div class="alert alert-success mt-3">Thank you! Your review has been submitted.</div>
                                    <?php endif; ?>
               <div class="row">
                  <div class="col-lg-10 col-md-12">
                     <div class="tpdetails__area mr-60 pb-30">
                        <div class="tpdetails__product mb-30">
                           
                           <div class="tpdetails__box">
                              <div class="row">
                              <div class="col-lg-6">
                                 <div class="tpproduct-details__nab">
                                    <div class="tab-content" id="nav-tabContents">
                                       <?php foreach ($images as $index => $img): 
                                          $isActive = ($index === 0) ? 'show active' : '';
                                          $tabId = 'nav-' . $index;
                                       ?>
                                          <div class="tab-pane fade <?= $isActive ?> w-img" id="<?= $tabId ?>" role="tabpanel" aria-labelledby="<?= $tabId ?>-tab" tabindex="0">
                                             <img src="../admin/<?= htmlspecialchars($img['product_img']) ?>" alt="">
                                          </div>
                                       <?php endforeach; ?>
                                    </div> 

                                    <nav>
                                       <div class="nav nav-tabs justify-content-center" id="nav-tab" role="tablist">
                                          <?php foreach ($images as $index => $img): 
                                             $isActive = ($index === 0) ? 'active' : '';
                                             $tabId = 'nav-' . $index;
                                          ?>
                                             <button class="nav-link <?= $isActive ?>" id="<?= $tabId ?>-tab" data-bs-toggle="tab" data-bs-target="#<?= $tabId ?>" type="button" role="tab" aria-controls="<?= $tabId ?>" aria-selected="<?= $isActive ? 'true' : 'false' ?>">
                                                <img src="../admin/<?= htmlspecialchars($img['product_img']) ?>" alt="">
                                             </button>
                                          <?php endforeach; ?>
                                       </div>
                                    </nav>                 
                                 </div>
                              </div>

                              <div class="col-lg-6">
                              <h3 class="tpdetails__title"><?= htmlspecialchars($product['product_name']) ?></h3>

                              <ul class="tpdetails__brand mb-4">
                              <li> 
                                 Category: 
                                 <a href="category.php?name=<?= urlencode($product['category_name']) ?>">
                                    <?= htmlspecialchars($product['category_name']) ?>
                                 </a> 
                              </li>

                                
                              <li>
                                 SKU: <span><?= htmlspecialchars($product['sku_id']) ?></span>
                              </li>

                              <li>
                                 HSN Code: <span><?= htmlspecialchars($product['hsn_code']) ?></span>
                              </li>
                              </ul>
                              <div class="product__details">
                                 <div class="product__details-price-box">
                                   
                                       <?php if (count($units) === 1): ?>
                                          <h5 class="product__weight"><?= htmlspecialchars($units[0]['unit_name']) ?></h5>
                                          <h5 class="product__details-price">₹<?= number_format($units[0]['unit_price'], 2) ?></h5>
                                          <input type="hidden" name="selected_unit" value="<?= htmlspecialchars($units[0]['unit_id']) ?>">
                                       <?php elseif (count($units) > 1): ?>
                                          <div class="product__unit-options mb-20 d-flex gap-2 flex-wrap">
                                             <?php foreach ($units as $index => $unit): ?>
                                                <label class="unit-box <?= $index === 0 ? 'active' : '' ?>">
                                                   <input type="radio" name="selected_unit" value="<?= $unit['unit_id'] ?>" <?= $index === 0 ? 'checked' : '' ?> hidden>
                                                   <span><?= htmlspecialchars($unit['unit_name']) ?> - ₹<?= number_format($unit['unit_price'], 2) ?></span>
                                                </label>
                                             <?php endforeach; ?>
                                          </div>
                                       <?php endif; ?>


                                    
                                 </div>

                                 <div class="product__details-cart mt-4">
                                    <div class="product__details-quantity d-flex align-items-center mb-15"> 
                                       <b>Qty:</b>
                                       <div class="product__details-count mr-10">
                                             <span class="cart-minus"><i class="fas fa-minus"></i></span>
                                             <input class="tp-cart-input" type="text" value="1" name="qty" id="quantity-input">
                                             <span class="cart-plus"><i class="far fa-plus"></i></span>
                                       </div>
                                       <div class="product__details-btn">
                                             <!-- Add to Cart button -->
                                             <a href="javascript:void(0);" id="add-to-cart-btn">Add to Cart</a>
                                       </div>
                                    </div>

                                    <ul class="product__details-check my-3">
                                    <li>
                                      <?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): ?>
                       Added in wishlist <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: ?>
                       Add to Wishlist <i class="icon-heart icons"></i>
                        <?php endif; ?>
                                    </li>

                                    <li>
                                        <a href="#" id="shareButton"><i class="icon-share-2"></i> Share</a>
                                    </li>

                                    </ul>
                                 </div>



                                 <div class="product__details-stock mb-25">
                                    <ul>
                                       <li>Availability: 
                                          <i><?= isset($product['stock']) ? $product['stock'] : 'In Stock' ?></i>
                                       </li>
                                       <li>Categories: 
                                          <span><?= isset($category_names) ? htmlspecialchars($category_names) : 'N/A' ?></span>
                                       </li>
                                       <li>Tags: 
                                          <span><?= isset($tags) ? htmlspecialchars($tags) : 'N/A' ?></span>
                                       </li>
                                    </ul>
                                 </div>
                              </div>


                                 </div>
                              </div>
                           </div>
                        </div>
                        <div class="tpdescription__box">
                           <div class="tpdescription__box-center d-flex align-items-center justify-content-center">
                              <nav>
                                 <div class="nav nav-tabs"  role="tablist">
                                   <button class="nav-link active" id="nav-description-tab" data-bs-toggle="tab" data-bs-target="#nav-description" type="button" role="tab" aria-controls="nav-description" aria-selected="true">Product Description</button>
                                   <button class="nav-link" id="nav-info-tab" data-bs-toggle="tab" data-bs-target="#nav-information" type="button" role="tab" aria-controls="nav-information" aria-selected="false">ADDITIONAL INFORMATION</button>
                                   <button class="nav-link" id="nav-review-tab" data-bs-toggle="tab" data-bs-target="#nav-review" type="button" role="tab" aria-controls="nav-review" aria-selected="false">Reviews (<?= count($reviews) ?> <?= count($reviews) > 1 ? '' : '' ?>)</button>
                                 </div>
                               </nav>
                           </div>
                           <div class="tab-content" id="nav-tabContent">
                              <div class="tab-pane fade show active" id="nav-description" role="tabpanel" aria-labelledby="nav-description-tab" tabindex="0">
                               
                                 <div class="tpdescription__video">
                                    <?= $product['product_description'] ?>
                                     </div>
                              </div>
                              <div class="tab-pane fade" id="nav-information" role="tabpanel" aria-labelledby="nav-info-tab" tabindex="0">
                                 <div class="tpdescription__content">
                                 <ul class="product__details-info-list">
                                    <?php 
                                    $specs = strip_tags($product['product_specification']);
                                    $lines = explode("\n", $specs);
                                    foreach ($lines as $line): 
                                       if (trim($line)):
                                    ?>
                                       <li><?= htmlspecialchars(trim($line)) ?></li>
                                    <?php 
                                       endif;
                                    endforeach; 
                                    ?>
                                 </ul>
                                 </div>
                                 
                              </div>

                              <div class="tab-pane fade" id="nav-review" role="tabpanel" aria-labelledby="nav-review-tab" tabindex="0">
                                 <div class="tpreview__wrapper">

                                <?php if (!empty($reviews)): ?>
    <h4 class="tpreview__wrapper-title">
        <?= count($reviews) ?> review<?= count($reviews) > 1 ? 's' : '' ?> for <?= htmlspecialchars($product['product_name']) ?>
    </h4>
    <?php foreach ($reviews as $review): ?>
        <?php $rating = (int) $review['rating']; ?>
        <div class="tpreview__comment">
            <div class="tpreview__comment-img mr-20">
                <img src="../assets/img/testimonial/test-avata-1.png" alt="Reviewer">
            </div>
            <div class="tpreview__comment-text">
                <div class="tpreview__comment-autor-info d-flex align-items-center justify-content-between">
                    <div class="tpreview__comment-author">
                        <span><?= htmlspecialchars($review['name']) ?></span>
                    </div>
                   <div class="tpreview__comment-star">
                       <?php for ($i = 1; $i <= 5; $i++): ?>
    <i class="fa<?= ($i <= $rating) ? 's' : 'r' ?> fa-star"></i>
<?php endfor; ?>

                    </div>
                    
                    
                                    </div>
                                    <span class="date mb-20"><?= date("F j, Y", strtotime($review['created_at'])) ?>:</span>
                                    <p><?= nl2br(htmlspecialchars($review['message'])) ?></p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p>No reviews yet.</p>
                    <?php endif; ?>


                                    <div class="tpreview__form">
                                       <h4 class="tpreview__form-title mb-25">Add a review </h4>
                                      

                                       <form action="../submit-review.php" method="POST" id="reviewForm">
                                         <input type="hidden" name="product_id" value="<?php echo $product['product_id']; ?>">
                                            <input type="hidden" name="product_url_name" value="<?php echo $product['product_url_name']; ?>">

                                           <div class="row">
                                              <div class="col-lg-6">
                                                 <input type="text" name="name" placeholder="Name" class="form-control" required>
                                              </div>
                                              <div class="col-lg-6">
                                                 <input type="email" name="email" placeholder="Email" class="form-control" required>
                                              </div>
                                              <div class="col-lg-12">
                                                 <h4 class="title my-3">Your Rating</h4>
                                                 <div class="rating-stars">
                                                    <input type="hidden" name="rating" id="ratingValue" required>
                                                    <i class="icon-star_outline1" data-value="1"></i>
                                                    <i class="icon-star_outline1" data-value="2"></i>
                                                    <i class="icon-star_outline1" data-value="3"></i>
                                                    <i class="icon-star_outline1" data-value="4"></i>
                                                    <i class="icon-star_outline1" data-value="5"></i>
                                                 </div>
                                                 <textarea name="message" placeholder="Message" class="form-control my-4" required></textarea>
                                                 <button type="submit" class="tp-btn">Submit</button>
                                              </div>
                                           </div>
                                        </form>

                                    </div>
                                 </div>
                              </div>
                           </div>   
                        </div>
                     </div>
                  </div>
                  <div class="col-lg-2 col-md-12">
                     <div class="tpsidebar pb-30">
                        <div class="tpsidebar__warning mb-30">
                           <ul>
                              <li>
                                 <div class="tpsidebar__warning-item">
                                    <div class="tpsidebar__warning-icon">
                                       <i class="icon-package"></i>
                                    </div>
                                    <div class="tpsidebar__warning-text">
                                       <p>Free shipping apply to all <br> orders over ₹90</p>
                                    </div>
                                 </div>
                              </li>
                              <li>
                                 <div class="tpsidebar__warning-item">
                                    <div class="tpsidebar__warning-icon">
                                       <i class="icon-shield"></i>
                                    </div>
                                    <div class="tpsidebar__warning-text">
                                       <p>Guaranteed 100% Organic <br>  from nature farms</p>
                                    </div>
                                 </div>
                              </li>
                              <li>
                                 <div class="tpsidebar__warning-item">
                                    <div class="tpsidebar__warning-icon">
                                       <i class="icon-package"></i>
                                    </div>
                                    <div class="tpsidebar__warning-text">
                                       <p>60 days returns if you change <br> your mind</p>
                                    </div>
                                 </div>
                              </li>
                           </ul>
                        </div>
                        <!--<div class="tpsidebar__banner mb-30">-->
                        <!--   <img src="assets/img/shape/sidebar-product-1.png" alt="">-->
                        <!--</div>-->
                        <div class="tpsidebar__product">
                           <h4 class="tpsidebar__title mb-15">Recent Products</h4>
                             <?php 
                                $shown_products = []; // Track displayed product IDs
                                foreach ($related_products as $related): 
                                    if (in_array($related['product_id'], $shown_products)) continue; // Skip if already shown
                                    $shown_products[] = $related['product_id']; // Mark as shown
                                ?>
                                <a href="../product-details.php/<?= htmlspecialchars($related['product_url_name']) ?>">
                           <div class="tpsidebar__product-item">
                              <div class="tpsidebar__product-thumb p-relative">
                                 <img src="../admin/<?= htmlspecialchars($related['product_img']) ?>" alt="<?= htmlspecialchars($related['product_name']) ?>">
                              </div>
                              <div class="tpsidebar__product-content">
                                 <span class="tpproduct__product-category">
                                    <a href="../product-details.php/<?= htmlspecialchars($related['product_url_name']) ?>"> <?= htmlspecialchars($product['category_name']) ?></a>
                                 </span>
                                 <h4 class="tpsidebar__product-title">
                                    <a href="../product-details.php/<?= htmlspecialchars($related['product_url_name']) ?>"> <?= htmlspecialchars($related['product_name']) ?></a>
                                 </h4>
                                 <div class="tpproduct__price">
                                    <span>₹<?= number_format($related['unit_price'] ?? 0, 2) ?></span>
                                    <del>₹19.00</del>
                                 </div>
                              </div>
                           </div>
                           </a>
                         <?php endforeach; ?>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </section>
         <!-- shop-details-area-end -->
      </main>

      <!-- footer-area-start -->
      <section class="feature-area mainfeature__bg grey-bg pt-50 pb-40" data-background="../assets/img/shape/footer-shape-1.svg">
            <div class="container">
               <div class="mainfeature__border pb-15">
                  <div class="row row-cols-lg-4 row-cols-md-3 row-cols-2">
                     <div class="col">
                        <div class="mainfeature__item text-center mb-30">
                           <div class="mainfeature__icon">
                              <img src="../assets/img/icon/feature-icon-1.svg" alt="">
                           </div>
                           <div class="mainfeature__content">
                              <h4 class="mainfeature__title">Fast Delivery</h4>
                              <p>Across West & East India</p>
                           </div>
                        </div>
                     </div>
                     <div class="col">
                        <div class="mainfeature__item text-center mb-30">
                           <div class="mainfeature__icon">
                              <img src="../assets/img/icon/feature-icon-2.svg" alt="">
                           </div>
                           <div class="mainfeature__content">
                              <h4 class="mainfeature__title">safe payment</h4>
                              <p>100% Secure Payment</p>
                           </div>
                        </div>
                     </div>
                     <div class="col">
                        <div class="mainfeature__item text-center mb-30">
                           <div class="mainfeature__icon">
                              <img src="../assets/img/icon/feature-icon-3.svg" alt="">
                           </div>
                           <div class="mainfeature__content">
                              <h4 class="mainfeature__title">Online Discount</h4>
                              <p>Add Multi-buy Discount </p>
                           </div>
                        </div>
                     </div>
                     <div class="col">
                        <div class="mainfeature__item text-center mb-30">
                           <div class="mainfeature__icon">
                              <img src="../assets/img/icon/feature-icon-4.svg" alt="">
                           </div>
                           <div class="mainfeature__content">
                              <h4 class="mainfeature__title">Help Center</h4>
                              <p>Dedicated 24/7 Support </p>
                           </div>
                        </div>
                     </div>
                     
                  </div>
               </div>
            </div>
            
         </section>


         <footer>
         <div class="tpfooter__area theme-bg-2">
            <div class="tpfooter__top pb-15">
               <div class="container">
                  <div class="row">
                     
                     <div class="col-xl-3 col-lg-4 col-md-6 col-sm-6">
                        <div class="tpfooter__widget footer-col-2 mb-50">
                           <h4 class="tpfooter__widget-title"><img src="../assets/img/allnew/logo.png"></h4>
                           <p>Address <br> </p>
                           <div class="tpfooter__widget-time-info mt-35">
                              <span>Monday – Friday: <b>8:10 AM – 6:10 PM</b></span>
                              <span>Saturday: <b>10:10 AM – 06:10 PM</b></span>
                              <span>Sunday: <b>Close</b></span>
                           </div>
                        </div>
                     </div>
                     <div class="col-xl-3 col-lg-4 col-md-6 col-sm-6">
                        <div class="tpfooter__widget footer-col-1 mb-50">
                           <h4 class="tpfooter__widget-title">Customer Support</h4>
                           
                           <div class="tpfooter__widget-links">
                              <ul>
                                 <li><a href="../cancel.php">Cancellation & Refund</a></li>
                                 <li><a href="../privacypolicy.php">Privacy Policy</a></li>
                                 <li><a href="../s&d.php">Shipping & Delivery</a></li>
                                 <li><a href="../terms.php">Terms & Condition</a></li>
                                 
                              </ul>
                           </div>
                        </div>
                     </div>
                     <div class="col-xl-2 col-lg-4 col-md-4 col-sm-5">
                        <div class="tpfooter__widget footer-col-3 mb-50">
                           <h4 class="tpfooter__widget-title">Quick Links</h4>
                           <div class="tpfooter__widget-links">
                              <ul>
                                 <li><a href="../index.php">Home</a></li>
                                 <li><a href="../about.php">About Us</a></li>
                                 <li><a href="../contactus.php">Contact Us</a></li>
                                 <li><a href="../Blog.php">Blog</a></li>
                              </ul>
                           </div>
                        </div>
                     </div>
                     <div class="col-xl-4 col-lg-6 col-md-8 col-sm-7">
                        <div class="tpfooter__widget footer-col-4 mb-50">
                           <h4 class="tpfooter__widget-title">Our newsletter</h4>
                           <div class="tpfooter__widget-newsletter">
                           <iframe
                                src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3770.5884245265042!2d73.00838082418423!3d19.081825101791654!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3be7c1394978006b%3A0x12fd6d16abacf57!2sCommodity%20Exchange!5e0!3m2!1sen!2sin!4v1703678311152!5m2!1sen!2sin"
                                width="400" height="200" style="border:0;" allowfullscreen="" loading="lazy"
                                referrerpolicy="no-referrer-when-downgrade"></iframe>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
            <div class="tpfooter___bottom pt-40 pb-40">
               <div class="container">
                  <div class="row">
                     <div class="col-lg-6 col-md-7 col-sm-12">
                        <div class="tpfooter__copyright">
                           <span class="tpfooter__copyright-text">Copyright © <a href="#">Love Beri</a> all rights reserved. Developed by <a href="#">HS Digital Media</a>.</span>
                        </div>
                     </div>
                     
                  </div>
               </div>
            </div>
         </div>
      </footer>
      <!-- footer-area-end -->
      
<!-- SweetAlert2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.11/dist/sweetalert2.min.css" rel="stylesheet">

<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.11/dist/sweetalert2.all.min.js"></script>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


<script>
    
document.querySelectorAll('.rating-stars i').forEach(star => {
    star.addEventListener('click', function () {
        let value = this.getAttribute('data-value');
        document.getElementById('ratingValue').value = value;

        // Reset all
        document.querySelectorAll('.rating-stars i').forEach(s => s.classList.remove('active'));

        // Highlight selected
        for (let i = 0; i < value; i++) {
            document.querySelectorAll('.rating-stars i')[i].classList.add('active');
        }
    });
});
</script>

<style>
.rating-stars i.active {
    color: orange;
}
</style>


<!-- 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>



<script>
document.getElementById('add-to-cart-btn').addEventListener('click', function() {
    var productId = <?= $product['product_id'] ?>;  // Get product ID dynamically from PHP
    var qtyInput = document.getElementById('quantity-input');

    if (!qtyInput) {
        console.error("Quantity input element not found!");
        return;
    }

    var qty = parseInt(qtyInput.value);
    if (isNaN(qty) || qty < 1) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid Quantity',
            text: 'Please enter a valid quantity.',
        });
        return;
    }

    var selectedUnit;

    // Check if there is only one unit
    if (document.querySelector('input[name="selected_unit"]')) {
        selectedUnit = document.querySelector('input[name="selected_unit"]:checked');
        
        // If no unit is selected and there is only one unit, select it by default
        if (!selectedUnit && document.querySelectorAll('input[name="selected_unit"]').length === 1) {
            selectedUnit = document.querySelector('input[name="selected_unit"]');
        }
    }

    // Ensure that the unitId is taken from the selected unit, else handle it based on available units
    var unitId = selectedUnit ? selectedUnit.value : null; 

    // If unitId is still null, log an error or show a message
    if (!unitId) {
        console.error("No unit selected or available!");
        Swal.fire({
            icon: 'error',
            title: 'Unit Selection Error',
            text: 'Please select a valid unit.',
        });
        return;
    }

    // Prepare the data for the POST request
    var formData = new FormData();
    formData.append('product_id', productId);
    formData.append('unit_id', unitId);
    formData.append('qty', qty);

    // Send the POST request using Fetch API
    fetch('../add-to-cart.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text().then(text => {
        console.log('Raw response:', text);  // Log the raw response
        try {
            return JSON.parse(text);  // Try parsing as JSON
        } catch (e) {
            console.error('Error parsing JSON:', e);
            throw new Error('Invalid JSON response');
        }
    }))
    .then(data => {
        if (data.status === 'success') {
            Swal.fire({
                icon: 'success',
                title: 'Product Added!',
                text: 'The product has been successfully added to your cart.',
            });
        } else if (data.status === 'login_required') {
            // Redirect to login page with a message
            window.location.href = "../log-in.php?message=login_required";
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message || "An error occurred while adding the product to the cart.",
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'There was an error adding the product to the cart.',
        });
    });
});


</script>



      <script>
    function toggleDropdown() {
    const dropdown = document.getElementById("dropdownMenu");
    dropdown.style.display = (dropdown.style.display === "block") ? "none" : "block";
}

</script>

<script>
  var swiper = new Swiper('.tpproduct-active', {
    slidesPerView: 4,
    spaceBetween: 30,
    loop: false, // Disable loop to avoid duplicated slides
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    breakpoints: {
      1200: { slidesPerView: 4 },
      992: { slidesPerView: 3 },
      768: { slidesPerView: 2 },
      576: { slidesPerView: 1 }
    }
  });
</script>


<script>
   document.querySelectorAll('.unit-box input').forEach(input => {
      input.addEventListener('change', function() {
         document.querySelectorAll('.unit-box').forEach(label => label.classList.remove('active'));
         this.closest('.unit-box').classList.add('active');
      });
   });
</script>

<!--share btn script-->

<script>
document.getElementById('shareButton').addEventListener('click', function (e) {
    e.preventDefault();

    const shareData = {
        title: document.title,
        text: 'Check out this product from Loveberi!',
        url: window.location.href
    };

    if (navigator.share) {
        navigator.share(shareData).catch((err) => {
            console.error('Error sharing:', err);
        });
    } else {
        // Fallback: copy link to clipboard
        navigator.clipboard.writeText(shareData.url).then(() => {
            alert("Link copied to clipboard!");
        }).catch(() => {
            prompt("Copy this link:", shareData.url);
        });
    }
});
</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>
