<?php  
require_once 'require_login.php';
require_once 'db.php'; // centralized DB connection
$is_admin = isset($_SESSION['is_admin']) ? intval($_SESSION['is_admin']) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shop | Taji Yetu</title>
<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">
<?php if ($is_admin): ?>
<link rel="stylesheet" href="admin-sidebar.css">
<?php endif; ?>
<style>
*{margin:0;padding:0;box-sizing:border-box;}
body{font-family:'Segoe UI',sans-serif;background:#000;color:#fff;min-height:100vh;display:flex;flex-direction:column;position:relative;overflow-x:hidden;}
main{padding-top:70px;text-align:center;position:relative;z-index:2;}
<?php if($is_admin): ?>main{margin-left:250px;}<?php endif;?> 

/* Masonry grid */
.masonry{column-count:4;column-gap:10px;padding:0 10px;}
.item{display:inline-block;background:rgba(30,30,30,0.95);border-radius:10px;overflow:hidden;text-align:center;position:relative;margin:0 0 10px;width:100%;animation:fadeUp 0.6s ease forwards;}
.item img{width:100%;display:block;object-fit:cover;filter:grayscale(100%);transition:all 0.5s ease;}
.item:hover img{filter:grayscale(0%);transform:scale(1.05);}
.item.short img{height:120px;}
.item.medium img{height:180px;}
.item.tall img{height:260px;}
.image-wrap{position:relative;}
.floating-buttons{position:absolute;bottom:5px;left:50%;transform:translateX(-50%);display:flex;gap:4px;flex-wrap:nowrap;justify-content:center;max-width:95%;}
.floating-buttons a{padding:3px 5px;font-size:9px;text-decoration:none;border-radius:3px;font-weight:bold;text-align:center;transition:all 0.3s ease;background:#fff;color:#000;white-space:nowrap;flex-shrink:1;min-width:0;}
.floating-buttons a:hover{background:#000;color:#fff;}
.floating-buttons .remove-button{background:#d32f2f;color:#fff;}
.floating-buttons .remove-button:hover{background:#fff;color:#d32f2f;}
.item .cart-icon{position:absolute;bottom:28px;left:5px;font-size:16px;color:#FF7F00;display:none;background:rgba(0,0,0,0.6);padding:4px;border-radius:50%;}
.info{padding:6px;display:flex;flex-direction:column;align-items:center;}
.info .product-name{font-size:12px;font-weight:600;margin-bottom:3px;}
.info .product-price{font-size:10px;color:#e0e0e0;margin-bottom:4px;display:flex;gap:4px;align-items:center;justify-content:center;font-weight:500;}
.info .product-price i{color:#FF7F00;}
.added-overlay{position:absolute;top:5px;right:5px;background:rgba(0,0,0,0.8);color:#fff;padding:3px 6px;border-radius:5px;font-weight:bold;display:none;align-items:center;gap:4px;font-size:0.7rem;}
.added-overlay i{color:#FF7F00;margin-right:3px;}
#floating-cart{position:fixed;top:70px;right:20px;background:#FF7F00;color:#fff;padding:6px;border-radius:25px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:9999;font-weight:bold;border:2px solid #fff;transition:all 0.3s ease;font-size:0.85rem;}
#floating-cart:hover{transform:scale(1.1);background:#fff;color:#000;}
#floating-cart span{margin-left:4px;}
@keyframes fadeUp{0%{opacity:0;transform:translateY(10px);}100%{opacity:1;transform:translateY(0);} }
.pagetitle{color:#fff;text-align:center;margin:15px 0;font-size:1.5em;opacity:0;transform:translateY(-10px);animation:entry 1s forwards;}
@keyframes entry{to{opacity:1;transform:translateY(0);} }
#particles-js{position:fixed;top:0;left:0;width:100%;height:100%;background:#000;z-index:0;overflow:hidden;}
footer{background:rgba(0,0,0,0.85);color:#fff;padding:40px 20px;display:flex;flex-wrap:wrap;justify-content:space-between;gap:20px;}
footer .column{flex:1;min-width:150px;}
footer h4{font-weight:bold;margin-bottom:10px;}
footer a{color:#fff;text-decoration:none;}
footer a:hover{text-decoration:underline;}
footer p{margin-top:10px;font-size:14px;}
@media (max-width:1200px){.masonry{column-count:3;}}
@media (max-width:992px){.masonry{column-count:2;}.floating-buttons a{font-size:8px;padding:2px 4px;}}
@media (max-width:480px){.masonry{column-count:2;}.floating-buttons a{font-size:7px;padding:2px 3px;}}
@media (max-width:768px){<?php if($is_admin): ?>main {margin-left:0 !important;padding-left:0 !important;}<?php endif; ?>}
</style>
</head>
<body>
<div id="particles-js"></div>
<?php include 'navbar.php'; ?>
<?php if($is_admin) include 'admin-sidebar.php'; ?>
<main>
<h2 class="pagetitle">Shop</h2>
<section class="masonry" id="product-list"></section>
<div id="cart-popup"></div>
</main>
<div id="floating-cart"><i class="fa-solid fa-cart-shopping"></i><span>Go to Cart (0)</span></div>

<script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
<script>
// Particles background
particlesJS("particles-js", {
  "particles": {
    "number":{"value":80,"density":{"enable":true,"value_area":800}},
    "color":{"value":"#ffffff"},
    "shape":{"type":"circle"},
    "opacity":{"value":0.8,"random":true,"anim":{"enable":true,"speed":1,"opacity_min":0.1,"sync":false}},
    "size":{"value":2,"random":true,"anim":{"enable":true,"speed":4,"size_min":0.1,"sync":false}},
    "move":{"enable":true,"speed":0.3,"direction":"top","random":true,"straight":false,"out_mode":"out","bounce":false}
  },
  "interactivity":{"events":{"onhover":{"enable":false},"onclick":{"enable":false}},"modes":{}},
  "retina_detect":true
});

// Floating cart draggable
const floatCart = document.getElementById('floating-cart');
let isDragging=false,offsetX=0,offsetY=0;
floatCart.addEventListener('mousedown',e=>{isDragging=true;offsetX=e.clientX-floatCart.offsetLeft;offsetY=e.clientY-floatCart.offsetTop;});
document.addEventListener('mousemove',e=>{if(!isDragging)return;floatCart.style.top=(e.clientY-offsetY)+'px';floatCart.style.left=(e.clientX-offsetX)+'px';});
document.addEventListener('mouseup',()=>isDragging=false);
floatCart.addEventListener('click',()=>window.location.href='cart.php');

// -------------------------
// Fetch and render products
// -------------------------
async function fetchProducts() {
    try {
        const res = await fetch('get-products.php');
        const data = await res.json();
        const container = document.getElementById('product-list');
        container.innerHTML = '';

        // Count items in cart
        let cartCount = 0;

        data.forEach((product, i) => {
            const item = document.createElement('div');
            item.className = 'item';
            const variation = ['short','medium','tall'][Math.floor(Math.random()*3)];
            item.classList.add(variation);
            item.style.animationDelay = (i*0.08)+'s';
            
            // Show overlay and icon if already in cart
            const inCartDisplay = product.in_cart ? 'block' : 'none';
            const overlayText = product.in_cart ? 'In Cart' : 'Added to cart';
            if(product.in_cart) cartCount++;

            item.innerHTML = `
                <div class="image-wrap">
                    <img src="uploads/${product.image}" alt="${product.name}">
                    <div class="added-overlay" style="display:${product.in_cart ? 'flex' : 'none'};">
                        <i class="fa-solid fa-cart-shopping"></i>
                        <span>${overlayText}</span>
                    </div>
                    <i class="fa-solid fa-cart-shopping cart-icon" style="display:${inCartDisplay}; color:#FF7F00;"></i>
                    <div class="floating-buttons">
                        <a class="buy-button" href="#" data-id="${product.id}">Add to cart</a>
                        <a class="view-button" href="product.php?id=${product.id}">View</a>
                        <a class="remove-button" href="#" data-id="${product.id}">Remove</a>
                    </div>
                </div>
                <div class="info">
                    <div class="product-name">${product.name}</div>
                    <div class="product-price"><i class="fa-solid fa-tag"></i> Ksh ${parseInt(product.price).toLocaleString()}</div>
                </div>
            `;
            container.appendChild(item);
        });

        // Update floating cart count on page load
        floatCart.querySelector('span').textContent = `Go to Cart (${cartCount})`;

    } catch(err) {
        console.error('Error fetching products:', err);
    }
}

// -------------------------
// Handle Add / Remove Cart
// -------------------------
document.getElementById('product-list').addEventListener('click', async e => {
    const itemDiv = e.target.closest('.item');
    if(!itemDiv) return;

    const overlay = itemDiv.querySelector('.added-overlay');
    const cartIcon = itemDiv.querySelector('.cart-icon');

    // Add to cart
    if(e.target.matches('.buy-button[data-id]')) {
        e.preventDefault();
        const id = e.target.dataset.id;
        try {
            const formData = new FormData();
            formData.append('add_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) {
                cartIcon.style.display = 'block';
                overlay.style.display = 'flex';
                overlay.querySelector('span').textContent = 'Added to cart!';
                setTimeout(() => { overlay.style.display = 'none'; }, 1500);
                floatCart.querySelector('span').textContent = `Go to Cart (${data.total_items})`;
            }
        } catch(err){ console.error(err); }
    }

    // Remove from cart
    if(e.target.matches('.remove-button[data-id]')) {
        e.preventDefault();
        const id = e.target.dataset.id;
        try {
            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) {
                cartIcon.style.display = 'none';
                overlay.style.display = 'flex';
                overlay.querySelector('span').textContent = 'Removed from cart!';
                setTimeout(() => { overlay.style.display = 'none'; }, 1500);
                floatCart.querySelector('span').textContent = `Go to Cart (${data.total_items})`;
            }
        } catch(err){ console.error(err); }
    }
});

// -------------------------
// Initialize products
// -------------------------
fetchProducts();
</script>

<script>
document.addEventListener('DOMContentLoaded', () => {

  // Add item
  document.querySelectorAll('.add-to-cart').forEach(btn => {
    btn.addEventListener('click', () => {
      const pid = btn.dataset.id;
      const form = new FormData();
      form.append('add_item', 1);
      form.append('id', pid);

      fetch('update_cart.php', { method: 'POST', body: form })
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            // Update navbar count dynamically
            if (window.refreshCartCount) window.refreshCartCount();
          }
        });
    });
  });

  // Remove item
  document.querySelectorAll('.remove-from-cart').forEach(btn => {
    btn.addEventListener('click', () => {
      const pid = btn.dataset.id;
      const form = new FormData();
      form.append('remove_item', 1);
      form.append('id', pid);

      fetch('update_cart.php', { method: 'POST', body: form })
        .then(res => res.json())
        .then(data => {
          if (data.success) {
            // Update navbar count dynamically
            if (window.refreshCartCount) window.refreshCartCount();
          }
        });
    });
  });

});
</script>


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