<?php
/**
 * Footer Template
 * Includes footer and closing scripts
 */
?>

    <!-- Page footer -->
    <footer class="footer position-relative bg-dark">
      <span class="position-absolute top-0 start-0 w-100 h-100 bg-body d-none d-block-dark"></span>
      <div class="container position-relative z-1 pt-sm-2 pt-md-3 pt-lg-4" data-bs-theme="dark">

        <!-- Columns with links that are turned into accordion on screens < 500px wide (sm breakpoint) -->
        <div class="accordion py-5" id="footerLinks">
          <div class="row">
            <div class="col-md-4 d-sm-flex flex-md-column align-items-center align-items-md-start pb-3 mb-sm-4">
              <h4 class="mb-sm-0 mb-md-4 me-4">
                <a class="text-dark-emphasis text-decoration-none" href="/">Cartzilla</a>
              </h4>
              <p class="text-body fs-sm text-sm-end text-md-start mb-sm-0 mb-md-3 ms-0 ms-sm-auto ms-md-0 me-4">Got questions? Contact us 24/7</p>
              <div class="dropdown" style="max-width: 250px">
                <button type="button" class="btn btn-light dropdown-toggle justify-content-between w-100 d-none-dark" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  Help and consultation
                </button>
                <button type="button" class="btn btn-secondary dropdown-toggle justify-content-between w-100 d-none d-flex-dark" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  Help and consultation
                </button>
                <ul class="dropdown-menu">
                  <li><a class="dropdown-item" href="help-topics-v2.php">Help center &amp; FAQ</a></li>
                  <li><a class="dropdown-item" href="contact-v3.php">Support chat</a></li>
                  <li><a class="dropdown-item" href="contact-v3.php">Open support ticket</a></li>
                  <li><a class="dropdown-item" href="contact-v3.php">Call center</a></li>
                </ul>
              </div>
            </div>
            <div class="col-md-8">
              <div class="row row-cols-1 row-cols-sm-3 gx-3 gx-md-4">
                <div class="accordion-item col border-0">
                  <h6 class="accordion-header" id="companyHeading">
                    <span class="text-dark-emphasis d-none d-sm-block">Company</span>
                    <button type="button" class="accordion-button collapsed py-3 d-sm-none" data-bs-toggle="collapse" data-bs-target="#companyLinks" aria-expanded="false" aria-controls="companyLinks">Company</button>
                  </h6>
                  <div class="accordion-collapse collapse d-sm-block" id="companyLinks" aria-labelledby="companyHeading" data-bs-parent="#footerLinks">
                    <ul class="nav flex-column gap-2 pt-sm-3 pb-3 mt-n1 mb-1">
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="about-v1.php">About company</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="about-v1.php">Our team</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="about-v1.php">Careers</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="contact-v3.php">Contact us</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="blog-list.php">News</a>
                      </li>
                    </ul>
                  </div>
                  <hr class="d-sm-none my-0">
                </div>
                <div class="accordion-item col border-0">
                  <h6 class="accordion-header" id="accountHeading">
                    <span class="text-dark-emphasis d-none d-sm-block">Account</span>
                    <button type="button" class="accordion-button collapsed py-3 d-sm-none" data-bs-toggle="collapse" data-bs-target="#accountLinks" aria-expanded="false" aria-controls="accountLinks">Account</button>
                  </h6>
                  <div class="accordion-collapse collapse d-sm-block" id="accountLinks" aria-labelledby="accountHeading" data-bs-parent="#footerLinks">
                    <ul class="nav flex-column gap-2 pt-sm-3 pb-3 mt-n1 mb-1">
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="/cont/info">Contul tău</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Shipping rates &amp; policies</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Refunds &amp; replacements</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Delivery info</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="/cont/comenzi">Urmărire comandă</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Taxes &amp; fees</a>
                      </li>
                    </ul>
                  </div>
                  <hr class="d-sm-none my-0">
                </div>
                <div class="accordion-item col border-0">
                  <h6 class="accordion-header" id="customerHeading">
                    <span class="text-dark-emphasis d-none d-sm-block">Customer service</span>
                    <button type="button" class="accordion-button collapsed py-3 d-sm-none" data-bs-toggle="collapse" data-bs-target="#customerLinks" aria-expanded="false" aria-controls="customerLinks">Customer service</button>
                  </h6>
                  <div class="accordion-collapse collapse d-sm-block" id="customerLinks" aria-labelledby="customerHeading" data-bs-parent="#footerLinks">
                    <ul class="nav flex-column gap-2 pt-sm-3 pb-3 mt-n1 mb-1">
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="/cont/plata">Metode de plată</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Money back guarantee</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Product returns</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Support center</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="help-topics-v2.php">Shipping</a>
                      </li>
                      <li class="d-flex w-100 pt-1">
                        <a class="nav-link animate-underline animate-target d-inline fw-normal text-truncate p-0" href="terms-and-conditions.php">Terms &amp; conditions</a>
                      </li>
                    </ul>
                  </div>
                  <hr class="d-sm-none my-0">
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Category / tag links -->
        <div class="d-flex flex-column gap-3 pb-3 pb-md-4 pb-lg-5 mt-n2 mt-sm-n4 mt-lg-0 mb-4">
          <ul class="nav align-items-center text-body-tertiary gap-2">
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/computers">Computere</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/smartphones">Smartphone-uri</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/tv-video">TV, Video</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/speakers">Boxe</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/cameras">Camere</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/printers">Imprimante</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/video-games">Jocuri video</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/headphones">Căști</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/wearable">Wearable</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/hdd-ssd">HDD/SSD</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/smart-home">Smart Home</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/apple-devices">Dispozitive Apple</a>
            </li>
            <li class="px-1">/</li>
            <li class="animate-underline">
              <a class="nav-link fw-normal p-0 animate-target" href="/catalog/tablets">Tablete</a>
            </li>
          </ul>
        </div>

        <!-- Copyright + Payment methods -->
        <div class="d-md-flex align-items-center border-top py-4">
          <div class="d-flex gap-2 gap-sm-3 justify-content-center ms-md-auto mb-4 mb-md-0 order-md-2">
            <div>
              <img src="/assets/img/payment-methods/visa-dark-mode.svg" alt="Visa">
            </div>
            <div>
              <img src="/assets/img/payment-methods/mastercard.svg" alt="Mastercard">
            </div>
            <div>
              <img src="/assets/img/payment-methods/paypal-dark-mode.svg" alt="PayPal">
            </div>
            <div>
              <img src="/assets/img/payment-methods/google-pay-dark-mode.svg" alt="Google Pay">
            </div>
            <div>
              <img src="/assets/img/payment-methods/apple-pay-dark-mode.svg" alt="Apple Pay">
            </div>
          </div>
          <p class="text-body fs-xs text-center text-md-start mb-0 me-4 order-md-1">&copy; <?php echo date('Y'); ?> All rights reserved. Made by <span class="animate-underline"><a class="animate-target text-dark-emphasis fw-medium text-decoration-none" href="https://coderthemes.com/" target="_blank" rel="noreferrer">Coderthemes</a></span></p>
        </div>
      </div>
    </footer>


    <!-- Confirmation Modal -->
    <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="confirmModalTitle">Confirmă acțiunea</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" id="confirmModalBody">
            Ești sigur că vrei să continui?
          </div>
          <div class="modal-footer flex-column flex-sm-row align-items-stretch">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulează</button>
            <button type="button" class="btn btn-primary" id="confirmModalBtn">Confirmă</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Alert Modal -->
    <div class="modal fade" id="alertModal" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="alertModalTitle">Notificare</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" id="alertModalBody">
            Mesaj
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary w-100" data-bs-dismiss="modal">OK</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Back to top button -->
    <div class="floating-buttons position-fixed top-50 end-0 z-sticky me-3 me-xl-4 pb-4">
      <a class="btn-scroll-top btn btn-sm bg-body border-0 rounded-pill shadow animate-slide-end" href="#top">
        Top
        <i class="ci-arrow-right fs-base ms-1 me-n1 animate-target"></i>
        <span class="position-absolute top-0 start-0 w-100 h-100 border rounded-pill z-0"></span>
        <svg class="position-absolute top-0 start-0 w-100 h-100 z-1" viewBox="0 0 62 32" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect x=".75" y=".75" width="60.5" height="30.5" rx="15.25" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10"/>
        </svg>
      </a>
    </div>


    <!-- Vendor scripts -->
    <script src="/assets/vendor/swiper/swiper-bundle.min.js"></script>

    <!-- Bootstrap + Theme scripts -->
    <script src="/assets/js/theme.min.js"></script>

    <!-- Cart AJAX functionality -->
    <script>
    // Modal helper functions
    function showConfirmModal(title, message, onConfirm) {
        const modal = document.getElementById('confirmModal');
        const modalTitle = document.getElementById('confirmModalTitle');
        const modalBody = document.getElementById('confirmModalBody');
        const confirmBtn = document.getElementById('confirmModalBtn');
        
        modalTitle.textContent = title;
        modalBody.textContent = message;
        
        // Remove old event listeners
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        
        // Add new event listener
        newConfirmBtn.addEventListener('click', function() {
            const bsModal = bootstrap.Modal.getInstance(modal);
            if (bsModal) bsModal.hide();
            if (onConfirm) onConfirm();
        });
        
        const bsModal = new bootstrap.Modal(modal);
        bsModal.show();
    }
    
    function showAlertModal(title, message, type = 'info') {
        const modal = document.getElementById('alertModal');
        const modalTitle = document.getElementById('alertModalTitle');
        const modalBody = document.getElementById('alertModalBody');
        const modalHeader = modal.querySelector('.modal-header');
        const modalBtn = modal.querySelector('.btn');
        
        modalTitle.textContent = title;
        modalBody.textContent = message;
        
        // Reset classes
        modalHeader.className = 'modal-header';
        modalBtn.className = 'btn w-100';
        
        // Apply type-specific styling
        if (type === 'success') {
            modalHeader.classList.add('bg-success', 'text-white');
            modalBtn.classList.add('btn-success');
        } else if (type === 'error') {
            modalHeader.classList.add('bg-danger', 'text-white');
            modalBtn.classList.add('btn-danger');
        } else if (type === 'warning') {
            modalHeader.classList.add('bg-warning');
            modalBtn.classList.add('btn-warning');
        } else {
            modalBtn.classList.add('btn-primary');
        }
        
        const bsModal = new bootstrap.Modal(modal);
        bsModal.show();
    }
    
    // Get free shipping threshold from config (via data attribute)
    const getFreeShippingThreshold = function() {
        const offcanvas = document.getElementById('shoppingCart');
        if (offcanvas && offcanvas.dataset.freeShippingThreshold) {
            return parseFloat(offcanvas.dataset.freeShippingThreshold) || 200;
        }
        return 200; // Fallback
    };
    
    // Make refreshCartOffcanvas globally available
    let refreshCartOffcanvas;
    
    // Helper function to update cart badge
    function updateCartBadge(count) {
        const cartBadge = document.querySelector('.cart-badge');
        if (count > 0) {
            if (cartBadge) {
                cartBadge.textContent = count;
                cartBadge.style.display = '';
            } else {
                // Create badge if it doesn't exist
                const cartBtn = document.querySelector('[data-bs-target="#shoppingCart"]');
                if (cartBtn) {
                    const badge = document.createElement('span');
                    badge.className = 'position-absolute top-0 start-100 mt-n1 ms-n3 badge text-bg-success border border-3 border-dark rounded-pill cart-badge';
                    badge.style.cssText = '--cz-badge-padding-y: .25em; --cz-badge-padding-x: .42em';
                    badge.textContent = count;
                    cartBtn.appendChild(badge);
                }
            }
        } else {
            if (cartBadge) cartBadge.style.display = 'none';
        }
    }
    
    // Helper function to update free shipping progress
    function updateFreeShippingProgress(cartTotal, freeShippingThreshold) {
        const offcanvasHeader = document.querySelector('#shoppingCart .offcanvas-header');
        if (!offcanvasHeader) return;
        
        const remaining = Math.max(0, freeShippingThreshold - cartTotal);
        const progress = Math.min(100, (cartTotal / freeShippingThreshold) * 100);
        
        // Get or create elements
        let freeShippingText = offcanvasHeader.querySelector('.free-shipping-text');
        let progressContainer = offcanvasHeader.querySelector('.free-shipping-progress');
        
        // If elements don't exist, create them
        if (!freeShippingText || !progressContainer) {
            // Remove any existing free shipping elements to rebuild
            const existingTexts = offcanvasHeader.querySelectorAll('p.fs-sm');
            existingTexts.forEach(el => {
                if (!el.classList.contains('free-shipping-text')) {
                    el.remove();
                }
            });
            const existingProgress = offcanvasHeader.querySelectorAll('.progress');
            existingProgress.forEach(el => {
                if (!el.classList.contains('free-shipping-progress')) {
                    el.remove();
                }
            });
            
            // Get title div
            const titleDiv = offcanvasHeader.querySelector('.d-flex.align-items-center.justify-content-between');
            if (titleDiv) {
                // Create text element
                freeShippingText = document.createElement('p');
                freeShippingText.className = 'fs-sm free-shipping-text';
                titleDiv.parentNode.insertBefore(freeShippingText, titleDiv.nextSibling);
                
                // Create progress bar
                progressContainer = document.createElement('div');
                progressContainer.className = 'progress w-100 free-shipping-progress';
                progressContainer.setAttribute('role', 'progressbar');
                progressContainer.setAttribute('aria-label', 'Progres transport gratuit');
                progressContainer.setAttribute('aria-valuemin', '0');
                progressContainer.setAttribute('aria-valuemax', '100');
                progressContainer.style.height = '4px';
                
                const progressBar = document.createElement('div');
                progressBar.className = 'progress-bar rounded-pill';
                progressContainer.appendChild(progressBar);
                
                freeShippingText.parentNode.insertBefore(progressContainer, freeShippingText.nextSibling);
            }
        }
        
        const progressBar = progressContainer ? progressContainer.querySelector('.progress-bar') : null;
        
        if (cartTotal > 0) {
            if (remaining > 0) {
                // Still need to reach threshold
                if (freeShippingText) {
                    freeShippingText.innerHTML = `Cumpără încă <span class="text-dark-emphasis fw-semibold">${remaining.toFixed(2)} RON</span> pentru <span class="text-dark-emphasis fw-semibold">Transport Gratuit</span>`;
                    freeShippingText.className = 'fs-sm free-shipping-text';
                }
                if (progressBar && progressContainer) {
                    progressBar.className = 'progress-bar bg-warning rounded-pill';
                    progressBar.style.width = progress + '%';
                    progressContainer.setAttribute('aria-valuenow', Math.round(progress));
                    progressContainer.style.display = '';
                }
            } else {
                // Threshold reached
                if (freeShippingText) {
                    freeShippingText.innerHTML = `<span class="text-dark-emphasis fw-semibold">Transport Gratuit</span> eligibil!`;
                    freeShippingText.className = 'fs-sm text-success free-shipping-text';
                }
                if (progressBar && progressContainer) {
                    progressBar.className = 'progress-bar bg-success rounded-pill';
                    progressBar.style.width = '100%';
                    progressContainer.setAttribute('aria-valuenow', '100');
                    progressContainer.style.display = '';
                }
            }
        } else {
            // Empty cart
            if (freeShippingText) {
                freeShippingText.textContent = 'Coșul tău este gol';
                freeShippingText.className = 'fs-sm free-shipping-text';
            }
            if (progressContainer) {
                progressContainer.style.display = 'none';
            }
        }
    }
    
    // Helper function to render cart items
    function renderCartItems(items) {
        const container = document.getElementById('cartItemsContainer');
        if (!container) return;
        
        if (!items || items.length === 0) {
            container.innerHTML = '<p class="text-center text-body-secondary">Coșul tău este gol</p>';
            return;
        }
        
        let html = '';
        items.forEach(item => {
            // Normalize image path
            let image = '/assets/img/shop/electronics/thumbs/01.png'; // default
            if (item.image) {
                if (item.image.startsWith('http') || item.image.startsWith('/')) {
                    image = item.image;
                } else {
                    image = '/assets/img/shop/electronics/thumbs/' + item.image;
                }
            }
            
            const unitPrice = parseFloat(item.price_at_add);
            const quantity = parseInt(item.quantity);
            const totalPrice = unitPrice * quantity;
            
            html += `
                <div class="d-flex align-items-center" data-cart-item-id="${item.id}">
                    <a class="flex-shrink-0" href="/produs/${item.slug}">
                        <img src="${image}" width="110" alt="${item.name}">
                    </a>
                    <div class="w-100 min-w-0 ps-2 ps-sm-3">
                        <h5 class="d-flex animate-underline mb-2">
                            <a class="d-block fs-sm fw-medium text-truncate animate-target" href="/produs/${item.slug}">${item.name}</a>
                        </h5>
                        <div class="h6 pb-1 mb-2" data-item-total data-unit-price="${unitPrice}">${totalPrice.toFixed(2)} RON</div>
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="count-input rounded-2">
                                <button type="button" class="btn btn-icon btn-sm cart-decrement-offcanvas" data-cart-item-id="${item.id}" aria-label="Scade cantitatea">
                                    <i class="ci-minus"></i>
                                </button>
                                <input type="number" class="form-control form-control-sm cart-quantity-offcanvas" data-cart-item-id="${item.id}" value="${quantity}" readonly>
                                <button type="button" class="btn btn-icon btn-sm cart-increment-offcanvas" data-cart-item-id="${item.id}" aria-label="Crește cantitatea">
                                    <i class="ci-plus"></i>
                                </button>
                            </div>
                            <button type="button" class="btn-close fs-sm cart-remove-offcanvas" data-cart-item-id="${item.id}" data-bs-toggle="tooltip" data-bs-custom-class="tooltip-sm" data-bs-title="Șterge" aria-label="Șterge din coș"></button>
                        </div>
                    </div>
                </div>
            `;
        });
        
        container.innerHTML = html;
    }
    
    // Cart update functionality
    document.addEventListener('DOMContentLoaded', function() {
        // Offcanvas cart - Increment quantity
        document.querySelectorAll('.cart-increment-offcanvas').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItemId = this.getAttribute('data-cart-item-id');
                const input = this.previousElementSibling;
                const quantity = parseInt(input.value) + 1;
                updateCartItemOffcanvas(cartItemId, quantity);
            });
        });

        // Offcanvas cart - Decrement quantity
        document.querySelectorAll('.cart-decrement-offcanvas').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItemId = this.getAttribute('data-cart-item-id');
                const input = this.nextElementSibling;
                const quantity = Math.max(1, parseInt(input.value) - 1);
                updateCartItemOffcanvas(cartItemId, quantity);
            });
        });

        // Offcanvas cart - Remove item
        document.querySelectorAll('.cart-remove-offcanvas').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItemId = this.getAttribute('data-cart-item-id');
                removeCartItemOffcanvas(cartItemId);
            });
        });

        // Legacy support for old data attributes
        document.querySelectorAll('[data-increment]').forEach(btn => {
            btn.addEventListener('click', function() {
                const itemId = this.getAttribute('data-item-id') || this.getAttribute('data-cart-item-id');
                const input = this.previousElementSibling || this.closest('.count-input').querySelector('input');
                const quantity = parseInt(input.value) + 1;
                updateCartItemOffcanvas(itemId, quantity);
            });
        });

        document.querySelectorAll('[data-decrement]').forEach(btn => {
            btn.addEventListener('click', function() {
                const itemId = this.getAttribute('data-item-id') || this.getAttribute('data-cart-item-id');
                const input = this.nextElementSibling || this.closest('.count-input').querySelector('input');
                const quantity = Math.max(1, parseInt(input.value) - 1);
                updateCartItemOffcanvas(itemId, quantity);
            });
        });

        document.querySelectorAll('[data-remove-item]').forEach(btn => {
            btn.addEventListener('click', function() {
                const itemId = this.getAttribute('data-item-id') || this.getAttribute('data-cart-item-id');
                removeCartItemOffcanvas(itemId);
            });
        });

        function updateCartItemOffcanvas(cartItemId, quantity) {
            // Optimistic UI update - update quantity immediately
            const itemContainer = document.querySelector(`[data-cart-item-id="${cartItemId}"]`);
            if (itemContainer) {
                const input = itemContainer.querySelector('.cart-quantity-offcanvas');
                if (input) {
                    const oldValue = input.value;
                    input.value = quantity;
                    
                    // Update item total price immediately
                    const totalPriceEl = itemContainer.querySelector('[data-item-total]');
                    if (totalPriceEl) {
                        const unitPrice = parseFloat(totalPriceEl.getAttribute('data-unit-price'));
                        const totalPrice = unitPrice * quantity;
                        totalPriceEl.textContent = totalPrice.toFixed(2) + ' RON';
                    }
                    
                    // Make API call
            fetch('/api/cart.php?action=update', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({cart_item_id: cartItemId, quantity: quantity})
            })
            .then(r => {
                if (!r.ok) {
                    throw new Error('HTTP error! status: ' + r.status);
                }
                return r.json();
            })
            .then(data => {
                if (data.success) {
                            // Refresh to get accurate totals from server
                    refreshCartOffcanvas();
                } else {
                            // Revert on failure
                            input.value = oldValue;
                    console.error('Update failed:', data.message);
                            alert('Eroare la actualizare: ' + (data.message || 'Eroare necunoscută'));
                }
            })
            .catch(err => {
                        // Revert on error
                        input.value = oldValue;
                console.error('Error:', err);
                        alert('Eroare la actualizare.');
            });
                }
            }
        }

        function removeCartItemOffcanvas(cartItemId) {
            // Optimistic UI - remove item immediately with animation
            const itemContainer = document.querySelector(`[data-cart-item-id="${cartItemId}"]`);
            if (itemContainer) {
                itemContainer.style.opacity = '0.5';
                itemContainer.style.pointerEvents = 'none';
            }
            
            fetch('/api/cart.php?action=remove', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({cart_item_id: cartItemId})
            })
            .then(r => {
                if (!r.ok) {
                    throw new Error('HTTP error! status: ' + r.status);
                }
                return r.json();
            })
            .then(data => {
                if (data.success) {
                    // Remove from DOM with animation
                    if (itemContainer) {
                        itemContainer.style.transition = 'all 0.3s ease';
                        itemContainer.style.maxHeight = '0';
                        itemContainer.style.overflow = 'hidden';
                        itemContainer.style.marginBottom = '0';
                        itemContainer.style.paddingBottom = '0';
                        setTimeout(() => {
                            refreshCartOffcanvas();
                        }, 300);
                    } else {
                    refreshCartOffcanvas();
                    }
                } else {
                    // Revert on failure
                    if (itemContainer) {
                        itemContainer.style.opacity = '1';
                        itemContainer.style.pointerEvents = '';
                    }
                    console.error('Remove failed:', data.message);
                }
            })
            .catch(err => {
                // Revert on error
                if (itemContainer) {
                    itemContainer.style.opacity = '1';
                    itemContainer.style.pointerEvents = '';
                }
                console.error('Error:', err);
            });
        }

        // Define refreshCartOffcanvas function (available globally)
        refreshCartOffcanvas = function() {
            // Fetch updated cart data
            fetch('/api/cart.php')
                .then(r => r.json())
                .then(data => {
                    if (data.success && data.cart) {
                        const freeShippingThreshold = getFreeShippingThreshold();
                        const cartTotal = parseFloat(data.cart.total) || 0;
                        const cartCount = parseInt(data.cart.count) || 0;
                        
                        // Update cart badge
                        updateCartBadge(cartCount);

                        // Update free shipping progress
                        updateFreeShippingProgress(cartTotal, freeShippingThreshold);

                        // Update subtotal
                        const cartSubtotal = document.getElementById('cartSubtotal');
                        if (cartSubtotal) {
                            cartSubtotal.textContent = cartTotal.toFixed(2) + ' RON';
                        }

                        // Update cart items
                        renderCartItems(data.cart.items);
                        
                        // Re-attach event listeners after rendering items
                        if (data.cart.items && data.cart.items.length > 0) {
                                attachOffcanvasListeners();
                        }
                    }
                })
                .catch(err => console.error('Error refreshing cart:', err));
        }

        function attachOffcanvasListeners() {
            // Re-attach increment listeners
            document.querySelectorAll('.cart-increment-offcanvas').forEach(btn => {
                btn.addEventListener('click', function() {
                    const cartItemId = this.getAttribute('data-cart-item-id');
                    const input = this.previousElementSibling;
                    const quantity = parseInt(input.value) + 1;
                    updateCartItemOffcanvas(cartItemId, quantity);
                });
            });

            // Re-attach decrement listeners
            document.querySelectorAll('.cart-decrement-offcanvas').forEach(btn => {
                btn.addEventListener('click', function() {
                    const cartItemId = this.getAttribute('data-cart-item-id');
                    const input = this.nextElementSibling;
                    const quantity = Math.max(1, parseInt(input.value) - 1);
                    updateCartItemOffcanvas(cartItemId, quantity);
                });
            });

            // Re-attach remove listeners
            document.querySelectorAll('.cart-remove-offcanvas').forEach(btn => {
                btn.addEventListener('click', function() {
                    const cartItemId = this.getAttribute('data-cart-item-id');
                    removeCartItemOffcanvas(cartItemId);
                });
            });
        }
    });
    </script>
  </body>
</html>

