<?php
/**
 * Shopping Cart Page
 * Converted from checkout-v1-cart.html
 * Displays cart items and order summary
 */

$pageTitle = 'Cartzilla | Coș de Cumpărături';
$pageDescription = 'Cartzilla - Magazin Online E-Commerce';

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/product-card-helper.php';

// Initialize classes
$cart = new Cart();
$product = new Product();
$user = new User();
$order = new Order();
$auth = new Auth();

// Get user ID and session ID
$userId = $auth->getUserId();
$sessionId = session_id();

// Get or create cart
$cartData = $cart->getOrCreateCart($userId, $sessionId);
$cartId = $cartData['id'];

// Get cart items
$cartItems = $cart->getCartItems($cartId);

// Get user B2B group for pricing
$b2bGroup = $userId ? $user->getB2BGroup($userId) : null;

// Calculate totals
$subtotal = 0;
$savings = 0;
$itemCount = 0;

foreach ($cartItems as $key => $item) {
    $productData = $product->getProductById($item['product_id']);
    if ($productData) {
        // Get current price (with B2B discount)
        $currentPrice = $product->getProductPrice($productData, $b2bGroup, $userId);
        $originalPrice = $productData['sale_price'] ?? $productData['price'];
        
        // Calculate savings (difference between original and current price)
        if ($originalPrice > $currentPrice) {
            $savings += ($originalPrice - $currentPrice) * $item['quantity'];
        }
        
        $cartItems[$key]['current_price'] = $currentPrice;
        $cartItems[$key]['original_price'] = $originalPrice;
        $cartItems[$key]['product_data'] = $productData;
        $cartItems[$key]['item_total'] = $currentPrice * $item['quantity'];
        $subtotal += $currentPrice * $item['quantity'];
        $itemCount += $item['quantity'];
        
        // Get product image
        $cartItems[$key]['image'] = $productData['image'] ?? 'assets/img/shop/electronics/thumbs/01.png';
        if (!str_starts_with($cartItems[$key]['image'], 'http') && !str_starts_with($cartItems[$key]['image'], '/') && !str_starts_with($cartItems[$key]['image'], 'assets/')) {
            $cartItems[$key]['image'] = 'assets/img/shop/electronics/thumbs/' . $cartItems[$key]['image'];
        }
    }
}

// Tax (19% VAT for Romania)
$taxRate = 0.19;
$tax = $subtotal * $taxRate;

// Shipping (calculated at checkout)
$shipping = 0;
$estimatedTotal = $subtotal + $tax + $shipping;

// Free shipping threshold from config
$freeShippingThreshold = defined('FREE_SHIPPING_THRESHOLD') ? FREE_SHIPPING_THRESHOLD : 200;
$freeShippingProgress = min(100, ($subtotal / $freeShippingThreshold) * 100);
$remainingForFreeShipping = max(0, $freeShippingThreshold - $subtotal);

// Get featured products for "Trending products" section
$featuredProducts = $product->getFeaturedProducts(4);
?>

    <!-- Page content -->
    <main class="content-wrapper">

      <!-- Breadcrumb -->
      <nav class="container pt-3 my-3 my-md-4" aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="/">Acasă</a></li>
          <li class="breadcrumb-item"><a href="/catalog">Magazin</a></li>
          <li class="breadcrumb-item active" aria-current="page">Coș</li>
        </ol>
      </nav>


      <!-- Items in the cart + Order summary -->
      <section class="container pb-5 mb-2 mb-md-3 mb-lg-4 mb-xl-5">
        <h1 class="h3 mb-4">Coș de cumpărături</h1>
        <div class="row">

          <!-- Items list -->
          <div class="col-lg-8">
            <div class="pe-lg-2 pe-xl-3 me-xl-3">
              <?php if ($remainingForFreeShipping > 0): ?>
              <p class="fs-sm">Cumpără încă <span class="text-dark-emphasis fw-semibold"><?php echo number_format($remainingForFreeShipping, 2); ?> RON</span> pentru <span class="text-dark-emphasis fw-semibold">Transport Gratuit</span></p>
              <div class="progress w-100 overflow-visible mb-4" role="progressbar" aria-label="Free shipping progress" aria-valuenow="<?php echo $freeShippingProgress; ?>" aria-valuemin="0" aria-valuemax="100" style="height: 4px">
                <div class="progress-bar bg-warning rounded-pill position-relative overflow-visible" style="width: <?php echo $freeShippingProgress; ?>%; height: 4px">
                  <div class="position-absolute top-50 end-0 d-flex align-items-center justify-content-center translate-middle-y bg-body border border-warning rounded-circle me-n1" style="width: 1.5rem; height: 1.5rem">
                    <i class="ci-star-filled text-warning"></i>
                  </div>
                </div>
              </div>
              <?php else: ?>
              <p class="fs-sm text-success"><span class="text-dark-emphasis fw-semibold">Transport Gratuit</span> eligibil!</p>
              <div class="progress w-100 overflow-visible mb-4" role="progressbar" aria-label="Free shipping progress" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="height: 4px">
                <div class="progress-bar bg-success rounded-pill position-relative overflow-visible" style="width: 100%; height: 4px">
                  <div class="position-absolute top-50 end-0 d-flex align-items-center justify-content-center translate-middle-y bg-body border border-success rounded-circle me-n1" style="width: 1.5rem; height: 1.5rem">
                    <i class="ci-check text-success"></i>
                  </div>
                </div>
              </div>
              <?php endif; ?>

              <?php if (empty($cartItems)): ?>
              <!-- Empty cart -->
              <div class="text-center py-5">
                <i class="ci-shopping-cart fs-1 text-body-secondary mb-3"></i>
                <h3 class="h5 mb-2">Coșul tău este gol</h3>
                <p class="text-body-secondary mb-4">Începe să cumperi pentru a adăuga produse în coș.</p>
                <a class="btn btn-primary" href="/catalog">
                  Continuă cumpărăturile
                  <i class="ci-arrow-right fs-base ms-1 me-n1"></i>
                </a>
              </div>
              <?php else: ?>
              <!-- Table of items -->
              <table class="table position-relative z-2 mb-4">
                <thead>
                  <tr>
                    <th scope="col" class="fs-sm fw-normal py-3 ps-0"><span class="text-body">Produs</span></th>
                    <th scope="col" class="text-body fs-sm fw-normal py-3 d-none d-xl-table-cell"><span class="text-body">Preț</span></th>
                    <th scope="col" class="text-body fs-sm fw-normal py-3 d-none d-md-table-cell"><span class="text-body">Cantitate</span></th>
                    <th scope="col" class="text-body fs-sm fw-normal py-3 d-none d-md-table-cell"><span class="text-body">Total</span></th>
                    <th scope="col" class="py-0 px-0">
                      <div class="nav justify-content-end">
                        <button type="button" class="nav-link d-inline-block text-decoration-underline text-nowrap py-3 px-0 clear-cart-btn">Golește coșul</button>
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody class="align-middle">
                  <?php foreach ($cartItems as $item): ?>
                  <!-- Item -->
                  <tr data-cart-item-id="<?php echo $item['id']; ?>">
                    <td class="py-3 ps-0">
                      <div class="d-flex align-items-center">
                        <a class="flex-shrink-0" href="/produs/<?php echo htmlspecialchars($item['slug']); ?>">
                          <?php if ($item['original_price'] > $item['current_price']): ?>
                          <span class="badge text-bg-danger position-absolute top-0 start-0">-<?php echo round((($item['original_price'] - $item['current_price']) / $item['original_price']) * 100); ?>%</span>
                          <?php endif; ?>
                          <img src="<?php echo htmlspecialchars($item['image']); ?>" width="110" alt="<?php echo htmlspecialchars($item['name']); ?>">
                        </a>
                        <div class="w-100 min-w-0 ps-2 ps-xl-3">
                          <h5 class="d-flex animate-underline mb-2">
                            <a class="d-block fs-sm fw-medium text-truncate animate-target" href="/produs/<?php echo htmlspecialchars($item['slug']); ?>"><?php echo htmlspecialchars($item['name']); ?></a>
                          </h5>
                          <ul class="list-unstyled gap-1 fs-xs mb-0">
                            <?php if (!empty($item['product_data']['sku'])): ?>
                            <li><span class="text-body-secondary">SKU:</span> <span class="text-dark-emphasis fw-medium"><?php echo htmlspecialchars($item['product_data']['sku']); ?></span></li>
                            <?php endif; ?>
                            <li class="d-xl-none"><span class="text-body-secondary">Preț:</span> <span class="text-dark-emphasis fw-medium"><?php echo number_format($item['current_price'], 2); ?> RON<?php if ($item['original_price'] > $item['current_price']): ?> <del class="text-body-tertiary fw-normal"><?php echo number_format($item['original_price'], 2); ?> RON</del><?php endif; ?></span></li>
                          </ul>
                          <div class="count-input rounded-2 d-md-none mt-3">
                            <button type="button" class="btn btn-sm btn-icon cart-decrement" data-cart-item-id="<?php echo $item['id']; ?>" aria-label="Scade cantitatea">
                              <i class="ci-minus"></i>
                            </button>
                            <input type="number" class="form-control form-control-sm cart-quantity" data-cart-item-id="<?php echo $item['id']; ?>" value="<?php echo $item['quantity']; ?>" readonly>
                            <button type="button" class="btn btn-sm btn-icon cart-increment" data-cart-item-id="<?php echo $item['id']; ?>" aria-label="Crește cantitatea">
                              <i class="ci-plus"></i>
                            </button>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td class="h6 py-3 d-none d-xl-table-cell">
                      <?php echo number_format($item['current_price'], 2); ?> RON
                      <?php if ($item['original_price'] > $item['current_price']): ?>
                      <del class="text-body-tertiary fs-xs fw-normal"><?php echo number_format($item['original_price'], 2); ?> RON</del>
                      <?php endif; ?>
                    </td>
                    <td class="py-3 d-none d-md-table-cell">
                      <div class="count-input">
                        <button type="button" class="btn btn-icon cart-decrement" data-cart-item-id="<?php echo $item['id']; ?>" aria-label="Scade cantitatea">
                          <i class="ci-minus"></i>
                        </button>
                        <input type="number" class="form-control cart-quantity" data-cart-item-id="<?php echo $item['id']; ?>" value="<?php echo $item['quantity']; ?>" readonly>
                        <button type="button" class="btn btn-icon cart-increment" data-cart-item-id="<?php echo $item['id']; ?>" aria-label="Crește cantitatea">
                          <i class="ci-plus"></i>
                        </button>
                      </div>
                    </td>
                    <td class="h6 py-3 d-none d-md-table-cell"><?php echo number_format($item['item_total'], 2); ?> RON</td>
                    <td class="text-end py-3 px-0">
                      <button type="button" class="btn-close fs-sm cart-remove" data-cart-item-id="<?php echo $item['id']; ?>" data-bs-toggle="tooltip" data-bs-custom-class="tooltip-sm" data-bs-title="Șterge" aria-label="Șterge din coș"></button>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>

              <div class="nav position-relative z-2 mb-4 mb-lg-0">
                <a class="nav-link animate-underline px-0" href="/catalog">
                  <i class="ci-chevron-left fs-lg me-1"></i>
                  <span class="animate-target">Continuă cumpărăturile</span>
                </a>
              </div>
              <?php endif; ?>
            </div>
          </div>


          <!-- Order summary (sticky sidebar) -->
          <aside class="col-lg-4" style="margin-top: -100px">
            <div class="position-sticky top-0" style="padding-top: 100px">
              <div class="bg-body-tertiary rounded-5 p-4 mb-3">
                <div class="p-sm-2 p-lg-0 p-xl-2">
                  <h5 class="border-bottom pb-4 mb-4">Rezumat comandă</h5>
                  <?php if (!empty($cartItems)): ?>
                  <ul class="list-unstyled fs-sm gap-3 mb-0">
                    <li class="d-flex justify-content-between">
                      Subtotal (<?php echo $itemCount; ?> <?php echo $itemCount == 1 ? 'articol' : 'articole'; ?>):
                      <span class="text-dark-emphasis fw-medium"><?php echo number_format($subtotal, 2); ?> RON</span>
                    </li>
                    <?php if ($savings > 0): ?>
                    <li class="d-flex justify-content-between">
                      Economii:
                      <span class="text-danger fw-medium">-<?php echo number_format($savings, 2); ?> RON</span>
                    </li>
                    <?php endif; ?>
                    <li class="d-flex justify-content-between">
                      TVA (19%):
                      <span class="text-dark-emphasis fw-medium"><?php echo number_format($tax, 2); ?> RON</span>
                    </li>
                    <li class="d-flex justify-content-between">
                      Transport:
                      <span class="text-dark-emphasis fw-medium">Calculat la finalizare</span>
                    </li>
                  </ul>
                  <div class="border-top pt-4 mt-4">
                    <div class="d-flex justify-content-between mb-3">
                      <span class="fs-sm">Total estimat:</span>
                      <span class="h5 mb-0"><?php echo number_format($estimatedTotal, 2); ?> RON</span>
                    </div>
                    <a class="btn btn-lg btn-primary w-100" href="/checkout/livrare">
                      Finalizează comanda
                      <i class="ci-chevron-right fs-lg ms-1 me-n1"></i>
                    </a>
                    <?php if (!$userId): ?>
                    <div class="nav justify-content-center fs-sm mt-3">
                      <a class="nav-link text-decoration-underline p-0 me-1" href="/cont/inregistrare">Creează un cont</a>
                      și primește
                      <span class="text-dark-emphasis fw-medium ms-1"><?php echo round($estimatedTotal); ?> bonusuri</span>
                    </div>
                    <?php endif; ?>
                  </div>
                  <?php else: ?>
                  <p class="text-body-secondary text-center py-4">Coșul tău este gol</p>
                  <?php endif; ?>
                </div>
              </div>
              <div class="accordion bg-body-tertiary rounded-5 p-4">
                <div class="accordion-item border-0">
                  <h3 class="accordion-header" id="promoCodeHeading">
                    <button type="button" class="accordion-button animate-underline collapsed py-0 ps-sm-2 ps-lg-0 ps-xl-2" data-bs-toggle="collapse" data-bs-target="#promoCode" aria-expanded="false" aria-controls="promoCode">
                      <i class="ci-percent fs-xl me-2"></i>
                      <span class="animate-target me-2">Aplică cod promoțional</span>
                    </button>
                  </h3>
                  <div class="accordion-collapse collapse" id="promoCode" aria-labelledby="promoCodeHeading">
                    <div class="accordion-body pt-3 pb-2 ps-sm-2 px-lg-0 px-xl-2">
                      <form class="needs-validation d-flex gap-2" id="promoCodeForm" novalidate>
                        <div class="position-relative w-100">
                          <input type="text" class="form-control" name="coupon_code" placeholder="Introdu codul promoțional" required>
                          <div class="invalid-tooltip bg-transparent py-0">Introdu un cod promoțional valid!</div>
                        </div>
                        <button type="submit" class="btn btn-dark">Aplică</button>
                      </form>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </aside>
        </div>
      </section>


      <!-- Trending products (Carousel) -->
      <?php if (!empty($featuredProducts)): ?>
      <section class="container pb-4 pb-md-5 mb-2 mb-sm-0 mb-lg-2 mb-xl-4">
        <h2 class="h3 border-bottom pb-4 mb-0">Produse populare</h2>

        <!-- Product carousel -->
        <div class="position-relative mx-md-1">

          <!-- External slider prev/next buttons visible on screens > 500px wide (sm breakpoint) -->
          <button type="button" class="trending-prev btn btn-prev btn-icon btn-outline-secondary bg-body rounded-circle animate-slide-start position-absolute top-50 start-0 z-2 translate-middle-y ms-n1 d-none d-sm-inline-flex" aria-label="Prev">
            <i class="ci-chevron-left fs-lg animate-target"></i>
          </button>
          <button type="button" class="trending-next btn btn-next btn-icon btn-outline-secondary bg-body rounded-circle animate-slide-end position-absolute top-50 end-0 z-2 translate-middle-y me-n1 d-none d-sm-inline-flex" aria-label="Next">
            <i class="ci-chevron-right fs-lg animate-target"></i>
          </button>

          <!-- Slider -->
          <div class="swiper py-4 px-sm-3" data-swiper='{
            "slidesPerView": 2,
            "spaceBetween": 24,
            "loop": true,
            "navigation": {
              "prevEl": ".trending-prev",
              "nextEl": ".trending-next"
            },
            "breakpoints": {
              "768": {
                "slidesPerView": 3
              },
              "992": {
                "slidesPerView": 4
              }
            }
          }'>
            <div class="swiper-wrapper">

              <?php foreach ($featuredProducts as $featuredProduct): ?>
              <div class="swiper-slide">
                <?php echo renderProductCard($featuredProduct, $b2bGroup); ?>
              </div>
              <?php endforeach; ?>

            </div>
          </div>
        </div>
      </section>
      <?php endif; ?>

    </main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const FREE_SHIPPING_THRESHOLD = <?php echo $freeShippingThreshold; ?>;
    const TAX_RATE = 0.19;
    
    // Helper function to format currency
    function formatCurrency(amount) {
        return parseFloat(amount).toFixed(2) + ' RON';
    }
    
    // Helper function to update free shipping progress
    function updateFreeShippingProgress(subtotal) {
        const remaining = Math.max(0, FREE_SHIPPING_THRESHOLD - subtotal);
        const progress = Math.min(100, (subtotal / FREE_SHIPPING_THRESHOLD) * 100);
        
        const progressSection = document.querySelector('.col-lg-8 .pe-lg-2');
        if (!progressSection) return;
        
        let progressHTML = '';
        if (remaining > 0) {
            progressHTML = `
                <p class="fs-sm">Cumpără încă <span class="text-dark-emphasis fw-semibold">${formatCurrency(remaining)}</span> pentru <span class="text-dark-emphasis fw-semibold">Transport Gratuit</span></p>
                <div class="progress w-100 overflow-visible mb-4" role="progressbar" aria-label="Free shipping progress" aria-valuenow="${Math.round(progress)}" aria-valuemin="0" aria-valuemax="100" style="height: 4px">
                    <div class="progress-bar bg-warning rounded-pill position-relative overflow-visible" style="width: ${progress}%; height: 4px">
                        <div class="position-absolute top-50 end-0 d-flex align-items-center justify-content-center translate-middle-y bg-body border border-warning rounded-circle me-n1" style="width: 1.5rem; height: 1.5rem">
                            <i class="ci-star-filled text-warning"></i>
                        </div>
                    </div>
                </div>
            `;
        } else {
            progressHTML = `
                <p class="fs-sm text-success"><span class="text-dark-emphasis fw-semibold">Transport Gratuit</span> eligibil!</p>
                <div class="progress w-100 overflow-visible mb-4" role="progressbar" aria-label="Free shipping progress" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="height: 4px">
                    <div class="progress-bar bg-success rounded-pill position-relative overflow-visible" style="width: 100%; height: 4px">
                        <div class="position-absolute top-50 end-0 d-flex align-items-center justify-content-center translate-middle-y bg-body border border-success rounded-circle me-n1" style="width: 1.5rem; height: 1.5rem">
                            <i class="ci-check text-success"></i>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // Update or create progress section
        let existingProgress = progressSection.querySelector('.fs-sm');
        if (existingProgress && existingProgress.parentNode === progressSection) {
            // Replace both p and progress
            let nextEl = existingProgress.nextElementSibling;
            existingProgress.remove();
            if (nextEl && nextEl.classList.contains('progress')) {
                nextEl.remove();
            }
            progressSection.insertAdjacentHTML('afterbegin', progressHTML);
        } else {
            progressSection.insertAdjacentHTML('afterbegin', progressHTML);
        }
    }
    
    // Helper function to render cart items table
    function renderCartItems(items, calculations) {
        const tbody = document.querySelector('table.table tbody');
        if (!tbody) return;
        
        if (!items || items.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center py-5">
                        <i class="ci-shopping-cart fs-1 text-body-secondary mb-3 d-block"></i>
                        <h3 class="h5 mb-2">Coșul tău este gol</h3>
                        <p class="text-body-secondary mb-4">Începe să cumperi pentru a adăuga produse în coș.</p>
                        <a class="btn btn-primary" href="/catalog">
                            Continuă cumpărăturile
                            <i class="ci-arrow-right fs-base ms-1 me-n1"></i>
                        </a>
                    </td>
                </tr>
            `;
            return;
        }
        
        let html = '';
        items.forEach(item => {
            const currentPrice = parseFloat(item.current_price || item.price_at_add);
            const originalPrice = parseFloat(item.original_price || currentPrice);
            const itemTotal = currentPrice * item.quantity;
            const hasDiscount = originalPrice > currentPrice;
            const discountPercent = hasDiscount ? Math.round(((originalPrice - currentPrice) / originalPrice) * 100) : 0;
            
            html += `
                <tr data-cart-item-id="${item.id}">
                    <td class="py-3 ps-0">
                        <div class="d-flex align-items-center">
                            <a class="flex-shrink-0 position-relative" href="/produs/${item.slug}">
                                ${hasDiscount ? `<span class="badge text-bg-danger position-absolute top-0 start-0">-${discountPercent}%</span>` : ''}
                                <img src="${item.image}" width="110" alt="${item.name}">
                            </a>
                            <div class="w-100 min-w-0 ps-2 ps-xl-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>
                                <ul class="list-unstyled gap-1 fs-xs mb-0">
                                    ${item.sku ? `<li><span class="text-body-secondary">SKU:</span> <span class="text-dark-emphasis fw-medium">${item.sku}</span></li>` : ''}
                                    <li class="d-xl-none"><span class="text-body-secondary">Preț:</span> <span class="text-dark-emphasis fw-medium">${formatCurrency(currentPrice)}${hasDiscount ? ` <del class="text-body-tertiary fw-normal">${formatCurrency(originalPrice)}</del>` : ''}</span></li>
                                </ul>
                                <div class="count-input rounded-2 d-md-none mt-3">
                                    <button type="button" class="btn btn-sm btn-icon cart-decrement" 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" data-cart-item-id="${item.id}" value="${item.quantity}" readonly>
                                    <button type="button" class="btn btn-sm btn-icon cart-increment" data-cart-item-id="${item.id}" aria-label="Crește cantitatea">
                                        <i class="ci-plus"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </td>
                    <td class="h6 py-3 d-none d-xl-table-cell">
                        ${formatCurrency(currentPrice)}
                        ${hasDiscount ? `<del class="text-body-tertiary fs-xs fw-normal">${formatCurrency(originalPrice)}</del>` : ''}
                    </td>
                    <td class="py-3 d-none d-md-table-cell">
                        <div class="count-input">
                            <button type="button" class="btn btn-icon cart-decrement" data-cart-item-id="${item.id}" aria-label="Scade cantitatea">
                                <i class="ci-minus"></i>
                            </button>
                            <input type="number" class="form-control cart-quantity" data-cart-item-id="${item.id}" value="${item.quantity}" readonly>
                            <button type="button" class="btn btn-icon cart-increment" data-cart-item-id="${item.id}" aria-label="Crește cantitatea">
                                <i class="ci-plus"></i>
                            </button>
                        </div>
                    </td>
                    <td class="h6 py-3 d-none d-md-table-cell">${formatCurrency(itemTotal)}</td>
                    <td class="text-end py-3 px-0">
                        <button type="button" class="btn-close fs-sm cart-remove" 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>
                    </td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
        attachCartEventListeners();
    }
    
    // Helper function to update order summary
    function updateOrderSummary(calculations) {
        const summaryList = document.querySelector('.bg-body-tertiary.rounded-5 ul.list-unstyled');
        if (!summaryList) return;
        
        const itemText = calculations.itemCount === 1 ? 'articol' : 'articole';
        
        let html = `
            <li class="d-flex justify-content-between">
                Subtotal (${calculations.itemCount} ${itemText}):
                <span class="text-dark-emphasis fw-medium">${formatCurrency(calculations.subtotal)}</span>
            </li>
        `;
        
        if (calculations.savings > 0) {
            html += `
                <li class="d-flex justify-content-between">
                    Economii:
                    <span class="text-danger fw-medium">-${formatCurrency(calculations.savings)}</span>
                </li>
            `;
        }
        
        html += `
            <li class="d-flex justify-content-between">
                TVA (19%):
                <span class="text-dark-emphasis fw-medium">${formatCurrency(calculations.tax)}</span>
            </li>
            <li class="d-flex justify-content-between">
                Transport:
                <span class="text-dark-emphasis fw-medium">Calculat la finalizare</span>
            </li>
        `;
        
        summaryList.innerHTML = html;
        
        // Update total
        const totalSpan = document.querySelector('.border-top .h5');
        if (totalSpan) {
            totalSpan.textContent = formatCurrency(calculations.estimatedTotal);
        }
    }
    
    // Attach event listeners to cart buttons
    function attachCartEventListeners() {
        // Update quantity
        document.querySelectorAll('.cart-increment, .cart-decrement').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItemId = this.getAttribute('data-cart-item-id');
                if (!cartItemId) return;
                
                const isIncrement = this.classList.contains('cart-increment');
                const row = this.closest('tr');
                const input = row ? row.querySelector('.cart-quantity') : null;
                if (!input) return;
                
                const currentQty = parseInt(input.value) || 1;
                const newQty = isIncrement ? currentQty + 1 : Math.max(1, currentQty - 1);
                
                updateCartItem(cartItemId, newQty);
            });
        });
        
        // Remove item
        document.querySelectorAll('.cart-remove').forEach(btn => {
            btn.addEventListener('click', function() {
                const cartItemId = this.getAttribute('data-cart-item-id');
                if (cartItemId) removeCartItem(cartItemId);
            });
        });
        
        // Clear cart button (re-attach on every render)
        const clearCartBtn = document.querySelector('.clear-cart-btn');
        if (clearCartBtn) {
            // Remove old listener by cloning
            const newClearBtn = clearCartBtn.cloneNode(true);
            clearCartBtn.parentNode.replaceChild(newClearBtn, clearCartBtn);
            
            // Attach new listener
            newClearBtn.addEventListener('click', function() {
                showConfirmModal(
                    'Golește coșul',
                    'Ești sigur că vrei să golești coșul? Această acțiune nu poate fi anulată.',
                    function() {
                        fetch('/api/cart.php?action=clear', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({}) // Trimite body gol
                        })
                        .then(r => r.json())
                        .then(data => {
                            if (data.success) {
                                refreshCartPage();
                                showAlertModal('Succes', 'Coșul a fost golit cu succes!', 'success');
                            } else {
                                showAlertModal('Eroare', 'Eroare la golirea coșului: ' + (data.message || 'Eroare necunoscută'), 'error');
                            }
                        })
                        .catch(err => {
                            console.error('Error clearing cart:', err);
                            showAlertModal('Eroare', 'A apărut o eroare la golirea coșului. Te rugăm să încerci din nou.', 'error');
                        });
                    }
                );
            });
        }
    }
    
    // Initial event listeners
    attachCartEventListeners();
    
    // Apply promo code
    const promoForm = document.getElementById('promoCodeForm');
    if (promoForm) {
        promoForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const couponCode = formData.get('coupon_code');
            
            if (!couponCode || couponCode.trim() === '') {
                showAlertModal('Atenție', 'Te rugăm să introduci un cod promoțional.', 'warning');
                return;
            }
            
            fetch('/api/coupons.php?action=validate', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({code: couponCode})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlertModal('Succes', 'Cod promoțional aplicat cu succes!', 'success');
                    refreshCartPage();
                } else {
                    showAlertModal('Eroare', data.message || 'Cod promoțional invalid', 'error');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showAlertModal('Eroare', 'A apărut o eroare la validarea codului promoțional.', 'error');
            });
        });
    }
    
    function updateCartItem(cartItemId, quantity) {
        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) {
                refreshCartPage();
            } else {
                console.error('Update failed:', data.message);
                showAlertModal('Eroare', 'Eroare la actualizare: ' + (data.message || 'Eroare necunoscută'), 'error');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showAlertModal('Eroare', 'A apărut o eroare la actualizarea coșului.', 'error');
        });
    }
    
    function removeCartItem(cartItemId) {
        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) {
                refreshCartPage();
            } else {
                console.error('Remove failed:', data.message);
            }
        })
        .catch(err => {
            console.error('Error:', err);
        });
    }

    function refreshCartPage() {
        // Fetch updated cart data from backend with full calculations
        fetch('/api/cart.php?action=get_full')
            .then(r => r.json())
            .then(data => {
                if (data.success && data.cart) {
                    const calculations = data.calculations || {
                        subtotal: data.cart.total || 0,
                        itemCount: data.cart.count || 0,
                        savings: 0,
                        tax: (data.cart.total || 0) * TAX_RATE,
                        estimatedTotal: (data.cart.total || 0) * (1 + TAX_RATE)
                    };
                    
                    // Update offcanvas cart if function exists
                    if (typeof refreshCartOffcanvas === 'function') {
                        refreshCartOffcanvas();
                    }
                    
                    // Update cart badge in header
                    const cartBadge = document.querySelector('.cart-badge');
                    if (data.cart.count > 0) {
                        if (cartBadge) {
                            cartBadge.textContent = data.cart.count;
                            cartBadge.style.display = '';
                        }
                    } else {
                        if (cartBadge) cartBadge.style.display = 'none';
                    }
                    
                    // Update free shipping progress
                    updateFreeShippingProgress(calculations.subtotal);
                    
                    // Update cart items table
                    renderCartItems(data.cart.items, calculations);
                    
                    // Update order summary
                    updateOrderSummary(calculations);
                    
                    // Show/hide empty state vs items
                    const tableContainer = document.querySelector('.col-lg-8 .pe-lg-2');
                    const emptyState = tableContainer ? tableContainer.querySelector('.text-center.py-5') : null;
                    const table = tableContainer ? tableContainer.querySelector('table.table') : null;
                    
                    if (data.cart.items && data.cart.items.length > 0) {
                        if (emptyState) emptyState.remove();
                        if (table) table.style.display = '';
                    } else {
                        if (table) table.style.display = 'none';
                        if (!emptyState && tableContainer) {
                            const continueBtn = tableContainer.querySelector('.nav.position-relative');
                            if (continueBtn) {
                                continueBtn.insertAdjacentHTML('beforebegin', `
                                    <div class="text-center py-5">
                                        <i class="ci-shopping-cart fs-1 text-body-secondary mb-3 d-block"></i>
                                        <h3 class="h5 mb-2">Coșul tău este gol</h3>
                                        <p class="text-body-secondary mb-4">Începe să cumperi pentru a adăuga produse în coș.</p>
                                        <a class="btn btn-primary" href="/catalog">
                                            Continuă cumpărăturile
                                            <i class="ci-arrow-right fs-base ms-1 me-n1"></i>
                                        </a>
                                    </div>
                                `);
                            }
                        }
                    }
                }
            })
            .catch(err => {
                console.error('Error refreshing cart:', err);
            });
    }
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>

