<?php
session_start();
$userRole = $_SESSION['user_role'] ?? '';
$page_title = 'Shop - Real Time Cart System';
include 'header-php.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <style>
        /* ========== RESET & BASE STYLES ========== */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f8f9fa;
        }

        body {
            padding: 0;
        }

        :root {
            --dynamic-header-offset: 120px;
        }

        /* ========== CONTAINER & LAYOUT ========== */
        .shop-container {
            width: auto;
        }

        .shop-wrapper {
            padding: 10px 0 0;
            overflow-x: clip;
        }

        /* ========== HEADER SECTION ========== */
        .shop-header {
            background: linear-gradient(135deg, #333 0%, #555 100%);
            color: white;
            padding: 2rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .shop-header h1 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .shop-header p {
            font-size: 1rem;
            opacity: 0.9;
        }

        /* ========== AUTHENTICATION ALERTS ========== */
        .alert-section {
            background: #fff3cd;
            border: 2px solid #ffc107;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 1rem;
            text-align: center;
        }

        .alert-section h2 {
            color: #856404;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }

        .alert-section p {
            color: #856404;
            font-size: 1rem;
            margin-bottom: 1.5rem;
        }

        .alert-buttons {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 1rem;
        }

        /* ========== STATUS BAR ========== */
        .status-bar {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
        }

        .status-bar strong {
            flex: 1;
            min-width: 200px;
        }

        /* ========== PRODUCT GRID ========== */
        .products-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1rem;
            margin-bottom: 2rem;
        }

        @media (min-width: 576px) {
            .products-grid {
                grid-template-columns: repeat(2, minmax(0, 1fr));
                gap: 1.25rem;
            }
        }

        @media (min-width: 992px) {
            .products-grid {
                grid-template-columns: repeat(3, minmax(0, 1fr));
                gap: 1.4rem;
            }
        }

        @media (min-width: 1320px) {
            .products-grid {
                grid-template-columns: repeat(4, minmax(0, 1fr));
            }
        }

        /* ========== PRODUCT CARD ========== */
        .product-card {
            background: white;
            border: 1px solid #919191f0;
            border-radius: 8px;
            padding: 1rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow: hidden;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.15);
            border-color: #d4a574;
        }

        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 6px;
            margin-bottom: 1rem;
            background: #f5f5f5;
        }

        @media (min-width: 768px) {
            .product-image {
                height: 220px;
            }
        }

        .product-content {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .product-name {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 0.5rem;
            line-height: 1.4;
        }

        .product-price {
            font-size: 1.4rem;
            color: #d4a574;
            font-weight: 700;
            margin-bottom: 1rem;
        }

        .product-controls {
            margin-top: auto;
        }

        .product-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.5rem;
        }

        /* ========== FAVORITE BUTTON ========== */
        .btn-favorite {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            padding: 0.25rem 0.5rem;
            transition: all 0.3s ease;
            color: #999;
            height: 40px;
            width: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .btn-favorite:hover {
            background: #f0f0f0;
            color: #d4a574;
            transform: scale(1.1);
        }

        .btn-favorite.active {
            color: #ff4444;
        }

        .btn-favorite.active:hover {
            color: #ff2222;
        }

        /* ========== QUANTITY INPUT ========== */
        .quantity-group {
            display: flex;
            align-items: center;
            margin-bottom: 0.75rem;
        }

        .quantity-input {
            width: 70px;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
            text-align: center;
        }

        .quantity-input:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 2px rgba(212, 165, 116, 0.1);
        }

        /* ========== BUTTONS ========== */
        .btn-add-cart {
            width: 100%;
            padding: 0.75rem 1rem;
            background: #333;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }

        .btn-add-cart:hover:not(:disabled) {
            background: #555;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        .btn-add-cart:active:not(:disabled) {
            transform: translateY(0);
        }

        .btn-add-cart:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-login {
            padding: 0.75rem 1.5rem;
            background: #d4a574;
            color: white;
            border: none;
            border-radius: 5px;
            text-decoration: none;
            font-weight: 600;
            display: inline-block;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .btn-login:hover {
            background: #b8905a;
            color: white;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #28a745;
        }

        .btn-secondary:hover {
            background: #218838;
        }

        .btn-danger {
            background: #dc3545;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        /* ========== ACTION BAR ========== */
        .action-bar {
            text-align: center;
            margin: 3rem 0 2rem 0;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 1rem;
        }

        /* ========== TOAST NOTIFICATIONS ========== */
        .toast {
            position: fixed;
            top: 1rem;
            right: 1rem;
            padding: 1rem 1.5rem;
            color: white;
            border-radius: 6px;
            z-index: 9999;
            display: none;
            font-weight: 600;
            animation: slideIn 0.3s ease-out;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            max-width: 90%;
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        @keyframes slideIn {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        /* ========== RESPONSIVE ADJUSTMENTS ========== */
        @media (max-width: 768px) {
            .shop-wrapper {
                padding: 0.6rem;
            }

            .shop-container {
                padding: 0.5rem;
            }

            .shop-header {
                padding: 1.5rem 1rem;
                margin-bottom: 1.5rem;
            }

            .shop-header h1 {
                font-size: 1.5rem;
            }

            .shop-header p {
                font-size: 0.9rem;
            }

            .alert-section {
                padding: 1.5rem 1rem;
                margin-bottom: 1.5rem;
            }

            .alert-section h2 {
                font-size: 1.25rem;
            }

            .alert-buttons {
                gap: 0.75rem;
            }

            .status-bar {
                flex-direction: column;
                text-align: center;
            }

            .status-bar strong {
                flex: 1;
                width: 100%;
            }

            .action-bar {
                gap: 0.75rem;
                margin: 1.5rem 0 1rem 0;
            }

            .btn-login, .btn-add-cart {
                font-size: 0.95rem;
                padding: 0.65rem 1rem;
                width: 100%;
                text-align: center;
            }

            .toast {
                top: auto;
                bottom: 1rem;
                left: 1rem;
                right: 1rem;
                font-size: 0.9rem;
            }
        }

        /* ========== EXTRA SMALL DEVICES (max-width: 480px) ========== */
        @media (max-width: 480px) {
            .shop-wrapper {
                padding: 0.45rem;
            }

            .shop-container {
                padding: 0.25rem;
            }

            .shop-header {
                padding: 1.25rem 0.75rem;
                margin-bottom: 1rem;
            }

            .shop-header h1 {
                font-size: 1.25rem;
                margin-bottom: 0.25rem;
            }

            .shop-header p {
                font-size: 0.85rem;
            }

            .alert-section {
                padding: 1.25rem 0.75rem;
                margin-bottom: 1rem;
            }

            .alert-section h2 {
                font-size: 1.1rem;
                margin-bottom: 0.75rem;
            }

            .alert-section p {
                font-size: 0.9rem;
                margin-bottom: 1rem;
            }

            .alert-buttons {
                gap: 0.5rem;
                flex-direction: column;
            }

            .alert-buttons a {
                width: 100%;
                text-align: center;
            }

            .products-grid {
                gap: 0.9rem;
            }

            .product-card {
                padding: 0.75rem;
            }

            .product-image {
                height: 180px;
                margin-bottom: 0.75rem;
            }

            .product-name {
                font-size: 1rem;
            }

            .product-price {
                font-size: 1.2rem;
            }
        }

        @media (max-width: 360px) {
            .shop-header h1 {
                font-size: 1.25rem;
            }

            .product-price {
                font-size: 1.2rem;
            }

            .btn-login, .btn-add-cart {
                font-size: 0.9rem;
                padding: 0.6rem 0.8rem;
            }
        }

        /* ========== FLOATING CART PANEL ========== */
        .floating-cart {
            position: fixed;
            right: 20px;
            top: 100px;
            width: min(380px, calc(100vw - 2rem));
            background: white;
            border-radius: 10px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            z-index: 10000;
            transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            border-left: 4px solid #d4a574;
            transform: translateX(calc(100% + 40px));
        }

        .floating-cart.active {
            transform: translateX(0);
        }

        .cart-panel-header {
            padding: 1.5rem;
            border-bottom: 2px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(135deg, #d4a574 0%, #b8905a 100%);
            color: white;
            border-radius: 10px 10px 0 0;
        }

        .cart-panel-header h3 {
            margin: 0;
            font-size: 1.2rem;
            font-weight: 700;
        }

        .cart-badge {
            display: inline-block;
            background: #ff4444;
            color: white;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 0.85rem;
            margin-left: 0.5rem;
        }

        .close-cart-btn {
            background: none;
            border: none;
            color: white;
            font-size: 1.5rem;
            cursor: pointer;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .close-cart-btn:hover {
            transform: rotate(90deg);
        }

        .cart-items-list {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
        }

        .cart-item-mini {
            display: flex;
            gap: 0.75rem;
            padding: 1rem;
            border: 1px solid #f0f0f0;
            border-radius: 8px;
            margin-bottom: 0.75rem;
            background: #f9f9f9;
            transition: all 0.3s ease;
        }

        .cart-item-mini:hover {
            background: #f0f0f0;
            border-color: #d4a574;
        }

        .cart-item-mini-img {
            width: 70px;
            height: 70px;
            object-fit: cover;
            border-radius: 6px;
            background: #e0e0e0;
        }

        .cart-item-mini-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .cart-item-mini-name {
            font-weight: 600;
            color: #333;
            font-size: 0.95rem;
            line-height: 1.3;
        }

        .cart-item-mini-price {
            color: #d4a574;
            font-weight: 700;
            font-size: 0.9rem;
        }

        .cart-item-mini-qty {
            color: #999;
            font-size: 0.85rem;
        }

        .cart-empty-msg {
            padding: 2rem 1rem;
            text-align: center;
            color: #999;
            font-size: 0.95rem;
        }

        .cart-panel-footer {
            border-top: 2px solid #f0f0f0;
            padding: 1.5rem;
            background: #f9f9f9;
            border-radius: 0 0 10px 10px;
        }

        .cart-total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
            font-weight: 600;
            color: #333;
        }

        .cart-total-value {
            color: #d4a574;
            font-size: 1.1rem;
        }

        .btn-view-cart-full {
            width: 100%;
            padding: 0.9rem;
            background: linear-gradient(135deg, #d4a574 0%, #b8905a 100%);
            color: white;
            border: none;
            border-radius: 6px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
            margin-bottom: 0.5rem;
        }

        .btn-view-cart-full:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .btn-continue-shop {
            width: 100%;
            padding: 0.9rem;
            background: white;
            color: #d4a574;
            border: 2px solid #d4a574;
            border-radius: 6px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.95rem;
        }

        .btn-continue-shop:hover {
            background: #f9f9f9;
        }

        .cart-toggle-btn {
            position: fixed;
            right: 20px;
            bottom: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #d4a574 0%, #b8905a 100%);
            color: white;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            transition: all 0.3s ease;
        }

        .cart-toggle-btn.show {
            display: flex;
        }

        .cart-toggle-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(212, 165, 116, 0.4);
        }

        .cart-toggle-badge {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ff4444;
            color: white;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 0.8rem;
        }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            .floating-cart {
                width: 100%;
                right: 0;
                left: 0;
                top: auto;
                bottom: 0;
                border-radius: 15px 15px 0 0;
                max-height: 70vh;
                transform: translateY(100%);
            }

            .floating-cart.active {
                transform: translateY(0);
            }

            .cart-toggle-btn {
                right: 15px;
                bottom: 20px;
            }
        }
    </style>
    <!-- Responsive Design System -->
    <link rel="stylesheet" href="assets/css/responsive-utilities.css">
    <link rel="stylesheet" href="assets/css/responsive-chat.css">
</head>
<body>

    <div class="shop-wrapper">
        <div class="shop-container">
            

            <!-- Authentication Section -->
            <?php if (!isset($_SESSION['user_id'])): ?>
                <div class="alert-section">
                    <h2>� Shop as Guest or Login</h2>
                    <p>Browse and add items to your cart. Login when ready to checkout!</p>
                    <div class="alert-buttons">
                        <a href="auth-system/login.php" class="btn-login">🔐 Login</a>
                        <a href="cart.php" class="btn-login btn-secondary">🛒 View Cart</a>
                    </div>
                </div>
            <?php elseif ($userRole !== 'customer'): ?>
                <div class="alert-section">
                    <h2>⛔ Admin Access Only</h2>
                    <p>Admin users cannot shop. Please login as Customer to purchase.</p>
                    <div class="alert-buttons">
                        <a href="auth-system/logout.php" class="btn-login btn-danger">Logout & Login as Customer</a>
                    </div>
                </div>
            <?php else: ?>
                <div class="status-bar">
                    <strong>✅ Welcome, <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Customer'); ?>!</strong>
                    <a href="cart.php" class="btn-login">🛒 View Cart</a>
                </div>
            <?php endif; ?>

            <!-- Products Grid -->
            <div class="products-grid">
                <!-- Product 1 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_1.jpg" alt="Nordic Wooden Chair" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Nordic Wooden Chair</div>
                                <div class="product-price">Rs. 18,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="1" data-name="Nordic Wooden Chair" data-price="18000" data-image="assets/img/product/product_1_1.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="1">
                            </div>
                            <button class="btn-add-cart" data-product-id="1" data-name="Nordic Wooden Chair" data-price="10000" data-image="assets/img/product/product_1_1.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 2 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_2.jpg" alt="Elegant Wooden Chair" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Elegant Wooden Chair</div>
                                <div class="product-price">Rs. 12,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="2" data-name="Elegant Wooden Chair" data-price="12000" data-image="assets/img/product/product_1_2.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="2">
                            </div>
                            <button class="btn-add-cart" data-product-id="2" data-name="Elegant Wooden Chair" data-price="12000" data-image="assets/img/product/product_1_2.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 3 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_3.jpg" alt="Rounded Dining Table" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Rounded Dining Table</div>
                                <div class="product-price">Rs. 14,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="3" data-name="Rounded Dining Table" data-price="14000" data-image="assets/img/product/product_1_3.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="3">
                            </div>
                            <button class="btn-add-cart" data-product-id="3" data-name="Rounded Dining Table" data-price="14000" data-image="assets/img/product/product_1_3.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 4 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_4.jpg" alt="Modern Sofa Set" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Modern Sofa Set</div>
                                <div class="product-price">Rs. 18,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="4" data-name="Modern Sofa Set" data-price="18000" data-image="assets/img/product/product_1_4.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="4">
                            </div>
                            <button class="btn-add-cart" data-product-id="4" data-name="Modern Sofa Set" data-price="18000" data-image="assets/img/product/product_1_4.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 5 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_5.jpg" alt="Wooden Bed Frame" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Wooden Bed Frame</div>
                                <div class="product-price">Rs. 22,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="5" data-name="Wooden Bed Frame" data-price="22000" data-image="assets/img/product/product_1_5.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="5">
                            </div>
                            <button class="btn-add-cart" data-product-id="5" data-name="Wooden Bed Frame" data-price="22000" data-image="assets/img/product/product_1_5.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 6 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_6.jpg" alt="Coffee Table" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Coffee Table</div>
                                <div class="product-price">Rs. 8,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="6" data-name="Coffee Table" data-price="8000" data-image="assets/img/product/product_1_6.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="6">
                            </div>
                            <button class="btn-add-cart" data-product-id="6" data-name="Coffee Table" data-price="8000" data-image="assets/img/product/product_1_6.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 7 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_7.jpg" alt="Bookshelf" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Bookshelf</div>
                                <div class="product-price">Rs. 15,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="7" data-name="Bookshelf" data-price="15000" data-image="assets/img/product/product_1_7.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="7">
                            </div>
                            <button class="btn-add-cart" data-product-id="7" data-name="Bookshelf" data-price="15000" data-image="assets/img/product/product_1_7.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

                <!-- Product 8 -->
                <div class="product-card">
                    <img src="assets/img/product/product_1_8.jpg" alt="Office Desk" class="product-image">
                    <div class="product-content">
                        <div class="product-header">
                            <div>
                                <div class="product-name">Office Desk</div>
                                <div class="product-price">Rs. 16,000</div>
                            </div>
                            <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                                <button class="btn-favorite" data-product-id="8" data-name="Office Desk" data-price="16000" data-image="assets/img/product/product_1_8.jpg" title="Add to favorites">♡</button>
                            <?php endif; ?>
                        </div>
                        <div class="product-controls">
                            <div class="quantity-group">
                                <input type="number" class="quantity-input qty-input" value="1" min="1" data-pid="8">
                            </div>
                            <button class="btn-add-cart" data-product-id="8" data-name="Office Desk" data-price="16000" data-image="assets/img/product/product_1_8.jpg">➕ ADD TO CART</button>
                        </div>
                    </div>
                </div>

            <!-- Action Bar -->
            <div class="action-bar">
                <?php if (isset($_SESSION['user_id']) && $userRole === 'customer'): ?>
                    <a href="cart.php" class="btn-login">🛒 Go to Cart</a>
                    <a href="auth-system/logout.php" class="btn-login btn-danger">Logout</a>
                <?php elseif (isset($_SESSION['user_id'])): ?>
                    <a href="auth-system/logout.php" class="btn-login btn-danger">Logout</a>
                <?php else: ?>
                    <a href="auth-system/login.php" class="btn-login">🔐 Login</a>
                    <a href="auth-system/register.php" class="btn-login btn-secondary">📝 Register</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Toast Notification -->
    <div id="toast" class="toast"></div>

    <!-- Floating Cart Panel -->
    <div class="floating-cart" id="floating-cart">
        <div class="cart-panel-header">
            <div>
                <h3>🛒 Cart
                    <span class="cart-badge" id="cart-count">0</span>
                </h3>
            </div>
            <button class="close-cart-btn" onclick="toggleFloatingCart()">✕</button>
        </div>
        <div class="cart-items-list" id="floating-cart-items">
            <div class="cart-empty-msg">Your cart is empty</div>
        </div>
        <div class="cart-panel-footer">
            <div class="cart-total-row">
                <span>Total:</span>
                <span class="cart-total-value" id="floating-cart-total">Rs. 0</span>
            </div>
            <button class="btn-view-cart-full" onclick="window.location.href='cart.php'">View Full Cart 🛒</button>
            <button class="btn-continue-shop" onclick="toggleFloatingCart()">Continue Shopping</button>
        </div>
    </div>

    <!-- Cart Toggle Button (Mobile) -->
    <button class="cart-toggle-btn" id="cart-toggle-btn" onclick="toggleFloatingCart()">
        🛒
        <span class="cart-toggle-badge" id="toggle-badge">0</span>
    </button>

    <!-- JavaScript -->
    <script>
        /**
         * Set dynamic top spacing based on active header height.
         */
        function syncShopOffsetWithHeader() {
            const selectors = [
                '.th-header',
                '.sticky-wrapper.sticky',
                '.sticky-wrapper',
                'header',
                '.navbar'
            ];

            let maxBottom = 0;
            const measured = new Set();

            selectors.forEach((selector) => {
                document.querySelectorAll(selector).forEach((el) => {
                    if (measured.has(el)) return;
                    measured.add(el);

                    const styles = window.getComputedStyle(el);
                    if (styles.display === 'none' || styles.visibility === 'hidden') return;

                    const rect = el.getBoundingClientRect();
                    if (rect.height <= 0 || rect.bottom <= 0) return;

                    const isOverlayHeader = el.classList.contains('header-absolute');
                    if (isOverlayHeader) return;

                    maxBottom = Math.max(maxBottom, rect.bottom);
                });
            });

            const fallback = window.innerWidth <= 768 ? 88 : 120;
            const offset = Math.max(Math.ceil(maxBottom), fallback);
            document.documentElement.style.setProperty('--dynamic-header-offset', `${offset}px`);
        }

        let headerOffsetFrame = null;
        function scheduleHeaderOffsetSync() {
            if (headerOffsetFrame !== null) return;
            headerOffsetFrame = window.requestAnimationFrame(() => {
                syncShopOffsetWithHeader();
                headerOffsetFrame = null;
            });
        }

        // Real-time cart data
        let cartData = {
            items: [],
            total: 0
        };

        /**
         * Toggle floating cart panel
         */
        function toggleFloatingCart() {
            const cart = document.getElementById('floating-cart');
            const toggleBtn = document.getElementById('cart-toggle-btn');
            cart.classList.toggle('active');
            if (window.innerWidth <= 768) {
                document.body.style.overflow = cart.classList.contains('active') ? 'hidden' : 'auto';
            }
        }

        /**
         * Update floating cart display
         */
        function updateFloatingCart() {
            const container = document.getElementById('floating-cart-items');
            const countBadge = document.getElementById('cart-count');
            const toggleBadge = document.getElementById('toggle-badge');
            const totalSpan = document.getElementById('floating-cart-total');
            const toggleBtn = document.getElementById('cart-toggle-btn');

            if (cartData.items.length === 0) {
                container.innerHTML = '<div class="cart-empty-msg">Your cart is empty</div>';
                countBadge.textContent = '0';
                toggleBadge.textContent = '0';
                toggleBtn.classList.remove('show');
                totalSpan.textContent = 'Rs. 0';
            } else {
                let html = '';
                let total = 0;

                cartData.items.forEach((item, index) => {
                    const itemTotal = parseInt(item.price) * item.quantity;
                    total += itemTotal;
                    html += `
                        <div class="cart-item-mini">
                            <img src="${item.image}" alt="${item.product_name}" class="cart-item-mini-img">
                            <div class="cart-item-mini-info">
                                <div class="cart-item-mini-name">${item.product_name}</div>
                                <div class="cart-item-mini-qty">Qty: ${item.quantity}</div>
                                <div class="cart-item-mini-price">Rs. ${itemTotal.toLocaleString()}</div>
                            </div>
                        </div>
                    `;
                });

                container.innerHTML = html;
                countBadge.textContent = cartData.items.length;
                toggleBadge.textContent = cartData.items.length;
                toggleBtn.classList.add('show');
                totalSpan.textContent = 'Rs. ' + total.toLocaleString();
                cartData.total = total;

                // Auto-show cart panel when item added (desktop only)
                if (window.innerWidth > 768) {
                    const cart = document.getElementById('floating-cart');
                    if (!cart.classList.contains('active')) {
                        setTimeout(() => cart.classList.add('active'), 300);
                        // Auto-hide after 4 seconds
                        setTimeout(() => cart.classList.remove('active'), 6000);
                    }
                }
            }
        }

        /**
         * Load cart from database (for logged-in users)
         */
        async function loadCartFromDatabase() {
            try {
                const response = await fetch('auth-system/cart-api.php?action=get');
                const data = await response.json();
                
                if (data.success && data.items) {
                    cartData.items = data.items;
                    updateFloatingCart();
                }
            } catch (error) {
                console.error('Error loading cart:', error);
            }
        }

        /**
         * Load cart from localStorage (for guests)
         */
        function loadCartFromLocalStorage() {
            const stored = localStorage.getItem('guestCart');
            if (stored) {
                cartData.items = JSON.parse(stored);
                updateFloatingCart();
            }
        }

        // Load cart on page load
        document.addEventListener('DOMContentLoaded', function() {
            scheduleHeaderOffsetSync();
            const isLoggedIn = localStorage.getItem('userLoggedIn');
            if (isLoggedIn) {
                loadCartFromDatabase();
            } else {
                loadCartFromLocalStorage();
            }
        });

        // Real-Time Shopping Cart Handler for Guest & Authenticated Users
        document.querySelectorAll('.btn-add-cart[data-product-id]').forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                
                const productId = this.getAttribute('data-product-id');
                const productName = this.getAttribute('data-name');
                const price = this.getAttribute('data-price');
                const image = this.getAttribute('data-image');
                const qtyInput = document.querySelector(`.qty-input[data-pid="${productId}"]`);
                const quantity = qtyInput ? parseInt(qtyInput.value) || 1 : 1;

                // Show loading state
                this.disabled = true;
                const originalText = this.textContent;
                this.textContent = '⏳ Adding...';

                const isLoggedIn = localStorage.getItem('userLoggedIn');

                if (isLoggedIn) {
                    // LOGGED IN USER: Use database cart
                    addToAuthenticatedCart(productId, productName, price, image, quantity, button, originalText, qtyInput);
                } else {
                    // GUEST USER: Use localStorage cart
                    addToGuestCart(productId, productName, price, image, quantity, button, originalText, qtyInput);
                }
            });
        });

        /**
         * Add to cart for authenticated users (database)
         */
        function addToAuthenticatedCart(productId, productName, price, image, quantity, button, originalText, qtyInput) {
            const formData = new FormData();
            formData.append('product_id', productId);
            formData.append('product_name', productName);
            formData.append('price', price);
            formData.append('image', image);
            formData.append('quantity', quantity);

            fetch('auth-system/cart-api.php?action=add', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('✅ ' + data.message, 'success');
                    if (qtyInput) qtyInput.value = 1;
                    // Reload cart from database in real-time
                    loadCartFromDatabase();
                } else {
                    showToast('❌ ' + (data.message || 'Error'), 'error');
                    button.disabled = false;
                    button.textContent = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('❌ Error adding to cart', 'error');
                button.disabled = false;
                button.textContent = originalText;
            })
            .finally(() => {
                button.disabled = false;
                button.textContent = originalText;
            });
        }

        /**
         * Add to cart for guest users (localStorage)
         */
        function addToGuestCart(productId, productName, price, image, quantity, button, originalText, qtyInput) {
            try {
                const existingItem = cartData.items.find(item => item.product_id == productId);
                
                if (existingItem) {
                    existingItem.quantity += quantity;
                    showToast('✅ Product quantity updated in cart', 'success');
                } else {
                    cartData.items.push({
                        product_id: productId,
                        product_name: productName,
                        price: price,
                        image: image,
                        quantity: quantity
                    });
                    showToast('✅ Product added to cart successfully', 'success');
                }

                localStorage.setItem('guestCart', JSON.stringify(cartData.items));
                updateFloatingCart();
                if (qtyInput) qtyInput.value = 1;
            } catch (error) {
                console.error('Error:', error);
                showToast('❌ Error adding to cart', 'error');
            } finally {
                button.disabled = false;
                button.textContent = originalText;
            }
        }

        /**
         * Display toast notification
         * @param {string} message - Message to display
         * @param {string} type - 'success' or 'error'
         */
        function showToast(message, type) {
            const toast = document.getElementById('toast');
            if (!toast) return;
            
            toast.textContent = message;
            toast.className = 'toast ' + type;
            toast.style.display = 'block';
            
            setTimeout(() => {
                toast.style.display = 'none';
            }, 3000);
        }

        /**
         * Favorite Button Handler
         */
        document.querySelectorAll('.btn-favorite').forEach(button => {
            button.addEventListener('click', async function(e) {
                e.preventDefault();
                
                const productId = this.getAttribute('data-product-id');
                const productName = this.getAttribute('data-name');
                const productPrice = this.getAttribute('data-price');
                const productImage = this.getAttribute('data-image');
                const isFavorite = this.classList.contains('active');
                
                try {
                    const action = isFavorite ? 'remove' : 'add';
                    const endpoint = `auth-system/favorites-api.php?action=${action}`;
                    
                    const response = await fetch(endpoint, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            product_id: productId,
                            product_name: productName,
                            product_price: productPrice,
                            product_image: productImage
                        })
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        this.classList.toggle('active');
                        const message = isFavorite ? 'Removed from favorites' : 'Added to favorites';
                        showToast('❤️ ' + message, 'success');
                    } else {
                        showToast('❌ ' + (data.message || 'Error'), 'error');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    showToast('❌ Error managing favorite', 'error');
                }
            });
        });

        /**
         * Check and load favorite status on page load
         */
        async function loadFavoriteStatus() {
            try {
                const response = await fetch('auth-system/favorites-api.php?action=get_all');
                const data = await response.json();
                
                if (data.success && data.favorites) {
                    const favoriteIds = data.favorites.map(fav => fav.product_id);
                    
                    document.querySelectorAll('.btn-favorite').forEach(button => {
                        const productId = button.getAttribute('data-product-id');
                        if (favoriteIds.includes(parseInt(productId))) {
                            button.classList.add('active');
                        }
                    });
                }
            } catch (error) {
                console.error('Error loading favorites:', error);
            }
        }

        // Load favorite status when page loads
        document.addEventListener('DOMContentLoaded', loadFavoriteStatus);

        // Handle window resize for responsive cart
        window.addEventListener('resize', function() {
            scheduleHeaderOffsetSync();
            if (window.innerWidth > 768) {
                const cart = document.getElementById('floating-cart');
                cart.classList.remove('active');
                document.body.style.overflow = 'auto';
            }
        });

        window.addEventListener('load', scheduleHeaderOffsetSync);
        window.addEventListener('scroll', scheduleHeaderOffsetSync, { passive: true });
    </script>

    <!-- Chat Widget -->
    <?php include 'includes/chat-widget.html'; ?>
    
    <!-- Responsive Chat Script -->
    <script src="assets/js/responsive-chat-ai.js"></script>

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