<?php
// ------------------------------------------
// 1. SESSION MANAGEMENT AND INITIAL COUNT
// ------------------------------------------
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Only calculate the count initially. The full content will be fetched via AJAX.
$cartCount = array_sum(array_column($_SESSION['cart'] ?? [], 'qty'));
$isLoggedIn = isset($_SESSION['user_id']);
?>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

<style>
:root{
    --primary:#002344;
}
body{
    font-family:'Poppins', sans-serif;
    overflow-x:hidden;
}

/* HEADER */
header{
    width:100%;
    background:#fff;
    padding:10px 35px;    /* reduced height */
    display:flex;
    align-items:center;
    justify-content:space-between;
    border-bottom:1px solid #eee;
    position:sticky;
    top:0;
    z-index:9000;
}


/* LOGO - MODIFIED FOR LARGER SIZE */
.logo img{
    width:220px;      /* change this value as you want */
    height:75px;
    object-fit:contain;
}


/* NAV */
nav{
    display:flex;
    gap:28px;
}

nav a{
    text-decoration:none;
    color:#222;
    font-weight:500;
    font-size:15px;
}

nav a:hover{
    color:var(--primary);
}

/* ICONS */
.icons{
    display:flex;
    align-items:center;
    gap:22px;
}

.icon{
    position:relative;
}

.icon img{
    width:28px;
    filter:invert(20%) sepia(10%) saturate(400%);
}

/* CART BADGE */
.cart-count{
    position:absolute;
    top:-6px;
    right:-6px;
    background:#ff0044;
    color:#fff;
    font-size:10px;
    padding:2px 6px;
    border-radius:50%;
}

/* MOBILE */
.menu-btn{
    display:none;
    cursor: pointer;
}

.menu-btn img{
    width:28px;
}

.mobile-nav{
    position:fixed;
    top:0;
    left:0;
    width:75%;
    max-width:330px;
    height:100%;
    background:white;
    padding:25px;
    box-shadow:4px 0 20px rgba(0,0,0,0.18);
    transform:translateX(-100%);
    transition:0.35s ease;
    z-index:9999;
}

.mobile-nav.active{
    transform:translateX(0);
}

.mobile-nav a{
    text-decoration:none;
    color:#222;
    display:block;
    padding:14px 0;
    font-size:17px;
    border-bottom:1px solid #eee;
}

@media(max-width:768px){
    nav{ display:none; }
    .menu-btn{ display:block; }
    header{ padding:15px 20px; }
    .logo img{ height:55px; } /* Updated mobile logo height */
}

/* MINI CART CSS */
.mini-cart-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.45);
    display: none;
    z-index: 9998;
}

.mini-cart {
    position: fixed;
    top: 0;
    right: -380px;
    width: 360px;
    height: 100%;
    background: #fff;
    box-shadow: -3px 0 20px rgba(0,0,0,0.25);
    z-index: 9999;
    display: flex;
    flex-direction: column;
    transition: 0.35s ease;
    border-left: 2px solid #eee;
    padding-bottom: 20px;
}

.mini-cart.open {
    right: 0;
}

.mini-cart-backdrop.show {
    display: block;
}

.mc-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.mc-header h3 {
    font-size: 20px;
    margin: 0;
}

.mc-close {
    font-size: 22px;
    cursor: pointer;
    padding: 5px 10px;
}

.mc-items {
    flex: 1;
    overflow-y: auto;
    padding: 15px;
}

.mc-item {
    display: flex;
    gap: 12px;
    margin-bottom: 15px;
    border-bottom: 1px solid #f1f1f1;
    padding-bottom: 12px;
}

.mc-item img {
    width: 60px;
    height: 60px;
    border-radius: 6px;
    object-fit: cover;
    background: #f7f7f7;
}

.mc-item .details {
    flex: 1;
    font-size: 14px;
}

.mc-item .details strong {
    font-size: 15px;
}

.mc-footer {
    border-top: 1px solid #eee;
    padding: 18px;
}

.mc-total {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    font-size: 17px;
}

.mc-btn {
    display: block;
    width: 100%;
    text-align: center;
    background: var(--primary);
    color: #fff;
    padding: 12px;
    border-radius: 5px;
    font-weight: 600;
    text-decoration: none;
    margin-bottom: 10px;
}

.mc-btn.view {
    background:#333;
}

.mc-btn.checkout {
    background:#002344;
}

</style>

<header>
    <div class="logo">
        <a href="index.php">
            <img src="https://lalitavarahifoods.com/uploads/lalitavarahifoodslogo.png">
        </a>
    </div>

    <nav>
        <a href="home.php">Home</a>
        <a href="products.php">Products</a>
        <a href="about.php">About</a>
        <a href="contact.php">Contact</a>
    </nav>

    <div class="icons">
        <a href="#" class="icon" id="cartIconHeader" onclick="openMiniCart(event)">
            <img src="https://img.icons8.com/ios-filled/50/shopping-bag.png">
            <?php if($cartCount>0): ?>
                <span class="cart-count"><?= $cartCount ?></span>
            <?php endif; ?>
        </a>

        <?php if($isLoggedIn): ?>
            <a href="profile.php" class="icon">
                <img src="https://img.icons8.com/ios-filled/50/user.png">
            </a>
        <?php else: ?>
            <a href="auth.php" class="icon">
                <img src="https://img.icons8.com/ios-filled/50/user-male-circle.png">
            </a>
        <?php endif; ?>

        <div class="menu-btn" onclick="openMenu()">
            <img src="https://img.icons8.com/ios-filled/50/menu--v1.png">
        </div>
    </div>
</header>

<div id="mobileNav" class="mobile-nav">
    <div style="text-align: right; padding-bottom: 15px; border-bottom: 1px solid #eee;">
        <span onclick="closeMenu()" style="font-size: 24px; cursor: pointer;">✕</span>
    </div>
    <a href="home.php">Home</a>
    <a href="products.php">Products</a>
    <a href="about.php">About</a>
    <a href="contact.php">Contact</a>
    <?php if($isLoggedIn): ?>
        <a href="profile.php">Profile</a>
    <?php else: ?>
        <a href="auth.php">Login / Register</a>
    <?php endif; ?>
</div>

<div id="miniCartBackdrop" class="mini-cart-backdrop"></div>

<div id="miniCart" class="mini-cart">
    <div class="mc-header">
        <h3>Your Cart</h3>
        <span class="mc-close" onclick="closeMiniCart()">✕</span>
    </div>

    <div id="miniCartItems" class="mc-items">
        <div style="text-align:center; padding: 40px;">Click the cart icon to load items.</div>
    </div>

    <div class="mc-footer">
        <div class="mc-total">
            <span>Total:</span>
            <strong id="miniCartTotal">Rs. 0.00</strong>
        </div>

        <a href="cart.php" class="mc-btn view">View Cart</a>
        <a href="checkout.php" class="mc-btn checkout">Checkout</a>
    </div>
</div>

<script>
// Get references to elements
const mobileNav = document.getElementById("mobileNav");
const miniCart = document.getElementById("miniCart");
const miniCartBackdrop = document.getElementById("miniCartBackdrop");
const cartIconHeader = document.getElementById("cartIconHeader");

/* ------------------- */
/* MOBILE MENU JS      */
/* ------------------- */

function openMenu(){
    if (mobileNav) {
        mobileNav.classList.add("active");
    }
}

function closeMenu() {
    if (mobileNav) {
        mobileNav.classList.remove("active");
    }
}

document.body.addEventListener("click", function(e){
    if(!mobileNav) return; 
    if(e.target.closest(".menu-btn") || e.target.closest(".mobile-nav")) return;
    mobileNav.classList.remove("active");
});

/* ------------------- */
/* MINI CART JS (DYNAMIC) */
/* ------------------- */

/**
 * Opens the mini-cart panel and triggers dynamic data fetch.
 * This is called when the user clicks the cart icon in the header.
 * @param {Event} e - The click event object (optional).
 */
function openMiniCart(e) {
    if (e) {
        e.preventDefault(); // Stop navigation to cart.php
    }
    
    // 1. Show the mini-cart container
    if (miniCart && miniCartBackdrop) {
        miniCart.classList.add("open");
        miniCartBackdrop.classList.add("show");
    }
    
    // 2. Fetch and inject the latest cart content
    fetchCartData();
}

/**
 * Fetches the latest cart data from fetch_cart.php and updates the display.
 */
function fetchCartData() {
    // Show loading message while fetching
    document.getElementById("miniCartItems").innerHTML = '<div style="text-align:center; padding: 40px;">Loading cart...</div>';

    // The fetch call goes to the separate data endpoint
    fetch('fetch_cart.php') 
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Update Mini Cart HTML and Total
            document.getElementById("miniCartItems").innerHTML = data.html;
            document.getElementById("miniCartTotal").innerText = 'Rs. ' + data.total;
            
            // Update the cart icon badge
            updateCartIcon(data.count); 
        })
        .catch(error => {
            console.error('Error fetching cart data:', error);
            document.getElementById("miniCartItems").innerHTML = '<div style="text-align:center; padding: 40px; color: red;">Failed to load cart data.</div>';
        });
}

function closeMiniCart() {
    if (miniCart && miniCartBackdrop) {
        miniCart.classList.remove("open");
        miniCartBackdrop.classList.remove("show");
    }
}

if (miniCartBackdrop) {
    miniCartBackdrop.onclick = closeMiniCart;
}




document.addEventListener("DOMContentLoaded", () => {
    fetch("fetch_cart.php")
        .then(res => res.json())
        .then(data => updateCartIcon(data.count));
});

/**
 * Updates the visibility and count of the cart badge.
 */
function updateCartIcon(count) {
    let container = document.querySelector("#cartIconHeader");
    let icon = document.querySelector("#cartIconHeader .cart-count");

    if (count > 0) {
        if (icon) {
            icon.innerText = count;
        } else {
            let badge = document.createElement("span");
            badge.classList.add("cart-count");
            badge.innerText = count;
            container.appendChild(badge);
        }
    } else {
        if (icon) {
            icon.remove();
        }
    }
}

// AUTO REFRESH CART COUNT ON EVERY PAGE LOAD
document.addEventListener("DOMContentLoaded", () => {
    fetch("fetch_cart.php")
        .then(res => res.json())
        .then(data => {
            updateCartIcon(data.count);
        });
});


</script>