<?php
// public/index.php — Sotuv (GS1 kodlar, product bo‘yicha guruhlangan savat)
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth_stub.php';

session_start();

// Foydalanuvchi (operator) ma'lumotlari – navbar va header uchun
$userName = current_user_name() ?: 'Operator';
$userRole = 'Operator';

// Mijozlar ro'yxati (sotuv uchun)
$clients = $pdo->query("SELECT id, name FROM customers WHERE is_active = 1 ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="uz">
<head>
  <meta charset="UTF-8">
  <title>Sotuv – GS1 kodlar</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap 5 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- FontAwesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
  <!-- Toastr -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">

  <style>
    :root {
      --brand-main: #0d47a1;
      --brand-soft: #e5edff;
      --brand-accent: #22c55e;
      --bg-soft: #f3f4f8;
      --card-bg: rgba(255,255,255,0.96);
      --border-soft: #d1d9e6;
      --text-main: #0b1220;
      --text-muted: #6b7280;
    }

    body {
      min-height: 100vh;
      margin: 0;
      background: radial-gradient(circle at top left, #c7d2fe 0, transparent 45%),
                  radial-gradient(circle at bottom right, #bfdbfe 0, transparent 45%),
                  #eef2ff;
      color: var(--text-main);
    }

    .page-wrapper {
      max-width: 1200px;
      margin: 0 auto;
    }

    .navbar {
      background: rgba(13,71,161,0.96);
      backdrop-filter: blur(10px);
      box-shadow: 0 10px 25px rgba(15,23,42,0.35);
    }
    .navbar-brand, .navbar-nav .nav-link, .navbar-text {
      color: #fff !important;
    }

    .navbar-nav .nav-link {
      font-size: 0.92rem;
      opacity: 0.9;
    }
    .navbar-nav .nav-link.active {
      opacity: 1;
      font-weight: 600;
      border-bottom: 2px solid #fff;
    }

    .user-chip {
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.15rem 0.75rem;
      background: rgba(15,23,42,0.2);
      border-radius: 999px;
      color: #e5edff;
      font-size: 0.85rem;
    }
    .user-avatar {
      width: 26px;
      height: 26px;
      border-radius: 999px;
      background: linear-gradient(135deg,#22c55e,#0ea5e9);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 0.9rem;
      color: #fff;
      font-weight: 700;
    }
    .user-role-badge {
      padding: 0.05rem 0.5rem;
      border-radius: 999px;
      background: rgba(15,23,42,0.35);
      font-size: 0.7rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }

    .card {
      border-radius: 18px;
      box-shadow: 0 16px 40px rgba(15,23,42,0.08);
      border: 1px solid rgba(148,163,184,0.35);
      background: var(--card-bg);
    }

    .pill-heading {
      font-size: 0.8rem;
      text-transform: uppercase;
      letter-spacing: 0.1em;
      color: var(--text-muted);
    }

    .form-label {
      font-weight: 600;
      color: var(--text-main);
    }

    .search-input {
      font-size: 1.05rem;
      padding: 0.7rem 0.9rem;
      border-radius: 12px;
    }

    .badge-pill-info {
      border-radius: 999px;
      padding: 0.15rem 0.65rem;
      font-size: 0.75rem;
      background: #e5e7eb;
      color: #4b5563;
    }

    .thumb-img {
      width: 48px;
      height: 48px;
      object-fit: cover;
      border-radius: 10px;
      border: 1px solid #e5e7eb;
      background: #fff;
      cursor: pointer;
    }

    .details-img {
      width: 240px;
      height: 240px;
      object-fit: cover;
      border-radius: 16px;
      border: 1px solid #e5e7eb;
      background: #fff;
    }

    .table thead {
      background: #eff3ff;
      font-size: 0.88rem;
    }
    .table tbody tr {
      font-size: 0.86rem;
      transition: background 0.12s ease;
    }
    .table tbody tr:hover {
      background: #f9fafb;
    }

    .loading-overlay {
      position: fixed;
      inset: 0;
      background: rgba(255,255,255,0.7);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 9999;
      backdrop-filter: blur(4px);
    }
    .loading-overlay.show {
      display: flex;
    }

    @media (max-width: 767.98px) {
      .page-wrapper {
        padding-inline: 0.4rem;
      }
    }
  </style>
</head>
<body>

<?php
  $active = 'sales'; // navbar.php ichida shunga qarab active bo‘ladi
  require __DIR__ . '/navbar.php';
?>

<!-- GLOBAL LOADING -->
<div class="loading-overlay" id="global-loading">
  <div class="text-center">
    <div class="spinner-border text-primary mb-2"></div>
    <div class="text-muted small">Iltimos, kuting...</div>
  </div>
</div>

<div class="page-wrapper">
  <div class="py-4">

    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-3 gap-2">
      <div>
        <h3 class="mb-1">Sotuv – GS1 kodlar</h3>
        <div class="text-muted">
          Mijoz tanlang, GS1 kodlarni skaner qiling, savatchada mahsulot bo‘yicha soni chiqsin va checkout qiling.
        </div>
      </div>
      
        <span class="badge bg-success-subtle text-success">
          <i class="fa-solid fa-barcode me-1"></i> Onlayn markirovka bilan uyg‘unlashgan
        </span>
      </div>
    </div>

    <!-- Mijoz + GS1 skaner CARD -->
    <div class="card mb-3">
      <div class="card-body">
        <div class="pill-heading mb-3">Mijoz va GS1 skaner</div>

        <div class="row g-3 mb-3">
          <div class="col-md-4">
            <label class="form-label" for="client-select">Mijoz</label>
            <select id="client-select" class="form-select">
              <option value="">Mijoz tanlang...</option>
              <?php foreach ($clients as $c): ?>
                <option value="<?= (int)$c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-8">
            <div class="row g-2">
              <div class="col-md-4">
                <label class="form-label">Viloyat / shahar</label>
                <input type="text" id="client-region" class="form-control form-control-sm" readonly>
              </div>
              <div class="col-md-4">
                <label class="form-label">Manzil</label>
                <input type="text" id="client-address" class="form-control form-control-sm" readonly>
              </div>
              <div class="col-md-4">
                <label class="form-label">Telefon</label>
                <input type="text" id="client-phone" class="form-control form-control-sm" readonly>
              </div>
            </div>
          </div>
        </div>

        <hr class="mb-3">

        <div class="pill-heading mb-1">GS1 / CIS kod</div>
        <div class="mb-2 text-muted small">
          Kodni skanerlang yoki qo‘l bilan kiriting, Enter yoki <strong>“Qo‘shish”</strong> tugmasini bosing.
        </div>

        <div class="row g-3 align-items-center">
          <div class="col-md-8">
            <input type="text" id="barcode-input" class="form-control search-input"
                   placeholder="GS1 / CIS kodni kiriting yoki skanerlang..."
                   autocomplete="off">
          </div>
          <div class="col-md-4 d-flex gap-2">
            <button type="button" class="btn btn-primary flex-fill" id="btn-scan">
              <i class="fa-solid fa-plus"></i> Qo‘shish
            </button>
            <button type="button" class="btn btn-outline-secondary d-none d-md-inline-flex" id="btn-refresh-cart">
              <i class="fa-solid fa-rotate"></i>
            </button>
          </div>
        </div>

      </div>
    </div>

    <!-- Savatcha CARD -->
    <div class="card">
      <div class="card-body">
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-2 gap-2">
          <div>
            <div class="pill-heading mb-1">Savatcha</div>
            <h5 class="mb-0">Sotiladigan mahsulotlar (product bo‘yicha guruhlangan)</h5>
          </div>
          <div class="d-flex flex-wrap gap-2 align-items-center">
            <span class="badge-pill-info" id="badge-items">
              0 ta kod
            </span>
            <button type="button" class="btn btn-outline-secondary btn-sm d-md-none" id="btn-refresh-cart-2">
              <i class="fa-solid fa-rotate"></i>
            </button>
          </div>
        </div>

        <div class="table-responsive mb-2">
          <table class="table table-hover align-middle" id="cart-table">
            <thead>
            <tr>
              <th>#</th>
              <th>Mahsulot</th>
              <th>Soni</th>
              <th>GS1 kod</th>
              <th>Rasm</th>
              <th>Amal</th>
            </tr>
            </thead>
            <tbody>
            <tr>
              <td colspan="6" class="text-center py-3 text-muted">
                Savatcha bo‘sh
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <div class="d-flex flex-column flex-md-row justify-content-between gap-2 align-items-md-center">
          <div class="text-muted small">
            Savatchadagi kodlar product bo‘yicha guruhlangan. <br>
            Checkoutdan so‘ng shu bloklarga mos kodlar <code>is_sale = 1</code> bo‘ladi.
          </div>
          <div class="d-flex flex-wrap gap-2">
            <button type="button" class="btn btn-outline-danger btn-sm" id="btn-clear-cart">
              <i class="fa-solid fa-trash-can"></i> Savatni tozalash
            </button>
            <button type="button" class="btn btn-success btn-sm" id="btn-checkout">
              <i class="fa-solid fa-cash-register"></i> Checkout (sotish)
            </button>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- Mahsulot rasmi preview MODAL -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Mahsulot rasmi</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center">
        <img id="modal-product-img" src="" alt="Mahsulot rasmi"
             class="details-img mb-2" style="display:none;">
        <div id="modal-product-name" class="fw-semibold"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Yopish</button>
      </div>
    </div>
  </div>
</div>

<!-- Confirm MODAL -->
<div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Tasdiqlash</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="confirm-message">
        Tasdiqlaysizmi?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Bekor qilish</button>
        <button type="button" class="btn btn-danger btn-sm" id="confirm-yes">Ha, davom et</button>
      </div>
    </div>
  </div>
</div>

<!-- JS -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
  const apiUrl = 'api.php'; // kerak bo'lsa: 'api/api.php'

  toastr.options = {
    positionClass: "toast-top-right",
    timeOut: 3000
  };

  let confirmCallback = null;
  let currentCartLength = 0; // jami kodlar soni

  function showGlobalLoading(show) {
    const el = document.getElementById('global-loading');
    if (show) el.classList.add('show');
    else      el.classList.remove('show');
  }

  // Xatolarni ko‘rsatish: server JSON dan message olib, "tarmoq xatosi" o‘rniga shu chiqsin
  function handleAjaxError(jqXHR, context) {
    let msg = '';

    if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
      msg = jqXHR.responseJSON.message;
    } else if (jqXHR.responseText) {
      try {
        const parsed = JSON.parse(jqXHR.responseText);
        if (parsed.message) {
          msg = parsed.message;
        }
      } catch (e) {
        // parse bo‘lmasa ham mayli
      }
    }

    if (!msg) {
      msg = 'Xatolik yuz berdi' + (context ? ' (' + context + ')' : '');
    }

    toastr.error(msg);
  }

  function openConfirm(message, callback) {
    confirmCallback = callback || null;
    document.getElementById('confirm-message').textContent = message;
    const m = new bootstrap.Modal(document.getElementById('confirmModal'));
    m.show();
  }

  function escapeHtml(str) {
    if (!str) return '';
    return String(str)
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }

  // Backend scan javobidan itemni olamiz (code / block / item)
  function extractScanItem(res) {
    if (res.code && typeof res.code === 'object') return res.code;
    if (res.block && typeof res.block === 'object') return res.block;
    if (res.item && typeof res.item === 'object') return res.item;
    if (res.data && typeof res.data === 'object' && !Array.isArray(res.data)) return res.data;
    return null;
  }

  // item ichidan id ni olamiz (id yoki code_id yoki block_id)
  function extractCodeId(info) {
    if (!info || typeof info !== 'object') return null;
    if (typeof info.id !== 'undefined') return info.id;
    if (typeof info.code_id !== 'undefined') return info.code_id;
    if (typeof info.block_id !== 'undefined') return info.block_id;
    return null;
  }

  // cart ni product_id bo‘yicha guruhlaymiz
  function groupCartByProduct(cart) {
    const map = {}; // product_id => group
    cart.forEach(item => {
      const pid = item.product_id || 0;
      if (!map[pid]) {
        map[pid] = {
          product_id: pid,
          product_name: item.product_name,
          product_gtin: item.product_gtin,
          product_image: item.product_image,
          quantity: 0,
          code_ids: [],
          codes: []
        };
      }
      map[pid].quantity++;
      const cid = (typeof item.code_id !== 'undefined') ? item.code_id
                : (typeof item.block_id !== 'undefined' ? item.block_id : 0);
      const codeText = (typeof item.gs1_data !== 'undefined') ? item.gs1_data
                      : (typeof item.gtin2_number !== 'undefined' ? item.gtin2_number : '');
      map[pid].code_ids.push(cid);
      map[pid].codes.push(codeText);
    });

    return Object.values(map);
  }

  $(function () {

    // Confirm "Ha"
    $('#confirm-yes').on('click', function(){
      if (confirmCallback) {
        const cb = confirmCallback;
        confirmCallback = null;
        cb();
      }
      const m = bootstrap.Modal.getInstance(document.getElementById('confirmModal'));
      if (m) m.hide();
    });

    // Mijoz tanlashda ma'lumotlarni yuklash
    $('#client-select').on('change', function(){
      const id = $(this).val();
      if (!id) {
        fillClientInfo(null);
        return;
      }
      $.getJSON(apiUrl, { action:'get_client_info', client_id:id })
        .done(function(res){
          if (res.status !== 'ok') {
            toastr.error(res.message || 'Mijoz ma’lumotida xato');
            fillClientInfo(null);
            return;
          }
          fillClientInfo(res.client);
        })
        .fail(function(jqXHR){
          handleAjaxError(jqXHR, 'get_client_info');
          fillClientInfo(null);
        });
    });

    // GS1 input – Enter
    $('#barcode-input').on('keypress', function(e){
      if (e.which === 13) {
        e.preventDefault();
        scanCode();
      }
    });

    $('#btn-scan').on('click', function(){
      scanCode();
    });

    $('#btn-refresh-cart, #btn-refresh-cart-2').on('click', function(){
      loadCart();
    });

    $('#btn-clear-cart').on('click', function(){
      if (!currentCartLength) {
        toastr.info('Savat allaqachon bo‘sh');
        return;
      }
      openConfirm('Savatni butunlay tozalashni tasdiqlaysizmi?', function(){
        $.post(apiUrl, { action:'clear_cart' }, function(res){
          if (res.status === 'ok') {
            toastr.success('Savat tozalandi');
            loadCart();
          } else {
            toastr.error(res.message || 'Savatni tozalashda xato');
          }
        }, 'json').fail(function(jqXHR){
          handleAjaxError(jqXHR, 'clear_cart');
        });
      });
    });

    // Checkout
    $('#btn-checkout').on('click', function(){
      const clientId = $('#client-select').val();
      if (!clientId) {
        toastr.warning('Avval mijozni tanlang');
        return;
      }
      if (!currentCartLength) {
        toastr.warning('Savat bo‘sh');
        return;
      }

      openConfirm('Ushbu mijozga sotuvni rasmiylashtirishni tasdiqlaysizmi?', function(){
        showGlobalLoading(true);
        $.post(apiUrl, { action:'checkout', client_id:clientId }, function(res){
          showGlobalLoading(false);
          if (res.status !== 'ok') {
            toastr.error(res.message || 'Checkout paytida xato');
            return;
          }
          toastr.success(res.message || 'Sotuv saqlandi');
          loadCart();
        }, 'json').fail(function(jqXHR){
          showGlobalLoading(false);
          handleAjaxError(jqXHR, 'checkout');
        });
      });
    });

    // Savatdagi mahsulotdan bitta kodni o‘chirish
    $(document).on('click', '.btn-remove-cart', function(){
      const codeId = $(this).data('id'); // bu block_id ham bo‘lishi mumkin
      openConfirm('Bu mahsulotdan bitta kodni savatdan o‘chirishni tasdiqlaysizmi?', function(){
        $.post(apiUrl, {
            action: 'remove_from_cart',
            code_id: codeId,
            block_id: codeId       // backend qaysinisini ishlatsa ham bo‘ladi
        }, function(res){
          if (res.status !== 'ok') {
            toastr.error(res.message || 'Kod savatdan o‘chmadi');
            return;
          }
          toastr.success('Kod savatdan o‘chirildi');
          loadCart();
        }, 'json').fail(function(jqXHR){
          handleAjaxError(jqXHR, 'remove_from_cart');
        });
      });
    });

    // Mahsulot rasmini ko‘rish
    $(document).on('click', '.thumb-img', function(){
      const src  = $(this).attr('data-full') || $(this).attr('src');
      const name = $(this).data('name') || '';
      $('#modal-product-img').attr('src', src).show();
      $('#modal-product-name').text(name);
      const m = new bootstrap.Modal(document.getElementById('imageModal'));
      m.show();
    });

    // Boshlang‘ich yuklash
    loadCart();
  });

  function fillClientInfo(client) {
    if (!client) {
      $('#client-region,#client-address,#client-phone').val('');
      return;
    }
    $('#client-region').val(
      (client.region || '') + (client.city ? (', ' + client.city) : '')
    );
    $('#client-address').val(client.address || '');
    $('#client-phone').val(client.phone || '');
  }

  function scanCode() {
    const $input = $('#barcode-input');
    const code   = $input.val().trim();
    if (!code) {
      toastr.warning('GS1 kod kiriting');
      return;
    }
    $input.val('');
    showGlobalLoading(true);

    // 1) GS1 kodni API orqali tekshiramiz
    $.post(apiUrl, { action:'scan', code:code }, function(res){
      showGlobalLoading(false);
      if (res.status !== 'ok') {
        toastr.error(res.message || 'GS1 kodni tekshirishda xato');
        return;
      }

      const info = extractScanItem(res);
      const codeId = extractCodeId(info);

      if (!info || codeId === null) {
        toastr.error('API JSON strukturasida xatolik: id/topilmadi (block_id yoki code_id)');
        console.error('SCAN RAW RESPONSE:', res);
        return;
      }

      // 2) Savatga qo‘shishga harakat qilamiz
      $.post(apiUrl, {
          action: 'add_to_cart',
          code_id: codeId,
          block_id: codeId       // backend block_id kutsa ham ishlaydi
      }, function(r2){
        if (r2.status === 'ok') {
          toastr.success('Kod savatga qo‘shildi');
          loadCart();
          return;
        }

        // Agar bu kod allaqachon savatda bo‘lsa – ochirish taklifi (toggle rejim)
        const msg = (r2.message || '').toLowerCase();
        if (msg.includes('allaqachon') && msg.includes('savat')) {
          openConfirm(
            'Bu kod allaqachon savatda. Uni savatdan o‘chirishni xohlaysizmi?',
            function () {
              $.post(apiUrl, {
                  action:'remove_from_cart',
                  code_id: codeId,
                  block_id: codeId
              }, function(rm){
                if (rm.status === 'ok') {
                  toastr.success('Kod savatdan o‘chirildi');
                  loadCart();
                } else {
                  toastr.error(rm.message || 'Kod savatdan o‘chmadi');
                }
              }, 'json').fail(function(jqXHR){
                handleAjaxError(jqXHR, 'remove_from_cart (toggle/add_to_cart)');
              });
            }
          );
          return;
        }

        // Boshqa xatolar
        toastr.error(r2.message || 'Kod savatga qo‘shilmadi');
      }, 'json').fail(function(jqXHR){
        handleAjaxError(jqXHR, 'add_to_cart');
      });

    }, 'json').fail(function(jqXHR){
      showGlobalLoading(false);

      // Bu yerda ham tekshiramiz: agar scan o‘zi "savatda allaqachon bor" desa
      let msg = '';
      if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
        msg = jqXHR.responseJSON.message;
      } else if (jqXHR.responseText) {
        try {
          const parsed = JSON.parse(jqXHR.responseText);
          if (parsed.message) msg = parsed.message;
        } catch (e) {}
      }

      const lower = (msg || '').toLowerCase();
      if (lower.includes('allaqachon') && lower.includes('savat')) {
        // Savatchadan o‘chirishni taklif qilamiz:
        openConfirm(
          'Bu kod allaqachon savatda. Uni savatdan o‘chirishni xohlaysizmi?',
          function () {
            // Avval savatni olib, aynan shu kodni topamiz (gs1_data/gtin2_number bo‘yicha)
            $.getJSON(apiUrl, { action:'get_cart' })
              .done(function(r3){
                if (r3.status !== 'ok') {
                  toastr.error(r3.message || 'Savatni olishda xato');
                  return;
                }
                const cart = r3.cart || [];
                const found = cart.find(it =>
                  (it.gs1_data || it.gtin2_number || '') === code
                );
                if (!found) {
                  toastr.error('Bu kod savatda topilmadi');
                  return;
                }

                const fId = (typeof found.code_id !== 'undefined') ? found.code_id
                           : (typeof found.block_id !== 'undefined' ? found.block_id : null);
                if (fId === null) {
                  toastr.error('Savat elementida id yo‘q (code_id/block_id)');
                  return;
                }

                $.post(apiUrl, {
                    action:'remove_from_cart',
                    code_id: fId,
                    block_id: fId
                }, function(rm){
                  if (rm.status === 'ok') {
                    toastr.success('Kod savatdan o‘chirildi');
                    loadCart();
                  } else {
                    toastr.error(rm.message || 'Kod savatdan o‘chmadi');
                  }
                }, 'json').fail(function(jqXHR2){
                  handleAjaxError(jqXHR2, 'remove_from_cart (toggle/scan)');
                });
              })
              .fail(function(jqXHR3){
                handleAjaxError(jqXHR3, 'get_cart (toggle/scan)');
              });
          }
        );
        return;
      }

      // Oddiy boshqa xato
      handleAjaxError(jqXHR, 'scan');
    });
  }

  function loadCart() {
    $.getJSON(apiUrl, { action:'get_cart' })
      .done(function(res){
        if (res.status !== 'ok') {
          toastr.error(res.message || 'Savatni olishda xato');
          return;
        }
        const cart = res.cart || [];
        currentCartLength = cart.length;

        // Product bo‘yicha guruhlaymiz
        const groups = groupCartByProduct(cart);

        // Badge – jami kodlar
        $('#badge-items').text(
          `${groups.length} ta mahsulot, ${cart.length} ta kod`
        );

        const $tb = $('#cart-table tbody');
        $tb.empty();

        if (!groups.length) {
          $tb.append(
            '<tr><td colspan="6" class="text-center py-3 text-muted">Savatcha bo‘sh</td></tr>'
          );
          return;
        }

        groups.forEach(function(g, idx){
          const imgFile = g.product_image || '';
          let imgHtml   = '<span class="text-muted small">Yo‘q</span>';
          if (imgFile) {
            const src = '/mark2/' + imgFile;
            imgHtml = `
              <img src="${src}" data-full="${src}"
                   data-name="${escapeHtml(g.product_name || '')}"
                   class="thumb-img" alt="rasm">
            `;
          }

          // GS1 ustunida birinchi kodni ko‘rsatib, nechta kod borligini yozamiz
          const firstCode = g.codes[0] || '';
          const gs1Html = `
            <div><code>${escapeHtml(firstCode)}</code></div>
            <div class="small text-muted">${g.quantity} ta kod</div>
          `;

          // Delete tugmasi bir dona kodni (oxirgi) o‘chiradi
          const lastCodeId = g.code_ids[g.code_ids.length - 1];

          const row = `
            <tr>
              <td>${idx+1}</td>
              <td>
                <div class="fw-semibold">${escapeHtml(g.product_name || '')}</div>
                <div class="small text-muted">
                  GTIN: ${escapeHtml(g.product_gtin || '-')}
                </div>
              </td>
              <td>${g.quantity}</td>
              <td>${gs1Html}</td>
              <td>${imgHtml}</td>
              <td>
                <button class="btn btn-sm btn-outline-danger btn-remove-cart" data-id="${lastCodeId}">
                  <i class="fa-solid fa-xmark"></i>
                </button>
              </td>
            </tr>
          `;
          $tb.append(row);
        });

      })
      .fail(function(jqXHR){
        handleAjaxError(jqXHR, 'get_cart');
      });
  }
</script>

</body>
</html>
