<?php
declare(strict_types=1);
session_start();
if (!isset($_SESSION['cart_by_user'])) $_SESSION['cart_by_user'] = [];
$uid = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
$items = [];
if ($uid > 0) {
  $dbHost = getenv('DB_HOST') ?: 'localhost';
  $dbUser = getenv('DB_USER') ?: 'root';
  $dbPass = getenv('DB_PASSWORD') ?: '';
  $dbName = 'listbnb';
  try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    $pdo->exec('CREATE TABLE IF NOT EXISTS user_carts (user_id INT UNSIGNED NOT NULL, product_id INT UNSIGNED NOT NULL, qty INT UNSIGNED NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uc_unique (user_id, product_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
    $stmt = $pdo->prepare('SELECT p.id, p.product_title, p.price, p.image1 FROM products p INNER JOIN user_carts uc ON uc.product_id=p.id WHERE uc.user_id=:u ORDER BY uc.created_at DESC');
    $stmt->execute([':u'=>$uid]);
    $items = $stmt->fetchAll();
  } catch (Throwable $e) { $items = []; }
}
if (!$items) { $items = isset($_SESSION['cart_by_user'][$uid]) ? array_values($_SESSION['cart_by_user'][$uid]) : []; }
$total = 0.0;
foreach ($items as $it) { $total += (float)($it['price'] ?? 0); }
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
   <meta charset="utf-8">
   <meta http-equiv="x-ua-compatible" content="ie=edge">
   <title>Cart - ListBnb</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">

   <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
   <link rel="stylesheet" href="assets/css/bootstrap.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/font-awesome-pro.css">
   <link rel="stylesheet" href="assets/css/spacing.css">
   <link rel="stylesheet" href="assets/css/custom-animation.css">
   <link rel="stylesheet" href="assets/css/main.css">
   <style>
     .cart-hero{background:linear-gradient(135deg,#eef1f5 0%,#ffbfd6 50%,#ff9fc4 100%);padding:16px 0;border-bottom:1px solid #e6e9ee;margin-bottom:24px}
     .cart-title{color:#1f2937;font-weight:800;margin:0;font-size:30px;position:relative;padding-bottom:8px}
     .cart-title:after{content:'';position:absolute;left:0;bottom:0;width:50px;height:4px;background:#ff9fc4;border-radius:2px}
     .cart-title-wrap{display:flex;flex-direction:column;gap:6px}
     .cart-count{color:#6b7280;margin-top:0}
     .cart-hero a{color:#1f2937 !important}
     .cart-back{font-size:1.25rem;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;border-radius:999px;background:#ffffffcc;border:1px solid #e6e9ee}
     .cart-back:hover{background:#fff}
     .cart-card{border:1px solid #e6e9ee;border-radius:16px;background:#fff;padding:0;overflow:hidden;box-shadow:0 8px 20px rgba(0,0,0,.08)}
     .cart-head{padding:16px 20px;border-bottom:1px solid #e6e9ee;display:flex;align-items:center;justify-content:space-between;background:#fff}
     .cart-head .tp-form-title{margin:0;color:#1f2937}
     .cart-list{padding:8px 0}
     .cart-table{width:100%}
     .cart-row{display:grid;grid-template-columns:96px 1fr 120px 100px;align-items:center;gap:16px;padding:14px 20px;border-bottom:1px solid #eef1f5;transition:background .2s ease}
     .cart-row:last-child{border-bottom:none}
     .cart-row:hover{background:#f9fafb}
     .cart-thumb{width:96px;height:96px;object-fit:cover;border-radius:12px;border:1px solid #e6e9ee;background:#fff}
     .cart-info{min-width:0}
     .cart-item-title{color:#1f2937;font-weight:600;margin:0}
     .cart-meta{color:#6b7280;font-size:13px}
     .cart-price{color:#10b981;font-weight:700}
     .cart-remove{background:transparent;border:1px solid #e6e9ee;color:#6b7280;border-radius:10px;padding:8px 10px;transition:all .2s ease}
     .cart-remove:hover{border-color:#ff9fc4;color:#ff9fc4}
     .cart-summary{border:1px solid #e6e9ee;border-radius:16px;background:#f5f6f8;padding:18px;color:#374151;box-shadow:0 8px 20px rgba(0,0,0,.06)}
     .cart-total{color:#1f2937;font-weight:700}
     .cart-actions{display:flex;gap:12px;justify-content:flex-end;margin-top:16px}
     .summary-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
     @media (max-width:991px){.cart-row{grid-template-columns:80px 1fr 110px 88px;gap:12px;padding:12px 16px}.cart-thumb{width:80px;height:80px}}
     @media (max-width:575px){.cart-row{grid-template-columns:64px 1fr 90px 72px}.cart-thumb{width:64px;height:64px}.cart-actions{justify-content:space-between}}
   </style>
</head>
<body>
   

   <main>
      <section class="cart-hero">
        <div class="container">
          <div class="row align-items-end">
            <div class="col-xl-8 col-lg-9">
              <div style="display:flex;align-items:center;gap:15px;">
                <a href="index-2.php" class="cart-back"><i class="fa fa-arrow-left"></i></a>
                <div class="cart-title-wrap">
                  <h1 class="cart-title">Shopping Cart</h1>
                  <p class="cart-count mb-0">Items: <?php echo (int)count($items); ?></p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="pb-120 pt-60">
        <div class="container">
          <?php if (empty($items)): ?>
            <div class="row justify-content-center">
              <div class="col-xl-8 col-lg-9">
                <div class="tp-login-wrapper text-center p-40" style="border:1px solid #1b1b1b;border-radius:16px;background:#0f0f10;">
                  <h3 class="tp-form-title mb-10">Your cart is empty</h3>
                  <p class="mb-20">Add items to your cart to proceed to checkout.</p>
                  <a class="tp-btn-theme" href="index-2.php"><span>Back to Home</span></a>
                </div>
              </div>
            </div>
          <?php else: ?>
          <div class="row">
            <div class="col-xl-8 col-lg-8">
              <div class="cart-card">
                <div class="cart-head">
                  <h4 class="tp-form-title">Your Items</h4>
                  <span class="tp-badge" style="background:#24262b;color:#9aa0a6;border-radius:999px;padding:6px 10px"><?php echo (int)count($items); ?></span>
                </div>
                <div class="cart-list">
                  <div class="cart-table">
                  <?php foreach ($items as $it): ?>
                    <div class="cart-row">
                      <img class="cart-thumb" src="<?php echo htmlspecialchars((string)($it['image1'] ?? 'assets/img/listing/listing-1-1.png'), ENT_QUOTES); ?>" alt="thumb">
                      <div class="cart-info">
                        <div class="cart-item-title"><?php echo htmlspecialchars((string)$it['product_title'], ENT_QUOTES); ?></div>
                        <div class="cart-meta">Standard delivery • 3–5 days</div>
                      </div>
                      <div class="cart-price">$<?php echo number_format((float)($it['price'] ?? 0), 2); ?></div>
                      <div class="text-end">
                        <button class="cart-remove" data-id="<?php echo (int)$it['id']; ?>"><i class="fa-light fa-xmark"></i> Remove</button>
                      </div>
                    </div>
                  <?php endforeach; ?>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-xl-4 col-lg-4">
              <div class="cart-summary">
                <div class="summary-row"><span>Subtotal</span><span>$<?php echo number_format($total, 2); ?></span></div>
                <div class="summary-row"><span>Shipping</span><span>Free</span></div>
                <div class="summary-row"><span>Tax</span><span>Included</span></div>
                <div class="summary-row" style="border-top:1px solid #24262b;padding-top:10px"><span>Total</span><span class="cart-total">$<?php echo number_format($total, 2); ?></span></div>
                <div class="cart-actions">
                  <a class="tp-btn-border" href="index-2.html"><span>Continue Shopping</span></a>
                  <a class="tp-btn-theme" href="checkout.php"><span>Checkout</span></a>
                </div>
              </div>
            </div>
          </div>
          <?php endif; ?>
        </div>
      </section>
   </main>

   <footer>
      <div class="tp-footer-area z-index black-bg fix p-relative pt-115 pb-70">
         <div class="tp-footer-big-text d-none d-md-block">
            <span>ReWear</span>
         </div>
         <div class="container">
            <div class="row">
               <div class="col-xl-6 col-lg-6 mb-50 wow tpfadeLeft" data-wow-duration=".9s" data-wow-delay=".5s">
                  <div class="tp-footer-widget">
                     <div class="tp-form-box">
                        <div class="tp-footer-title-box pb-50">
                           <span class="tp-section-subtitle-2 mb-10">support email</span>
                           <h4 class="tp-form-title">
                              <a href="mailto:info@listbnb.com">info@listbnb.com</a>
                           </h4>
                        </div>
                        <form action="#">
                           <div class="row">
                              <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                                 <div class="tp-form-input-box">
                                    <label>full name</label>
                                    <input type="text" placeholder="Your name">
                                 </div>
                              </div>
                              <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                                 <div class="tp-form-input-box">
                                    <label>email address</label>
                                    <input type="email" placeholder="Your email">
                                 </div>
                              </div>
                              <div class="col-12">
                                 <div class="tp-form-textarea-box">
                                    <label>message</label>
                                    <textarea placeholder="Your message"></textarea>
                                 </div>
                              </div>
                           </div>                       
                        </form>
                        <div class="tp-form-button">
                           <button class="tp-btn-black theme-bg" type="submit">
                              <span>
                                 Submit 
                                 <i class="fa-sharp fa-regular fa-arrow-right-long"></i>
                              </span>
                           </button>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="col-xl-6 col-lg-6 mb-50 wow tpfadeRight" data-wow-duration=".9s" data-wow-delay=".7s">
                  <div class="tp-footer-widget">                     
                     <div class="tp-footer-right">
                        <h4 class="tp-form-title pb-30">Essential</h4>
                        <div class="tp-footer-list pb-65">
                           <ul>
                              <li><a href="#">Company & Contact Info</a></li>
                              <li><a href="sitemap.html">Sitemap</a></li>
                              <li><a href="privacy.html">Privacy Policy</a></li>
                              <li><a href="faq.html">FAQ Page</a></li>
                              <li><a href="terms.html">Terms & Conditions</a></li>
                           </ul>
                        </div>
                        <div class="tp-footer-content tp-footer-content-border">
                  <p><i>ReWear</i> a Largest Classified Listing Marketplace offers perfect WordPress Ads classified Themes to build your own classified websites.</p>
                           <a href="contact.html"><i class="fal fa-arrow-right-long"></i> Get It Now</a>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>

      <div class="tp-copyright-area black-bg">
         <div class="container">
            <div class="tp-copyright-ptb">            
               <div class="row align-items-center">
                  <div class="col-xl-7 col-lg-6 col-md-6 col-sm-7 wow tpfadeUp" data-wow-duration=".9s" data-wow-delay=".3s">
                     <div class="tp-copyright-left d-flex align-items-center justify-content-center justify-content-md-start">
                        <div class="tp-copyright-logo d-none d-xl-block"><span>ReWear</span></div>
                        <div class="tp-copyright-text text-center text-md-start">
                           <p>Copyright & Design by <a href="#">@ThemePure</a> - 2024</p>
                        </div>
                     </div>
                  </div>
                  <div class="col-xl-5 col-lg-6 col-md-6 col-sm-5 wow tpfadeUp" data-wow-duration=".9s" data-wow-delay=".3s">
                     <div class="tp-copyright-right justify-content-center d-flex justify-content-sm-end align-items-center">
                        <div class="tp-copyright-social">
                           <a href="#"><i class="fa-brands fa-facebook-f"></i></a>
                           <a href="#"><i class="fa-brands fa-twitter"></i></a>
                           <a href="#"><i class="fa-brands fa-behance"></i></a>
                           <a href="#"><i class="fa-brands fa-youtube"></i></a>
                        </div>
                        <div class="tp-copyright__lang d-none d-md-block">
                           <ul>
                               <li>
                                   <a id="tp-copyright__lang-toogle" href="javascript:void(0)">
                                       English
                                       <span><i class="fa-regular fa-angle-up"></i></span>
                                   </a>
                                   <ul class="tp-copyright__lang-submenu">
                                       <li>
                                           <a href="#">Arabic</a>
                                       </li>
                                       <li>
                                           <a href="#">Spanish</a>
                                       </li>
                                       <li>
                                           <a href="#">Mandarin</a>
                                       </li>
                                   </ul>
                               </li>
                           </ul>
                       </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </footer>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/slick.js"></script>
   <script src="assets/js/main.js"></script>
   <script>
     document.querySelectorAll('.cart-remove').forEach(function(b){
       b.addEventListener('click', function(){
         var id = b.getAttribute('data-id');
         fetch('api/cart.php?action=remove', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'id='+encodeURIComponent(id)})
           .then(function(r){ return r.json(); })
           .then(function(){ window.location.reload(); });
       });
     });
   </script>
</body>
</html>
