<?php

require('connection.inc.php');
require('security.php');

error_reporting(E_ALL);
ini_set('display_errors', 1);

$cartItems = [];
$cartSubtotal = 0;

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];

    $sql = "SELECT 
                cart.id AS cart_id,
                cart.quantity,
                products.product_id,
                products.product_name,
                products.product_url_name,  
                (
                    SELECT product_img 
                    FROM product_imgs 
                    WHERE product_imgs.product_id = products.product_id 
                    AND deleted_at IS NULL 
                    ORDER BY img_id ASC 
                    LIMIT 1
                ) AS product_img,
                product_units.unit_id,
                product_units.unit_name,
                product_units.unit_price
            FROM cart
            JOIN products ON cart.product_id = products.product_id
            JOIN product_units ON cart.unit_id = product_units.unit_id
            WHERE cart.user_id = ?";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    }

    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $cartItems[] = $row;
    }

    foreach ($cartItems as $item) {
        $cartSubtotal += $item['unit_price'] * $item['quantity'];
    }
}
?>


<!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">
   </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 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.html">Home</a></span>
                           <span class="dvdr">/</span>
                           <span>Cart</span>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <!-- breadcrumb-area-end -->

         <!-- cart area -->
         <section class="cart-area pb-80">
            <div class="container">
            <div class="row">
               <div class="col-12">
                     <form action="#">
                        <div class="table-content table-responsive">
                           <table class="table">
                                 <thead>
                                    <tr>
                                       <th class="product-thumbnail">Images</th>
                                       <th class="cart-product-name">Courses</th>
                                       <th class="product-price">Unit Price</th>
                                       <th class="product-quantity">Quantity</th>
                                       <th class="product-subtotal">Total</th>
                                       <th class="product-remove">Remove</th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    <?php
                                    // Display the error message if it's set
if (isset($_SESSION['error_message'])) {
   echo '<div class="alert alert-danger">' . $_SESSION['error_message'] . '</div>';
   unset($_SESSION['error_message']); // Unset the session message after showing it
}
?>
                                    
    <?php if (!isset($_SESSION['user_id'])): ?>
        <tr>
            <td colspan="6" class="text-center">
                <p class="text-danger">Please login first to view your cart.</p>
                <a href="log-in.php" class="btn btn-primary mt-2">Login</a>
            </td>
        </tr>
    <?php elseif (empty($cartItems)): ?>
        <tr>
            <td colspan="6" class="text-center">
                <img src="assets/img/cart/cartempty.gif" height="150">
                <p>Your cart is empty. Add items to get started!</p>
                <a href="product.php" class="text-danger">Shop Now</a>
            </td>
        </tr>
    <?php else: ?>
        <?php foreach ($cartItems as $item): ?>
            <tr>
                <td class="product-thumbnail">
                    <a href="product-details.php/<?php echo urlencode($item['product_url_name']); ?>">
                        <img src="admin/<?php echo htmlspecialchars($item['product_img']); ?>" alt="" width="80">
                    </a>
                </td>
                <td class="product-name">
                    <a href="product-details.php/<?php echo urlencode($item['product_url_name']); ?>">
                        <?php echo htmlspecialchars($item['product_name']) . ' (' . htmlspecialchars($item['unit_name']) . ')'; ?>
                    </a>
                </td>
                <td class="product-price">
                    <span class="amount">₹<?php echo number_format($item['unit_price'], 2); ?></span>
                </td>
                <td class="product-quantity">
                    <button class="cart-minus" onclick="updateQuantity(<?php echo $item['cart_id']; ?>, -1)">-</button>
                    <input class="cart-input" id="qty-<?php echo $item['cart_id']; ?>" type="text" value="<?php echo $item['quantity']; ?>" readonly>
                    <button class="cart-plus" onclick="updateQuantity(<?php echo $item['cart_id']; ?>, 1)">+</button>
                </td>
                <td class="product-subtotal">
                    <span class="amount">₹<?php echo number_format($item['unit_price'] * $item['quantity'], 2); ?></span>
                </td>
                <td class="product-remove">
                    <a href="javascript:void(0);" onclick="removeFromCart(<?php echo $item['cart_id']; ?>)">
                        <i class="fas fa-times"></i>
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
    <?php endif; ?>
</tbody>


                           </table>
                        </div>
                        <!-- <div class="row">
                           <div class="col-12">
                                 <div class="coupon-all">
                                    <div class="coupon">
                                       <input id="coupon_code" class="input-text" name="coupon_code" value=""
                                             placeholder="Coupon code" type="text">
                                       <button class="tp-btn tp-color-btn banner-animation" name="apply_coupon" type="submit">Apply
                                             Coupon</button>
                                    </div>
                                    <div class="coupon2">
                                       <button class="tp-btn tp-color-btn banner-animation" name="update_cart" type="submit">Update cart</button>
                                    </div>
                                 </div>
                           </div>
                        </div> -->
                        <div class="row justify-content-end">
                           <div class="col-md-5">
                              <div class="cart-page-total">
                                 <h2>Cart totals</h2>
                                 <ul class="mb-20">
                                    <li>Subtotal <span>₹<?php echo number_format($cartSubtotal, 2); ?></span></li>
                                    <li>Total <span>₹<?php echo number_format($cartSubtotal, 2); ?></span></li>
                                 </ul>
                                 <a href="checkout.php" class="tp-btn tp-color-btn banner-animation">Proceed to Checkout</a>
                              </div>
                           </div>
                        </div>

                     </form>
               </div>
            </div>
            </div>
         </section>
         <!-- cart area end-->

         
         <!-- feature-area-start -->
      
         <!-- feature-area-end -->

      </main>

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

      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

      <script>
         function updateQuantity(cartId, change) {
            const qtyInput = document.getElementById('qty-' + cartId);
            let currentQty = parseInt(qtyInput.value);

            const newQty = currentQty + change;
            if (newQty < 1) return; // Prevent quantity below 1

            fetch('update_cart_quantity.php', {
               method: 'POST',
               headers: {
                     'Content-Type': 'application/x-www-form-urlencoded',
               },
               body: `cart_id=${cartId}&quantity=${newQty}`
            })
            .then(response => response.json())
            .then(data => {
               if (data.success) {
                     qtyInput.value = newQty;
                     // Optionally refresh totals or prices without full reload
                     location.reload(); // or update subtotal manually
               } else {
                     alert('Failed to update quantity.');
               }
            });
         }


         function removeFromCart(cartId) {
            Swal.fire({
               title: 'Are you sure?',
               text: "Do you want to remove this item from cart?",
               icon: 'warning',
               showCancelButton: true,
               confirmButtonColor: '#d33',
               cancelButtonColor: '#3085d6',
               confirmButtonText: 'Yes, remove it!'
            }).then((result) => {
               if (result.isConfirmed) {
                  fetch('remove_from_cart.php', {
                     method: 'POST',
                     headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                     },
                     body: `cart_id=${cartId}`
                  })
                  .then(response => response.json())
                  .then(data => {
                     if (data.success) {
                        Swal.fire({
                           icon: 'success',
                           title: 'Removed!',
                           text: 'The item has been removed from your cart.',
                           timer: 1500,
                           showConfirmButton: false
                        }).then(() => {
                           location.reload();
                        });
                     } else {
                        Swal.fire('Error', 'Failed to remove item from cart.', '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>
