<?php
session_start();
$conn = new mysqli("localhost","kkfxoaad","Bitok@2025","kkfxoaad_bella");
if($conn->connect_error) die("DB connection failed: ".$conn->connect_error);

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

// Get cart id
if($user_id){
    $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id=?");
    $stmt->bind_param("i",$user_id);
}else{
    $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token=?");
    $stmt->bind_param("s",$session_token);
}
$stmt->execute();
$res = $stmt->get_result();
$cart = $res->fetch_assoc();
$stmt->close();

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

    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="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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">


<style>
@import url('https://fonts.googleapis.com/css?family=Anonymous+Pro');

/* Typewriter Your Cart */
.cursor{
    font-family: 'Anonymous Pro', monospace;
    font-size: 2rem;
    font-weight: bold;
    color: #000;
    text-align: center;
    margin-bottom: 15px;
    width: fit-content;
    margin-left:auto; margin-right:auto;
    border-right: 2px solid rgba(0,0,0,0.75);
    white-space: nowrap;
    overflow: hidden;
    animation: typewriter 3s steps(30) 1s 1 normal both, blinkingCursor 500ms steps(30) infinite normal;
}
@keyframes typewriter { from { width:0; } to { width:100%; } }
@keyframes blinkingCursor { 0%, 100%{ border-right-color: rgba(0,0,0,0.75); } 50% { border-right-color: transparent; } }

/* Background animation */
html, body { height:100%; margin:0; }
.bg, .bg2, .bg3 {
  animation: slide 6s ease-in-out infinite alternate;
  background-image: linear-gradient(-60deg, #fff 50%, #666 50%);
  position: fixed;
  top:0; left:-50%; right:-50%; bottom:0;
  opacity:.80;
  z-index:-1;
}
.bg2 { animation-direction: alternate-reverse; animation-duration:0s; }
.bg3 { 
    animation-duration:13s;
      opacity:.8; }
@keyframes slide { 0% { transform:translateX(-25%); } 100% { transform:translateX(25%); } }

/* Main layout */
main {
    display:flex;
    justify-content:flex-start;
    align-items:flex-start;
    gap:20px;
    flex-wrap: wrap;
    max-width: 1200px;
    margin: auto;
}

/* Cart Items */
.cart-items { flex:2; min-width:280px; }
.cart-item {
    display:flex; align-items:center; justify-content:space-between;
    background:#1a1a1a; padding:10px; border-radius:8px; margin-bottom:8px;
    flex-wrap:wrap;  color: white;
}
.cart-item img { width:70px; height:70px; object-fit:cover; border-radius:5px; margin-right:10px; }
.cart-details { flex:1; font-size:14px; transition: all 0.3s ease; }
.cart-actions { display:flex; flex-direction:column; align-items:flex-end; gap:5px; }
.cart-actions input[type=number] {
    width:60px; padding:5px; border-radius:5px; border:1px solid #333; background:#222; color:#fff; text-align:center;  color: white;
}

/* Buttons */
.btn {
    padding:8px 15px; border:none; border-radius:5px; cursor:pointer;
    font-weight:bold; font-size:13px; color:#fff; background:#555;
    transition: all 0.3s ease;
}
.btn:hover { background:#fff; color:#000; transform:scale(1.05); }

/* Cart Summary */
.cart-summary {
    flex:1; background:#222; padding:10px; border-radius:8px; text-align:center; min-width:220px;
    align-self:flex-end;  color: white;
}
.cart-summary h2 {
    margin-bottom:12px;
    font-size:2rem;
    color: white;
}

/* Responsive */
@media(max-width:768px){
    main { flex-direction:column; align-items:center; }
    .cart-summary { width:100%; margin-top:15px; }
    .cart-actions { flex-direction:row; align-items:center; gap:5px; }
    .cart-item { gap:10px; }
}
</style>
</head>
<body>

<div class="bg"></div>
<div class="bg2"></div>
<div class="bg3"></div>

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

<main>
  <div class="cart-items">
    <div class="cursor">Your Cart</div>
    <?php if(empty($items)): ?>
      <p>Your cart is empty.</p>
      <a href="listing.php" class="btn">Back to Shop</a>
    <?php else: ?>
      <?php foreach($items as $item): ?>
      <div class="cart-item" data-id="<?= $item['cart_item_id'] ?>">
        <img src="uploads/<?= htmlspecialchars($item['image']) ?>" alt="<?= htmlspecialchars($item['name']) ?>">
        <div class="cart-details">
          <strong><?= htmlspecialchars($item['name']) ?></strong><br>
          Price: Ksh <span class="price"><?= number_format($item['price']) ?></span><br>
          Subtotal: Ksh <span class="subtotal"><?= number_format($item['price'] * $item['qty']) ?></span>
        </div>
        <div class="cart-actions">
          <input type="number" class="qty" value="<?= $item['qty'] ?>" min="1">
          <button class="btn update-btn">Update</button>
          <button class="btn remove-btn">Remove</button>
        </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>
    <a href="checkout.php" class="btn">Checkout</a>
    <a href="listing.php" class="btn">Continue Shopping</a>
  </div>
  <?php endif; ?>
</main>

<script>
// Animate number change smoothly
function animateNumber(el, newVal) {
    let current = parseInt(el.textContent.replace(/[^0-9]/g, '')) || 0;
    const step = (newVal - current) / 10;
    let i = 0;
    const interval = setInterval(() => {
        current += step;
        el.textContent = 'Ksh ' + Math.round(current).toLocaleString();
        if (++i >= 10) {
            clearInterval(interval);
            el.textContent = 'Ksh ' + newVal.toLocaleString();
        }
    }, 30);
}

// AJAX Update / Remove functionality
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 formData = new FormData();
        formData.append('update_quantity', 1);
        formData.append('id', id);
        formData.append('quantity', qty);

        const res = await fetch('update-cart.php', { method: 'POST', body: formData });
        const data = await res.json();
        if (data.success) {
            animateNumber(subtotalEl, data.subtotal);
            document.getElementById('total-items').textContent = data.total_items;
            animateNumber(document.getElementById('total-price'), data.total_price);
        }
    }

    async function removeCartItem() {
        const formData = new FormData();
        formData.append('remove_item', 1);
        formData.append('id', id);

        const res = await fetch('update-cart.php', { method: 'POST', body: formData });
        const data = await res.json();
        if (data.success) {
            item.remove();
            document.getElementById('total-items').textContent = data.total_items;
            animateNumber(document.getElementById('total-price'), data.total_price);
        }
    }

    // Auto-update on quantity change with debounce
    let timeout;
    qtyInput.addEventListener('input', () => {
        clearTimeout(timeout);
        const qty = parseInt(qtyInput.value);
        if (qty > 0) {
            timeout = setTimeout(() => { updateCart(qty); }, 300);
        }
    });

    // Optional manual update button
    item.querySelector('.update-btn').addEventListener('click', () => {
        const qty = parseInt(qtyInput.value);
        if (qty > 0) updateCart(qty);
    });

    // Remove button
    item.querySelector('.remove-btn').addEventListener('click', () => {
        removeCartItem();
    });
});
</script></body><?php include "footer.php"; ?>
</body>
</html>
