<?php
// marking.php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth_stub.php';

session_start();
$userName = current_user_name() ?: 'Operator';

// Kategoriyalarni oldindan yuklab qo‘yamiz
$stmt = $pdo->query("SELECT id, name, image_path FROM categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="uz">
<head>
  <meta charset="UTF-8">
  <title>Markirovka – Mineral Suv</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: 1320px;
      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.25rem 0.8rem;
      background: rgba(15,23,42,0.12);
      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);
    }

    .stat-card {
      position: relative;
      overflow: hidden;
      border: none;
      background: radial-gradient(circle at top left, #e0ecff 0, #ffffff 45%);
    }
    .stat-card::before {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: inherit;
      border: 2px solid transparent;
      background: linear-gradient(120deg, rgba(37,99,235,0.7), rgba(56,189,248,0.6));
      -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
      -webkit-mask-composite: xor;
      mask-composite: exclude;
      padding: 1px;
      opacity: 0.6;
    }
    .stat-icon {
      width: 36px;
      height: 36px;
      border-radius: 999px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: rgba(37,99,235,0.07);
      color: #1d4ed8;
      margin-bottom: 0.5rem;
    }
    .stat-label {
      color: var(--text-muted);
      font-size: 0.9rem;
    }
    .stat-value {
      font-size: 1.8rem;
      font-weight: 700;
    }

    .clock-pill {
      display: inline-flex;
      align-items: center;
      gap: 0.35rem;
      padding: 0.25rem 0.7rem;
      border-radius: 999px;
      background: rgba(15,118,110,0.1);
      color: #0f766e;
      font-size: 0.8rem;
    }

    .steps-row {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
      margin-bottom: 0.5rem;
    }
    .step-pill {
      flex: 1 1 0;
      min-width: 0;
      border-radius: 999px;
      border: 1px dashed rgba(148,163,184,0.9);
      padding: 0.35rem 0.7rem;
      font-size: 0.78rem;
      display: flex;
      align-items: center;
      gap: 0.4rem;
      color: var(--text-muted);
      background: rgba(255,255,255,0.8);
    }
    .step-pill.active {
      border-style: solid;
      border-color: rgba(37,99,235,0.8);
      background: linear-gradient(120deg,#1d4ed8,#22c55e);
      color: #e5edff;
      font-weight: 600;
    }
    .step-pill span.step-index {
      width: 20px;
      height: 20px;
      border-radius: 999px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 0.7rem;
      background: rgba(15,23,42,0.07);
    }
    .step-pill.active span.step-index {
      background: rgba(15,23,42,0.25);
    }

    .scan-card {
      background: radial-gradient(circle at top left, rgba(59,130,246,0.9) 0, rgba(37,99,235,0.95) 35%, rgba(15,23,42,1) 100%);
      color: #e5edff;
      border-radius: 24px;
      position: relative;
      overflow: hidden;
    }
    .scan-card::before {
      content: "";
      position: absolute;
      width: 220px;
      height: 220px;
      border-radius: 999px;
      background: radial-gradient(circle, rgba(56,189,248,0.4), transparent 70%);
      top: -60px;
      right: -80px;
      opacity: 0.7;
    }
    .scan-card::after {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: inherit;
      border: 1px solid rgba(191,219,254,0.45);
      pointer-events: none;
    }
    .scan-left {
      position: relative;
      z-index: 1;
    }
    .scan-label {
      font-size: 0.9rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.1em;
      color: #bfdbfe;
    }
    .scan-title {
      font-size: 1.5rem;
      font-weight: 700;
    }
    .scan-subtitle {
      font-size: 0.9rem;
      color: #c7d2fe;
    }
    .scan-input-wrapper {
      background: rgba(15,23,42,0.6);
      border-radius: 18px;
      padding: 0.75rem;
      border: 1px solid rgba(148,163,184,0.45);
      box-shadow: 0 18px 45px rgba(15,23,42,0.65);
    }

    .scan-input-big {
      font-size: 1.5rem;
      padding-top: 0.9rem !important;
      padding-bottom: 0.9rem !important;
      background: rgba(15,23,42,0.85);
      border: 1px solid rgba(148,163,184,0.8);
      color: #e5edff;
    }
    .scan-input-big::placeholder {
      color: rgba(148,163,184,0.8);
    }
    #gs1_text:focus {
      box-shadow: 0 0 0 0.16rem rgba(56,189,248,0.55);
      border-color: #38bdf8;
    }
    .scan-input-addon {
      background: rgba(15,23,42,0.9);
      border: 1px solid rgba(148,163,184,0.8);
      border-right: none;
      color: #bfdbfe;
    }
    .btn-scan {
      font-size: 1rem;
      padding: 0.9rem 1.4rem;
      border-radius: 12px;
      background: linear-gradient(120deg,#22c55e,#a3e635);
      border: none;
      color: #052e16;
      font-weight: 600;
      box-shadow: 0 15px 35px rgba(22,163,74,0.45);
    }
    .btn-scan:hover {
      filter: brightness(1.02);
    }

    .scan-pulse {
      position: absolute;
      inset: 0;
      border-radius: inherit;
      border: 1px solid rgba(96,165,250,0.7);
      pointer-events: none;
      animation: pulseBorder 2.2s infinite;
      opacity: 0.7;
    }
    @keyframes pulseBorder {
      0% { transform: scale(0.98); opacity: 0.8; }
      50% { transform: scale(1.02); opacity: 0.3; }
      100% { transform: scale(0.98); opacity: 0.8; }
    }

    .btn-rollback {
      border-radius: 999px;
      border-width: 2px;
      border-color: rgba(248,113,113,0.9);
      color: #fee2e2;
      padding: 0.5rem 1.3rem;
      font-size: 0.9rem;
      font-weight: 600;
      display: inline-flex;
      align-items: center;
      gap: 0.4rem;
      background: transparent;
    }
    .btn-rollback i {
      font-size: 1rem;
    }
    .btn-rollback:hover {
      background: rgba(248,113,113,0.18);
    }

    .btn-restart-block {
      border-radius: 999px;
      border-width: 2px;
      border-color: rgba(248,113,113,0.9);
      color: #b91c1c;
      font-weight: 600;
      padding: 0.5rem 1.1rem;
      display: inline-flex;
      align-items: center;
      gap: 0.35rem;
      background: #fff;
    }
    .btn-restart-block i {
      font-size: 1rem;
    }
    .btn-restart-block:hover {
      background: rgba(248,113,113,0.08);
    }

    .form-select-lg {
      padding-top: 0.7rem;
      padding-bottom: 0.7rem;
      font-size: 1rem;
      border-radius: 12px;
    }
    .form-select-lg:focus {
      box-shadow: 0 0 0 0.12rem rgba(37,99,235,0.35);
      border-color: #2563eb;
    }
    .selector-card {
      background: rgba(255,255,255,0.96);
    }

    /* ✅ (3) RASM KESILMASIN: contain */
    .img-thumb {
      width: 220px;
      height: 220px;
      object-fit: contain;      /* cover -> contain */
      border-radius: 16px;
      border: 1px solid #e5e7eb;
      background: #fff;
      padding: 8px;            /* uzoqroqdan ko‘rinsin */
    }

    .table thead {
      background: #eff3ff;
      font-size: 0.95rem;
    }
    .table tbody tr {
      font-size: 0.95rem;
      transition: background 0.12s ease;
    }
    .table tbody tr:hover {
      background: #f9fafb;
    }
    .badge-mode {
      font-size: 0.78rem;
    }
    code {
      font-size: 0.85rem;
      background: #f3f4f6;
      padding: 0.05rem 0.25rem;
      border-radius: 4px;
    }

    /* ✅ (5) ICHKI SCROLLNI OLIB TASHLASH */
    #group_api_result {
      border-radius: 8px;
      border: 1px solid #e5e7eb;
      padding: 0.4rem 0.75rem;
      background: #f9fafb;
      font-size: 0.8rem;
      /* max-height / overflow removed */
    }
    #group_api_result .code-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 2px 0;
    }
    #group_api_result .code-item.bad {
      color: #b91c1c;
      font-weight: 600;
    }
    #group_api_result .code-item.good {
      color: #15803d;
    }

    /* ✅ jadval ichida “scroll” bo‘lib ketmasin: kenglikni boshqarish */
    table.table {
      table-layout: fixed;
      width: 100%;
    }
    table.table th, table.table td {
      word-break: break-word;
      overflow-wrap: anywhere;
      vertical-align: top;
    }

    @media (max-width: 767.98px) {
      .scan-card { border-radius: 18px; }
      .scan-input-big { font-size: 1.1rem; }
      .scan-subtitle { font-size: 0.8rem; }
      .page-wrapper { padding-inline: 0.4rem; }
      .img-thumb { width: 170px; height: 170px; }
    }
  </style>
</head>
<body>

<?php
  $active = 'marking';
  require __DIR__ . '/navbar.php';
?>
<div class="page-wrapper">
  <div class="py-4">

    <!-- Title + clock + user -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-3">
      <div class="mb-2 mb-md-0">
        <h3 class="mb-1 d-flex align-items-center gap-2">
          Markirovka sahifasi
        </h3>
        <div class="text-muted">
          GS1 DataMatrix orqali mineral suv mahsulotlarini real-time markirovkalash.
        </div>
      </div>
      <div class="text-md-end mt-2 mt-md-0">
        <div class="clock-pill mb-1">
          <i class="fa-regular fa-clock"></i>
          <span id="clock"></span>
        </div>
        <div class="text-muted small">Bugungi sana va vaqt</div>
      </div>
    </div>

    <!-- Mobil uchun user chip -->
    <div class="mb-3 d-md-none">
      <span class="user-chip">
        <span class="user-avatar">
          <?php echo strtoupper(mb_substr($userName, 0, 1, 'UTF-8')); ?>
        </span>
        <span>
          <span class="d-block" style="line-height:1;">
            <?php echo htmlspecialchars($userName); ?>
          </span>
          <span class="user-role-badge">Operator</span>
        </span>
      </span>
    </div>

    <!-- Qadamlar -->
    <div class="steps-row mb-3">
      <div class="step-pill active">
        <span class="step-index"><i class="fa-solid fa-1"></i></span>
        <span>Skaner apparat orqali GS1 kodni yuboring</span>
      </div>
      <div class="step-pill">
        <span class="step-index"><i class="fa-solid fa-2"></i></span>
        <span>Kategoriya va mahsulotni tanlang</span>
      </div>
      <div class="step-pill">
        <span class="step-index"><i class="fa-solid fa-3"></i></span>
        <span>Bloklar holatini va hisobotni kuzating</span>
      </div>
    </div>

    <!-- Stat cards -->
    <div class="row g-3 mb-4">
      <div class="col-md-4">
        <div class="card stat-card">
          <div class="card-body">
            <div class="stat-icon"><i class="fa-solid fa-list-check"></i></div>
            <div class="stat-label">Joriy blok uchun kiritildi</div>
            <div class="stat-value" id="stat-current-count">0</div>
            <div class="text-muted small">dona GS1 kod</div>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card stat-card">
          <div class="card-body">
            <div class="stat-icon"><i class="fa-solid fa-box-open"></i></div>
            <div class="stat-label">Blok unit uchun qoldi</div>
            <div class="stat-value" id="stat-remaining">0</div>
            <div class="text-muted small">dona to‘liq blokgacha</div>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card stat-card">
          <div class="card-body">
            <div class="stat-icon"><i class="fa-solid fa-layer-group"></i></div>
            <div class="stat-label">Bugungi bloklar soni</div>
            <div class="stat-value" id="stat-today-blocks">0</div>
            <div class="text-muted small">yakunlangan blok / guruh</div>
          </div>
        </div>
      </div>
    </div>

    <!-- KATTA GS1 SCAN KARTOCHKA -->
    <div class="card scan-card mb-4">
      <div class="scan-pulse"></div>
      <div class="card-body">
        <div class="row g-4 align-items-center">
          <div class="col-lg-4 scan-left">
            <div class="scan-label mb-2">Real-time markirovka</div>
            <div class="scan-title mb-1">
              <i class="fa-solid fa-barcode"></i> GS1 DataMatrix skaneri
            </div>
            <div class="scan-subtitle mb-3">
              Skaner aniq va tez ishlashi uchun faqat shu oynadagi inputga uzluksiz kod yuboradi.
            </div>
            <button id="btn-rollback" class="btn btn-rollback" type="button">
              <i class="fa-solid fa-triangle-exclamation"></i>
              <span>Fors-major: joriy blokni to‘liq restart qilish</span>
            </button>
            <div class="text-light small mt-2">
              <i class="fa-regular fa-lightbulb"></i>
              Agar noto‘g‘ri mahsulotni tanlab yuborsangiz yoki skaner chalkashsa, shu tugma orqali
              joriy blokni bekor qilib, boshidan boshlashingiz mumkin.
            </div>
          </div>
          <div class="col-lg-8">
            <div class="scan-input-wrapper">
              <form id="scan_form">
                <div class="input-group input-group-lg">
                  <span class="input-group-text scan-input-addon">
                    <i class="fa-solid fa-qrcode"></i>
                  </span>
                  <input
                    type="text"
                    id="gs1_text"
                    name="gs1_text"
                    class="form-control scan-input-big"
                    placeholder="GS1 iste’mol kodini skanerlang..."
                    autocomplete="off"
                  >
                  <button class="btn btn-scan" type="submit">
                    <i class="fa-solid fa-paper-plane"></i> Yuborish
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Category + product qatori -->
    <div class="card selector-card mb-4">
      <div class="card-body">
        <div class="row g-4 align-items-start">
          <div class="col-md-6">
            <label for="category_id" class="form-label">Kategoriya</label>
            <select id="category_id" class="form-select form-select-lg">
              <option value="">Tanlang...</option>
              <?php foreach ($categories as $cat): ?>
                <option value="<?= (int)$cat['id'] ?>"
                        data-image="<?= htmlspecialchars($cat['image_path'] ?? '') ?>">
                  <?= htmlspecialchars($cat['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="mt-3 d-flex flex-column flex-sm-row align-items-start gap-3">
              <img id="category_image_preview" class="img-thumb" src="" alt="Kategoriya rasmi" style="display:none;">
            </div>
          </div>

          <div class="col-md-6">
            <label for="product_id" class="form-label">Mahsulot</label>
            <select id="product_id" class="form-select form-select-lg" disabled>
              <option value="">Avval kategoriya tanlang</option>
            </select>
            <div class="mt-3 d-flex flex-column flex-sm-row align-items-start gap-3">
              <img id="product_image_preview" class="img-thumb" src="" alt="Mahsulot rasmi" style="display:none;">
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Jadval blok + kodlar -->
    <div class="row g-3">
      <div class="col-lg-7">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <span>Oxirgi 10 ta blok / transport kodlari</span>
          </div>
          <div class="card-body p-0">
            <!-- ✅ (5) table-responsive olib tashlandi -->
            <table class="table table-sm mb-0 align-middle">
              <thead>
              <tr>
                <th style="width:60px;">#</th>
                <th>Mahsulot</th>
                <th>Foydalanuvchi</th>
                <th>Blok / transport kodi</th>
                <th>Rejim</th>
                <th>Vaqt</th>
              </tr>
              </thead>
              <tbody id="tbl-blocks-body">
                <tr><td colspan="6" class="text-center py-3 text-muted">Ma’lumot yo‘q</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="col-lg-5">
        <div class="card">
          <div class="card-header">
            Oxirgi 5 ta iste’mol kodlari
          </div>
          <div class="card-body p-0">
            <!-- ✅ (5) table-responsive olib tashlandi -->
            <table class="table table-sm mb-0 align-middle">
              <thead>
              <tr>
                <th style="width:60px;">#</th>
                <th>Mahsulot</th>
                <th>Foydalanuvchi</th>
                <th>GS1 matn</th>
                <th>Vaqt</th>
              </tr>
              </thead>
              <tbody id="tbl-codes-body">
                <tr><td colspan="5" class="text-center py-3 text-muted">Ma’lumot yo‘q</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- Manual / Auto group code modal -->
<div class="modal fade" id="groupCodeModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <form id="group_code_form" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="fa-solid fa-boxes-stacked me-1"></i>
          Guruh (blok) GS1 kodini kiriting
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p class="small text-muted mb-2">
          Joriy blok to‘ldi. Endi blok/guruh uchun GS1 DataMatrix matnini kiriting
          yoki auto generatsiya natijasini ko‘ring.
        </p>

        <div id="group_error_alert" class="alert alert-danger d-none small" role="alert"></div>

        <div class="mb-3">
          <label for="group_gs1_text" class="form-label">Guruh GS1 kodi</label>
          <input type="text" id="group_gs1_text" name="group_gs1_text" class="form-control" autocomplete="off">
          <div class="form-text small">
            Maslahat: guruh kodini kiritishdan oldin, barcha iste’mol kodlari to‘liq skan qilinganligiga ishonch hosil qiling.
          </div>
        </div>
        <div id="group_api_result" class="mt-2" style="display:none;"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-restart-block me-auto" id="group_restart_btn">
          <i class="fa-solid fa-rotate-left"></i>
          Blokni to‘liq bekor qilish (Restart)
        </button>
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Oynani yopish</button>
        <button type="submit" class="btn btn-primary">
          <span class="spinner-border spinner-border-sm me-1 d-none" id="group_submit_spinner"></span>
          <i class="fa-solid fa-circle-check"></i> Saqlash
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Scripts -->
<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/api_marking.php';

  const BASE_PATH = '/mark2/';

  // ✅ (2) VALIDATION RULES
  const REQUIRED_SUBSTR = '478008327';
  const MIN_LEN = 31;
  const MAX_LEN = 40;

  function isValidGs1Text(txt) {
    const s = String(txt || '').trim();
    if (!s) return false;
    if (s.length < MIN_LEN || s.length > MAX_LEN) return false;
    if (s.indexOf(REQUIRED_SUBSTR) === -1) return false; // strpos
    return true;
  }

  function gs1RuleMessage() {
    return `GS1 kod ${MIN_LEN}-${MAX_LEN} belgidan iborat bo‘lishi va ichida ${REQUIRED_SUBSTR} qatnashishi shart`;
  }

  function withBase(path) {
    if (!path) return '';
    if (/^(https?:)?\/\//.test(path) || path.startsWith(BASE_PATH) || path.startsWith('data:')) {
      return path;
    }
    if (path[0] === '/') {
      path = path.slice(1);
    }
    return BASE_PATH + path;
  }

  function updateClock() {
    const now = new Date();
    const pad = (n) => n.toString().padStart(2, '0');
    const y = now.getFullYear();
    const m = pad(now.getMonth() + 1);
    const d = pad(now.getDate());
    const h = pad(now.getHours());
    const i = pad(now.getMinutes());
    const s = pad(now.getSeconds());
    document.getElementById('clock').innerText = `${y}-${m}-${d} ${h}:${i}:${s}`;
  }
  setInterval(updateClock, 1000);
  updateClock();

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

  let groupModal;
  let openModalAfterStatus = false;

  $(function () {
    groupModal = new bootstrap.Modal(document.getElementById('groupCodeModal'));

    $('#groupCodeModal').on('shown.bs.modal', function () {
      $('#group_gs1_text').trigger('focus');
    });

    // LocalStorage’dan oxirgi holat
    const storedWaiting = localStorage.getItem('marking_waiting_group') === '1';
    const storedCat  = localStorage.getItem('marking_last_category') || '';
    const storedProd = localStorage.getItem('marking_last_product') || '';

    openModalAfterStatus = storedWaiting;

    // Sahifa ochilganda oxirgi kategoriya + mahsulotni qayta yuklaymiz
    if (storedCat) {
      $('#category_id').val(storedCat);
      showSelectedCategoryImage();
      loadProducts(storedCat, storedProd);
    }

    $('#gs1_text').focus();

    $('#gs1_text').on('keydown', function (e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        sendGS1();
      }
    });

    $('#scan_form').on('submit', function (e) {
      e.preventDefault();
      sendGS1();
    });

    $('#category_id').on('change', function () {
      const catId = $(this).val();
      showSelectedCategoryImage();

      $('#product_id').prop('disabled', true).html('<option value="">Yuklanmoqda...</option>');
      $('#product_image_preview').hide();

      if (catId) {
        loadProducts(catId, null);
      } else {
        $('#product_id').html('<option value="">Avval kategoriya tanlang</option>');
      }
    });

    $('#product_id').on('change', function () {
      const opt    = $(this).find('option:selected');
      const imgRaw = opt.data('image') || '';
      const img    = withBase(imgRaw);

      if (imgRaw) {
        $('#product_image_preview').attr('src', img).show();
      } else {
        $('#product_image_preview').hide();
      }

      const productId = $(this).val();
      const catId = $('#category_id').val();

      if (productId) {
        localStorage.setItem('marking_last_category', catId || '');
        localStorage.setItem('marking_last_product', productId);
        loadStatus(productId);
      } else {
        localStorage.removeItem('marking_last_product');
        resetStatsAndTables();
      }
    });

    $('#btn-rollback').on('click', function () {
      rollbackOpenBlock(false);
    });

    $('#group_restart_btn').on('click', function () {
      rollbackOpenBlock(true);
    });

    $('#group_code_form').on('submit', function (e) {
      e.preventDefault();
      saveGroupCode();
    });

    $(document).on('click', '.btn-print-sscc', function () {
      const code = $(this).data('code');
      const rowId = $(this).data('id'); // ✅ (4)
      if (!code) {
        toastr.error('SSCC kod topilmadi');
        return;
      }
      printSSCC(code, rowId);
    });
  });

  function showSelectedCategoryImage() {
    const opt   = $('#category_id').find('option:selected');
    const imgRaw = opt.data('image') || '';
    const img    = withBase(imgRaw);
    if (imgRaw) {
      $('#category_image_preview').attr('src', img).show();
    } else {
      $('#category_image_preview').hide();
    }
  }

  function loadProducts(categoryId, preselectProductId) {
    $.getJSON(apiUrl, {action: 'get_products', category_id: categoryId})
      .done(function (res) {
        if (res.status !== 'ok') {
          toastr.error(res.message || 'Xatolik');
          $('#product_id').html('<option value="">Xatolik</option>').prop('disabled', true);
          return;
        }
        const list = res.products || [];
        if (!list.length) {
          $('#product_id').html('<option value="">Bu kategoriyada mahsulot yo‘q</option>').prop('disabled', true);
          return;
        }
        let html = '<option value="">Mahsulot tanlang...</option>';
        list.forEach(p => {
          const selectedAttr = (preselectProductId && String(preselectProductId) === String(p.id)) ? ' selected' : '';
          html += `<option value="${p.id}" data-image="${p.product_image || ''}"${selectedAttr}>
                     ${escapeHtml(p.name)}
                   </option>`;
        });
        $('#product_id').html(html).prop('disabled', false);

        if (preselectProductId) {
          $('#product_id').trigger('change');
        }
      })
      .fail(function () {
        toastr.error('Mahsulotlarni yuklashda xatolik');
        $('#product_id').html('<option value="">Xatolik</option>').prop('disabled', true);
      });
  }

  function loadStatus(productId) {
    $.getJSON(apiUrl, {action: 'get_status', product_id: productId})
      .done(function (res) {
        if (res.status !== 'ok') {
          toastr.error(res.message || 'Xatolik');
          return;
        }
        updateStats(res.stats);
        renderBlocks(res.last_blocks);
        renderCodes(res.last_codes);

        // storedWaiting faqat manual bo‘lganda ishlaydi.
        if (openModalAfterStatus) {
          openModalAfterStatus = false;
          $('#group_gs1_text').val('');
          $('#group_api_result').hide().empty();
          $('#group_error_alert').addClass('d-none').text('');
          groupModal.show();
        }
      })
      .fail(function () {
        toastr.error('Statusni yuklashda xatolik');
      });
  }

  function sendGS1() {
    const categoryId = $('#category_id').val();
    const productId  = $('#product_id').val();
    const gs1Text    = $('#gs1_text').val().trim();

    if (!categoryId) {
      $('#category_id').addClass('is-invalid').focus();
      toastr.error('Kategoriya majburiy');
      return;
    } else {
      $('#category_id').removeClass('is-invalid');
    }
    if (!productId) {
      $('#product_id').addClass('is-invalid').focus();
      toastr.error('Mahsulot majburiy');
      return;
    } else {
      $('#product_id').removeClass('is-invalid');
    }

    // ✅ (2) VALIDATE GS1 INPUT
    if (!isValidGs1Text(gs1Text)) {
      $('#gs1_text').addClass('is-invalid').focus();
      toastr.error(gs1RuleMessage());
      return;
    } else {
      $('#gs1_text').removeClass('is-invalid');
    }

    $.post(apiUrl + '?action=scan_code', {
      category_id: categoryId,
      product_id: productId,
      gs1_text: gs1Text
    }, function (res) {
      if (res.status !== 'ok') {
        toastr.error(res.message || 'Xatolik');

        if (res.message && res.message.indexOf('guruh GS1') !== -1) {
          $('#group_gs1_text').val('');
          $('#group_api_result').hide().empty();
          $('#group_error_alert').addClass('d-none').text('');
          groupModal.show();
          localStorage.setItem('marking_waiting_group', '1');
        }

        if (res.stats) updateStats(res.stats);
        if (res.last_blocks) renderBlocks(res.last_blocks);
        if (res.last_codes) renderCodes(res.last_codes);
        return;
      }

      if (res.stats) updateStats(res.stats);
      if (res.last_blocks) renderBlocks(res.last_blocks);
      if (res.last_codes) renderCodes(res.last_codes);

      if (res.mode === 'code_saved') {
        toastr.success('Kod qabul qilindi');

      } else if (res.mode === 'need_group_code') {
        toastr.info('Blok to‘ldi. Guruh GS1 kodini kiriting');
        $('#group_gs1_text').val('');
        $('#group_api_result').hide().empty();
        $('#group_error_alert').addClass('d-none').text('');
        $('#group_submit_spinner').addClass('d-none');
        $('#group_gs1_text').prop('readonly', false);
        groupModal.show();

        localStorage.setItem('marking_waiting_group', '1');
        localStorage.setItem('marking_last_category', categoryId || '');
        localStorage.setItem('marking_last_product', productId || '');

      } else if (res.mode === 'block_completed_auto') {
        // ✅ (1) AUTO bo‘lsa MODAL UMUMAN OCHILMASIN
        toastr.success('Blok yakunlandi (auto).');
        localStorage.removeItem('marking_waiting_group');
        // xohlasangiz shu yerda qo‘shimcha “print ready” toast ham qo‘shamiz
      }
    }, 'json').fail(function () {
      toastr.error('Server xatosi');
    }).always(function () {
      $('#gs1_text').val('').focus();
    });
  }

  function rollbackOpenBlock(fromModal) {
    const productId = $('#product_id').val();
    if (!productId) {
      toastr.error('Avval mahsulot tanlang');
      return;
    }
    if (!confirm('Joriy blokdagi kiritilgan kodlarni butunlay bekor qilasizmi (restart)?')) {
      return;
    }
    $.post(apiUrl + '?action=rollback_open_block', {product_id: productId}, function (res) {
      if (res.status !== 'ok') {
        toastr.error(res.message || 'Xatolik');
        return;
      }
      toastr.success(res.message || 'Joriy blok bekor qilindi');

      localStorage.removeItem('marking_waiting_group');

      if (res.stats) updateStats(res.stats);
      if (res.last_blocks) renderBlocks(res.last_blocks);
      if (res.last_codes) renderCodes(res.last_codes);

      if (fromModal && groupModal) {
        groupModal.hide();
      }
      $('#group_error_alert').addClass('d-none').text('');
      $('#group_api_result').hide().empty();

      $('#gs1_text').val('').focus();
    }, 'json').fail(function () {
      toastr.error('Server xatosi');
    });
  }

  function saveGroupCode() {
    const productId     = $('#product_id').val();
    const groupGs1Text  = $('#group_gs1_text').val().trim();

    if (!productId) {
      toastr.error('Mahsulot tanlanmagan');
      return;
    }

    // ✅ (2) VALIDATE GROUP GS1 INPUT HAM
    if (!isValidGs1Text(groupGs1Text)) {
      toastr.error(gs1RuleMessage());
      $('#group_gs1_text').focus();
      return;
    }

    $('#group_submit_spinner').removeClass('d-none');
    $('#group_error_alert').addClass('d-none').text('');

    $.post(apiUrl + '?action=save_group_code', {
      product_id: productId,
      group_gs1_text: groupGs1Text
    }, function (res) {
      $('#group_submit_spinner').addClass('d-none');

      if (res.status !== 'ok') {
        toastr.error(res.message || 'Xatolik');

        if (res.message) {
          $('#group_error_alert').removeClass('d-none').text(res.message);
        } else {
          $('#group_error_alert').addClass('d-none').text('');
        }

        if (res.codes && Array.isArray(res.codes)) {
          renderGroupApiResult(res.codes);
        } else {
          $('#group_api_result').hide().empty();
        }

        if (res.stats) updateStats(res.stats);
        if (res.last_blocks) renderBlocks(res.last_blocks);
        if (res.last_codes) renderCodes(res.last_codes);

        $('#group_gs1_text').val('').focus();
        return;
      }

      toastr.success(res.message || 'Blok guruh kodi bilan saqlandi');

      if (res.stats) updateStats(res.stats);
      if (res.last_blocks) renderBlocks(res.last_blocks);
      if (res.last_codes) renderCodes(res.last_codes);

      $('#group_api_result').hide().empty();
      $('#group_gs1_text').val('');
      $('#group_error_alert').addClass('d-none').text('');

      localStorage.removeItem('marking_waiting_group');

      groupModal.hide();
      $('#gs1_text').val('').focus();
    }, 'json').fail(function () {
      $('#group_submit_spinner').addClass('d-none');
      toastr.error('Server xatosi');
      $('#group_gs1_text').val('').focus();
    });
  }

  function renderGroupApiResult(codes) {
    let html = '';
    codes.forEach(c => {
      const cls = c.isError ? 'bad' : 'good';
      html += `<div class="code-item ${cls}">
                 <span>${escapeHtml(c.value || '')}</span>
                 <span>${c.isError ? 'Xato' : 'OK'}</span>
               </div>`;
    });
    $('#group_api_result').html(html).show();
  }

  function updateStats(stats) {
    if (!stats) return;
    $('#stat-current-count').text(stats.current_count ?? 0);
    $('#stat-remaining').text(stats.remaining ?? 0);
    $('#stat-today-blocks').text(stats.today_blocks ?? 0);
  }

  function renderBlocks(list) {
    const tbody = $('#tbl-blocks-body');
    if (!list || !list.length) {
      tbody.html('<tr><td colspan="6" class="text-center py-3 text-muted">Ma’lumot yo‘q</td></tr>');
      return;
    }
    let html = '';
    list.forEach(row => {
      const modeClass = row.mode_type === 'auto'
        ? 'bg-success-subtle text-success'
        : 'bg-primary-subtle text-primary';
      const modeText  = row.mode_type === 'auto' ? 'Auto' : 'Manual';

      let codeCell = `<code>${escapeHtml(row.gtin2_number || '')}</code>`;
      if (row.mode_type === 'auto' && row.gtin2_number) {
        codeCell += ` 
          <button type="button"
                  class="btn btn-sm btn-outline-secondary ms-1 btn-print-sscc"
                  data-code="${escapeHtml(row.gtin2_number)}"
                  data-id="${escapeHtml(row.id)}">
            <i class="fa-solid fa-print"></i>
          </button>`;
      }

      html += `<tr>
        <td>${escapeHtml(row.id)}</td>
        <td>${escapeHtml(row.product_name || '')}</td>
        <td>${escapeHtml(row.user_name || '')}</td>
        <td>${codeCell}</td>
        <td><span class="badge ${modeClass} badge-mode">${modeText}</span></td>
        <td>${escapeHtml(row.created_at || '')}</td>
      </tr>`;
    });
    tbody.html(html);
  }

  function renderCodes(list) {
    const tbody = $('#tbl-codes-body');
    if (!list || !list.length) {
      tbody.html('<tr><td colspan="5" class="text-center py-3 text-muted">Ma’lumot yo‘q</td></tr>');
      return;
    }
    let html = '';
    list.forEach(row => {
      html += `<tr>
        <td>${escapeHtml(row.id)}</td>
        <td>${escapeHtml(row.product_name || '')}</td>
        <td>${escapeHtml(row.user_name || '')}</td>
        <td><code>${escapeHtml(row.gs1_text || '')}</code></td>
        <td>${escapeHtml(row.created_at || '')}</td>
      </tr>`;
    });
    tbody.html(html);
  }

  function resetStatsAndTables() {
    updateStats({current_count: 0, remaining: 0, today_blocks: 0});
    $('#tbl-blocks-body').html('<tr><td colspan="6" class="text-center py-3 text-muted">Ma’lumot yo‘q</td></tr>');
    $('#tbl-codes-body').html('<tr><td colspan="5" class="text-center py-3 text-muted">Ma’lumot yo‘q</td></tr>');
  }

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

  // ✅ (4) SSCC print: pastiga ID raqam yoziladi
  function printSSCC(code, rowId) {
    const w = window.open('', '_blank', 'width=520,height=360');
    if (!w) {
      toastr.error('Pop-up oynani brauzer blok qildi, iltimos ruxsat bering.');
      return;
    }
    const safeCode = String(code || '').replace(/[^0-9]/g, '');
    const safeId   = String(rowId ?? '').replace(/[^0-9]/g, '');

    w.document.write(`
      <!DOCTYPE html>
      <html lang="uz">
      <head>
        <meta charset="UTF-8">
        <title>SSCC Print</title>
        <style>
          * { box-sizing: border-box; }
          body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
          }
          .code-wrapper { text-align: center; width: 100%; max-width: 520px; }
          .code-label { font-size: 14px; margin-bottom: 6px; }
          .id-line { margin-top: 10px; font-size: 14px; font-weight: 700; letter-spacing: 0.5px; }
          .code-value { font-size: 20px; letter-spacing: 3px; font-weight: 600; margin-top: 8px; }
          svg { width: 100%; max-width: 460px; }
        </style>
      </head>
      <body>
        <div class="code-wrapper">
          <div class="code-label">SSCC / blok kodi</div>
          <svg id="barcode"></svg>
          <div class="code-value">${escapeHtml(code)}</div>
          <div class="id-line">ID RAQAM: ${escapeHtml(safeId || String(rowId || ''))}</div>
        </div>
      </body>
      </html>
    `);
    w.document.close();

    const script = w.document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js';
    script.onload = function () {
      try {
        w.JsBarcode('#barcode', safeCode, {
          format: 'code128',
          displayValue: false,
          margin: 0,
          width: 2,
          height: 80
        });
        w.focus();
        w.print();
      } catch (e) {
        console.error(e);
      }
    };
    w.document.head.appendChild(script);
  }
</script>
</body>
</html>
