<?php
session_start();
require_once 'db.php'; // PDO connection

// remember current page so login can return here
$_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];

$user_id = $_SESSION['user_id'] ?? null;
$session_token = session_id();

// Get cart id (PDO)
if ($user_id) {
    $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id = ?");
    $stmt->execute([$user_id]);
} else {
    $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token = ?");
    $stmt->execute([$session_token]);
}
$cart = $stmt->fetch(PDO::FETCH_ASSOC);

$items = [];
$total = 0;
if ($cart) {
    $cart_id = $cart['id'];
    $stmt = $conn->prepare("
        SELECT ci.id AS cart_item_id, ci.qty, ci.price, p.id AS product_id, p.name, p.image 
        FROM cart_items ci
        JOIN products p ON ci.product_id = p.id
        WHERE ci.cart_id = ?
    ");
    $stmt->execute([$cart_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($items as $item) {
        $total += ($item['price'] * $item['qty']);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Your Cart - Taji Yetu</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<style>
/* --- Common Black & White Theme + Strong Animated Background --- */
:root {
  --bg-dark: #000;
  --panel: #111;
  --panel-2: #1a1a1a;
  --muted: #666;
  --accent: #fff;
}

html,body{height:100%;}
body {
  margin:0;
  font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  background: var(--bg-dark);
  color: var(--accent);
  -webkit-font-smoothing:antialiased;
  -moz-osx-font-smoothing:grayscale;
  overflow-x:hidden;
  position:relative;
}

/* stronger animated background visible on black theme */
body::before{
  content:'';
  position:fixed;
  inset:0;
  z-index:-1;
  background:
    radial-gradient(circle at 10% 20%, rgba(255,255,255,0.12), transparent 20%),
    radial-gradient(circle at 85% 80%, rgba(255,255,255,0.06), transparent 25%),
    linear-gradient(180deg, #000 0%, #0b0b0b 100%);
  background-size: 200% 200%, 200% 200%, 100% 100%;
  animation: bgMove 14s ease-in-out infinite;
  opacity:1;
}
@keyframes bgMove {
  0% { background-position: 0% 0%, 100% 100%, 0% 0%; }
  50%{ background-position: 100% 100%, 0% 0%, 0% 0%; }
  100%{ background-position: 0% 0%, 100% 100%, 0% 0%; }
}

/* Page layout */
main{
  display:flex;
  flex-wrap:wrap;
  max-width:1200px;
  margin: auto;
  padding: 100px 20px 40px;
  gap:20px;
  position:relative;
  z-index:1;
}

/* Cart column */
.cart-items {
  flex: 2;
  min-width: 300px;
  background: var(--panel-2);
  border-radius: 10px;
  padding:16px;
  box-shadow: 0 6px 20px rgba(0,0,0,0.6);
}

/* Cart item */
.cart-item{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  padding:12px;
  border-bottom:1px solid rgba(255,255,255,0.04);
  flex-wrap:wrap;
  background: transparent;
  transition: background 150ms ease;
  opacity:0;
  animation:fadeUp 0.6s ease forwards;
}
.cart-item:hover { background: rgba(255,255,255,0.01); }

.cart-item img{
  width:72px;
  height:72px;
  object-fit:cover;
  border-radius:8px;
  background:#000;
  flex-shrink:0;
  box-shadow: 0 4px 12px rgba(0,0,0,0.6);
}

.cart-details{ flex:1; min-width:160px; font-size:14px; line-height:1.3; color:var(--accent); }
.cart-details strong{ display:block; margin-bottom:6px; }

/* Actions */
.cart-actions{ display:flex; gap:8px; align-items:center; margin-left:8px; }
.cart-actions input[type="number"]{
  width:66px;
  padding:6px;
  border-radius:6px;
  border:1px solid rgba(255,255,255,0.06);
  background:#000;
  color:#fff;
  text-align:center;
}
.btn{ padding:8px 14px; border-radius:6px; border:none; cursor:pointer; font-weight:600; font-size:13px; }
.btn-muted{ background:#444; color:#fff; }
.btn-muted:hover{ background:#fff; color:#000; transform:scale(1.03); }
.btn-danger{ background:#b33; color:#fff; }
.btn-danger:hover{ background:#fff; color:#b33; transform:scale(1.03); }
.btn-primary{ background:#28a745; color:#fff; }
.btn-primary:hover{ background:#fff; color:#28a745; transform:scale(1.03); }

/* Summary */
.cart-summary{
  flex:1;
  min-width:240px;
  background: var(--panel);
  padding:18px;
  border-radius:10px;
  text-align:center;
  position:sticky;
  top:90px;
  box-shadow: 0 6px 20px rgba(0,0,0,0.6);
  opacity:0;
  animation:fadeUp 0.6s ease forwards;
}
.cart-summary h2{ margin:0 0 12px; font-size:1.4rem; }

/* Animations */
@keyframes fadeUp {
  from { opacity:0; transform:translateY(14px); }
  to   { opacity:1; transform:translateY(0); }
}

/* Responsive */
@media(max-width:860px){
  main{ padding-top:120px; }
  .cart-summary{ position:relative; top:0; width:100%; }
  .cart-item{ gap:8px; }
}
</style>
</head>
<body>

<?php include "navbar.php"; ?>
<?php include "sidebar.php"; ?>

<main>
  <div class="cart-items">
    <h1>Your Cart</h1>

    <?php if (empty($items)): ?>
      <p style="color:#fff; padding:12px;">Your cart is empty.</p>
      <a href="listing.php" class="btn btn-muted" style="margin:12px 0; display:inline-block;">Back to Shop</a>
    <?php else: ?>
      <?php foreach ($items as $index => $item): ?>
        <div class="cart-item" style="animation-delay:<?= ($index * 0.08) ?>s" data-id="<?= htmlspecialchars($item['cart_item_id']) ?>">
          <img src="uploads/<?= htmlspecialchars($item['image']) ?>" alt="<?= htmlspecialchars($item['name']) ?>">
          <div class="cart-details">
            <strong><?= htmlspecialchars($item['name']) ?></strong>
            <div>Price: Ksh <span class="price"><?= number_format($item['price']) ?></span></div>
            <div>Subtotal: Ksh <span class="subtotal"><?= number_format($item['price'] * $item['qty']) ?></span></div>
          </div>

          <div class="cart-actions">
            <input type="number" class="qty" value="<?= htmlspecialchars($item['qty']) ?>" min="1">
            <button class="btn btn-danger remove-btn">Remove</button>
            <a class="btn btn-primary" href="product.php?id=<?= htmlspecialchars($item['product_id']) ?>">View</a>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <?php if (!empty($items)): ?>
    <div class="cart-summary">
      <h2>Order Summary</h2>
      <p>Items: <span id="total-items"><?= array_sum(array_column($items, 'qty')) ?></span></p>
      <p>Total: Ksh <span id="total-price"><?= number_format($total) ?></span></p>
      <div style="margin-top:12px;">
        <a class="btn btn-primary" href="checkout.php">Checkout</a>
        <a class="btn btn-muted" href="listing.php" style="margin-left:8px;">Continue Shopping</a>
      </div>
      <div style="margin-top:12px;">
        <button id="clear-cart" class="btn btn-danger">Clear Cart</button>
      </div>
    </div>
  <?php endif; ?>
</main>

<script>
// Animate numeric changes (used for subtotal/total)
function animateNumberElement(el, newVal, prefix = 'Ksh ') {
  const clean = (v) => parseInt(String(v).replace(/[^0-9]/g,'')) || 0;
  let current = clean(el.textContent);
  const target = Math.round(newVal);
  const steps = 10;
  const step = (target - current) / steps;
  let i = 0;
  const iv = setInterval(() => {
    current = Math.round(current + step);
    el.textContent = prefix + current.toLocaleString();
    if (++i >= steps) {
      clearInterval(iv);
      el.textContent = prefix + target.toLocaleString();
    }
  }, 25);
}

// Wire up update/remove handlers
document.querySelectorAll('.cart-item').forEach(item => {
  const id = item.dataset.id;
  const qtyInput = item.querySelector('.qty');
  const subtotalEl = item.querySelector('.subtotal');

  async function updateCart(qty) {
    const fd = new FormData();
    fd.append('update_quantity', 1);
    fd.append('id', id);
    fd.append('quantity', qty);

    try {
      const res = await fetch('update_cart.php', { method: 'POST', body: fd });
      const data = await res.json();
      if (data.success) {
        // server returns numeric subtotal and totals (assumed)
        if (data.subtotal !== undefined) animateNumberElement(subtotalEl, data.subtotal);
        if (data.total_price !== undefined) animateNumberElement(document.getElementById('total-price'), data.total_price);
        if (data.total_items !== undefined) document.getElementById('total-items').textContent = data.total_items;
      }
    } catch (e) {
      console.error(e);
    }
  }

  async function removeItem() {
    const fd = new FormData();
    fd.append('remove_item', 1);
    fd.append('id', id);
    try {
      const res = await fetch('update_cart.php', { method: 'POST', body: fd });
      const data = await res.json();
      if (data.success) {
        item.remove();
        if (data.total_items !== undefined) document.getElementById('total-items').textContent = data.total_items;
        if (data.total_price !== undefined) animateNumberElement(document.getElementById('total-price'), data.total_price);
        if (data.total_items === 0) {
          document.querySelector('.cart-items').innerHTML = '<p style="color:white;padding:15px;">Your cart is empty.</p><a href="listing.php" class="btn btn-muted" style="margin:15px;">Back to Shop</a>';
          const summary = document.querySelector('.cart-summary');
          if (summary) summary.remove();
        }
      }
    } catch (e) {
      console.error(e);
    }
  }

  let timeout;
  qtyInput.addEventListener('input', () => {
    clearTimeout(timeout);
    const qty = parseInt(qtyInput.value) || 1;
    timeout = setTimeout(() => updateCart(qty), 350);
  });

  const removeBtn = item.querySelector('.remove-btn');
  if (removeBtn) removeBtn.addEventListener('click', removeItem);
});

// Clear cart
const clearBtn = document.getElementById('clear-cart');
if (clearBtn) {
  clearBtn.addEventListener('click', async () => {
    const fd = new FormData();
    fd.append('clear_cart', 1);
    try {
      const res = await fetch('update_cart.php', { method: 'POST', body: fd });
      const data = await res.json();
      if (data.success) {
        document.querySelector('.cart-items').innerHTML = '<p style="color:white;padding:15px;">Your cart is empty.</p><a href="listing.php" class="btn btn-muted" style="margin:15px;">Back to Shop</a>';
        const summary = document.querySelector('.cart-summary');
        if (summary) summary.remove();
      }
    } catch (e) {
      console.error(e);
    }
  });
}
</script>

<?php include "footer.php"; ?>
</body>
</html>
