<?php
// public/km.php
require_once __DIR__ . '/auth_stub.php';
?>
<!DOCTYPE html>
<html lang="uz">
<head>
  <meta charset="UTF-8">
  <title>KM tekshirish – Markirovka tizimi</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;
    }

    .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);
    }

    .badge-count {
      font-size: 0.8rem;
      border-radius: 999px;
      padding: 0.2rem 0.6rem;
    }

    .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;
    }

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

<?php
  $active = 'km';
  require __DIR__ . '/navbar.php';
?>

<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">
      <div>
        <h3 class="mb-1">KM tekshirish</h3>
        <div class="text-muted">
          Yuklangan fayldagi kodlarni bazadagi <strong>GS1</strong> kodlar bilan solishtirish va yo‘q kodlar ro‘yxatini olish.
        </div>
      </div>
    </div>

    <!-- UPLOAD CARD -->
    <div class="card mb-3">
      <div class="card-body">
        <div class="pill-heading mb-3">1-qadam: Rejim va fayl</div>

        <form id="km-form" class="row g-3">
          <div class="col-md-4">
            <label class="form-label d-block">Kod turi</label>
            <div class="btn-group" role="group" aria-label="KM mode">
              <input type="radio" class="btn-check" name="km_mode" id="mode_consumer" value="consumer" checked>
              <label class="btn btn-outline-primary" for="mode_consumer">
                <i class="fa-solid fa-barcode"></i> Iste'mol kodi
              </label>

              <input type="radio" class="btn-check" name="km_mode" id="mode_group" value="group">
              <label class="btn btn-outline-primary" for="mode_group">
                <i class="fa-solid fa-boxes-stacked"></i> Guruh kodi (blok)
              </label>
            </div>
            <div class="form-text text-muted small mt-1">
              Iste'mol kodi → <code>codes.gs1_text</code><br>
              Guruh kodi → <code>blocks.gtin2_number</code>
            </div>
          </div>

          <div class="col-md-5">
            <label class="form-label" for="km_file">Fayl (TXT / CSV)</label>
            <input type="file" class="form-control" id="km_file" name="file" accept=".txt,.csv,.dat,.log" required>
            <div class="form-text small text-muted">
              1 qatorda 1 ta kod bo‘lishi kerak. Excel fayl bo‘lsa, avval CSV qilib saqlab yuboring.
            </div>
          </div>

          <div class="col-md-3 d-flex align-items-end">
            <button type="submit" class="btn btn-primary w-100" id="btn-check">
              <i class="fa-solid fa-magnifying-glass"></i> Tekshirish
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- RESULT CARD -->
    <div class="card" id="result-card" style="display:none;">
      <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">2-qadam: Natija</div>
            <h5 class="mb-1" id="result-title">Natija</h5>
            <div class="small text-muted" id="result-subtitle"></div>
          </div>
          <div class="text-end">
            <div class="mb-1">
              <span class="badge bg-info-subtle text-info badge-count" id="badge-uploaded">Yuklangan: 0</span>
              <span class="badge bg-success-subtle text-success badge-count" id="badge-found">Bazadan topildi: 0</span>
              <span class="badge bg-danger-subtle text-danger badge-count" id="badge-missing">Yo‘q: 0</span>
            </div>
            <div class="d-flex flex-wrap gap-2 justify-content-md-end">
              <button type="button" class="btn btn-outline-secondary btn-sm" id="btn-export-txt">
                <i class="fa-solid fa-file-lines"></i> TXT
              </button>
              <button type="button" class="btn btn-outline-secondary btn-sm" id="btn-export-csv">
                <i class="fa-solid fa-file-csv"></i> CSV (Excel)
              </button>
              <button type="button" class="btn btn-outline-secondary btn-sm" id="btn-export-doc">
                <i class="fa-solid fa-file-word"></i> DOC
              </button>
              <button type="button" class="btn btn-outline-secondary btn-sm" id="btn-print-pdf">
                <i class="fa-solid fa-file-pdf"></i> PDF (50x50 mm, DataMatrix)</button>
            </div>
          </div>
        </div>

        <hr>

        <div class="table-responsive">
          <table class="table table-hover align-middle" id="missing-table">
            <thead>
            <tr>
              <th>#</th>
              <th>Kod (yo‘q)</th>
            </tr>
            </thead>
            <tbody>
              <tr><td colspan="2" class="text-center py-3 text-muted">Yo‘q kodlar ro‘yxati hali yo‘q</td></tr>
            </tbody>
          </table>
        </div>

        <div class="d-flex justify-content-between align-items-center mt-2 flex-wrap gap-2">
          <div>
            <button type="button" class="btn btn-outline-secondary btn-sm" id="btn-prev-page">
              <i class="fa-solid fa-chevron-left"></i> Oldingi
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm" id="btn-next-page">
              Keyingi <i class="fa-solid fa-chevron-right"></i>
            </button>
          </div>
          <div class="small text-muted" id="missing-page-info">Sahifa 1/1, jami 0 kod</div>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- JS kutubxonalar -->
<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>
<!-- DataMatrix / barcode uchun bwip-js (asosiy oynada) -->
<script src="https://cdn.jsdelivr.net/npm/bwip-js/dist/bwip-js-min.js"></script>

<script>
  // public/km.php dan api ga yo'l (agar km.php public/ ichida bo'lsa):
  const apiUrl = 'api/km_check.php';

  let kmMode        = 'consumer';
  let missingCodes  = [];
  let totalUploaded = 0;
  let totalUnique   = 0;
  let foundCount    = 0;
  let missingCount  = 0;

  let pageSize      = 50;
  let currentPage   = 1;
  let totalPages    = 1;

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

  $(function () {
    $('input[name="km_mode"]').on('change', function () {
      kmMode = $(this).val();
    });

    $('#km-form').on('submit', function (e) {
      e.preventDefault();
      runKmCheck();
    });

    $('#btn-prev-page').on('click', function () {
      if (currentPage > 1) {
        currentPage--;
        renderMissingTable();
      }
    });
    $('#btn-next-page').on('click', function () {
      if (currentPage < totalPages) {
        currentPage++;
        renderMissingTable();
      }
    });

    $('#btn-export-txt').on('click', function () {
      if (!missingCodes.length) {
        toastr.info('Eksport uchun yo‘q kodlar topilmadi');
        return;
      }
      const content = missingCodes.join('\\r\\n');
      downloadTextFile(content, 'km_missing_codes.txt');
    });

    $('#btn-export-csv').on('click', function () {
      if (!missingCodes.length) {
        toastr.info('Eksport uchun yo‘q kodlar topilmadi');
      return;
      }
      const header  = 'Index;Code';
      const lines   = [header];
      missingCodes.forEach((code, i) => {
        lines.push((i+1) + ';' + code.replace(/;/g, ','));
      });
      const content = lines.join('\\r\\n');
      downloadTextFile(content, 'km_missing_codes.csv');
    });

    $('#btn-export-doc').on('click', function () {
      if (!missingCodes.length) {
        toastr.info('Eksport uchun yo‘q kodlar topilmadi');
        return;
      }
      const content = missingCodes.join('\\r\\n');
      downloadTextFile(content, 'km_missing_codes.doc');
    });

    $('#btn-print-pdf').on('click', function () {
      printMissingCodes();
    });
  });

  function runKmCheck() {
    const fileInput = $('#km_file')[0];
    if (!fileInput.files.length) {
      toastr.error('Fayl tanlang');
      return;
    }

    const formData = new FormData();
    formData.append('action', 'check');
    formData.append('mode', kmMode);
    formData.append('file', fileInput.files[0]);

    $('#btn-check').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Tekshirilmoqda...');

    $.ajax({
      url: apiUrl,
      method: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json'
    }).done(function (res) {
      if (res.status !== 'ok') {
        toastr.error(res.message || 'Tekshirishda xatolik');
        return;
      }

      missingCodes  = res.missing_codes || [];
      totalUploaded = res.total_uploaded || 0;
      totalUnique   = res.total_unique || 0;
      foundCount    = res.found_count || 0;
      missingCount  = res.missing_count || 0;
      kmMode        = res.mode || kmMode;

      currentPage = 1;
      totalPages  = missingCount > 0 ? Math.ceil(missingCount / pageSize) : 1;

      updateSummary(res.file_name || '');
      renderMissingTable();

      $('#result-card').slideDown(200);
      toastr.success('KM tekshirish yakunlandi');
    }).fail(function () {
      toastr.error('Server xatosi');
    }).always(function () {
      $('#btn-check').prop('disabled', false).html('<i class="fa-solid fa-magnifying-glass"></i> Tekshirish');
    });
  }

  function updateSummary(fileName) {
    const modeText = kmMode === 'group' ? 'Guruh kodlari (blok)' : 'Iste\'mol kodlari';

    $('#result-title').text('Natija: ' + modeText);
    $('#result-subtitle').text(
      (fileName ? ('Fayl: ' + fileName + ' — ') : '') +
      'Yuklangan qatorlar: ' + totalUploaded +
      ', noyob kodlar: ' + totalUnique
    );

    $('#badge-uploaded').text('Yuklangan: ' + totalUploaded);
    $('#badge-found').text('Bazadan topildi: ' + foundCount);
    $('#badge-missing').text('Yo‘q: ' + missingCount);
  }

  function renderMissingTable() {
    const tbody = $('#missing-table tbody');

    if (!missingCodes.length) {
      tbody.html('<tr><td colspan="2" class="text-center py-3 text-muted">Barcha kodlar bazada topildi</td></tr>');
      $('#missing-page-info').text('Sahifa 1/1, jami 0 kod');
      $('#btn-prev-page').prop('disabled', true);
      $('#btn-next-page').prop('disabled', true);
      return;
    }

    totalPages = Math.max(1, Math.ceil(missingCodes.length / pageSize));
    if (currentPage > totalPages) currentPage = totalPages;

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex   = Math.min(startIndex + pageSize, missingCodes.length);
    const slice      = missingCodes.slice(startIndex, endIndex);

    let html = '';
    slice.forEach((code, i) => {
      const index = startIndex + i + 1;
      html += `
        <tr>
          <td>${index}</td>
          <td><code>${escapeHtml(code)}</code></td>
        </tr>
      `;
    });

    tbody.html(html);

    $('#missing-page-info').text(
      'Sahifa ' + currentPage + '/' + totalPages +
      ', jami ' + missingCodes.length + ' kod'
    );

    $('#btn-prev-page').prop('disabled', currentPage <= 1);
    $('#btn-next-page').prop('disabled', currentPage >= totalPages);
  }

  function downloadTextFile(content, filename) {
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8;' });
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }

  // === MUHIM QISM: 1 sahifada 1 ta DataMatrix, 50x50 mm ===
  function printMissingCodes() {
    if (!missingCodes.length) {
      toastr.info('PDF/print uchun yo‘q kodlar topilmadi');
      return;
    }

    if (typeof bwipjs === 'undefined') {
      toastr.error('Barcode kutubxona (bwip-js) yuklanmadi');
      return;
    }

    const win = window.open('', '_blank', 'width=500,height=500');
    if (!win) {
      toastr.error('Pop-up oynani brauzer blok qildi, iltimos ruxsat bering.');
      return;
    }

    const doc = win.document;
    doc.open();
    doc.write(`<!DOCTYPE html>
<html lang="uz">
<head>
  <meta charset="UTF-8">
  <title>KM – Yo'q kodlar (DataMatrix, 50x50 mm)</title>
  <style>
    @page {
      size: 50mm 50mm;
      margin: 0;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      padding: 0;
      font-family: Arial, sans-serif;
    }
    .page {
      width: 50mm;
      height: 50mm;
      display: flex;
      align-items: center;
      justify-content: center;
      page-break-after: always;
    }
    .label-inner {
      text-align: center;
      width: 100%;
      padding: 2mm;
    }
    .code-text {
      font-size: 6pt;
      margin-top: 1mm;
      word-wrap: break-word;
    }
    canvas {
      display: block;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <div id="labels"></div>
</body>
</html>`);
    doc.close();

    win.onload = function () {
      const container = doc.getElementById('labels');
      if (!container) {
        console.error('labels container topilmadi');
        return;
      }

      // Har bir kod uchun alohida sahifa (.page)
      missingCodes.forEach(function (code, idx) {
        const pageDiv = doc.createElement('div');
        pageDiv.className = 'page';

        const inner = doc.createElement('div');
        inner.className = 'label-inner';

        const canvas = doc.createElement('canvas');
        canvas.width = 200;
        canvas.height = 200;

        const txt = doc.createElement('div');
        txt.className = 'code-text';
        txt.textContent = code;

        inner.appendChild(canvas);
        inner.appendChild(txt);
        pageDiv.appendChild(inner);
        container.appendChild(pageDiv);

        try {
          // DataMatrix (XPrinter uchun mos 2D kod)
          bwipjs.toCanvas(canvas, {
            bcid: 'datamatrix',
            text: code,
            scale: 3,
            includetext: false
          });
        } catch (e) {
          console.error('Barcode chizishda xato:', e);
          txt.textContent = code + ' (chizishda xato)';
        }
      });

      // Barchasi chizilgandan keyin print
      setTimeout(function () {
        win.focus();
        win.print();
        // Agar oynani avtomatik yopmoqchi bo'lsangiz, quyidagi qatordan kommentni oling:
        // win.close();
      }, 300);
    };
  }

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