<?php
// public/products.php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth_stub.php';

session_start();

// Kategoriyalar ro'yxati
$catStmt = $pdo->query("SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name");
$categories = $catStmt->fetchAll();

$userName = current_user_name() ?: 'Admin';
?>
<!DOCTYPE html>
<html lang="uz">
<head>
  <meta charset="UTF-8">
  <title>Mahsulotlar – 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;
    }

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

    .badge-status {
      font-size: 0.75rem;
      border-radius: 999px;
      padding: 0.2rem 0.55rem;
    }

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

    .search-input {
      max-width: 260px;
    }

    .product-img-thumb{
  width: 54px;
  height: 54px;
  object-fit: contain;      /* ✅ kesmaydi */
  background: #fff;         /* ✅ bo‘sh joy oq */
  padding: 6px;             /* ✅ ichkaridan joy */
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

#product_image_preview{
  width: 100%;
  max-width: 240px;
  height: 170px;            /* ✅ preview box balandligi */
  object-fit: contain;      /* ✅ kesmaydi */
  background: #fff;
  padding: 10px;
  border-radius: 14px;
  border: 1px solid #e5e7eb;
}


    .filter-select {
      min-width: 140px;
    }

    .pagination {
      margin-bottom: 0;
    }

    /* Global loader */
    #global-loader {
      position: fixed;
      inset: 0;
      background: rgba(15,23,42,0.25);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 2000;
    }
    #global-loader .spinner-border {
      width: 3rem;
      height: 3rem;
    }
    #global-loader .loader-text {
      color: #e5edff;
      margin-top: 0.75rem;
      font-size: 0.9rem;
    }

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

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

<!-- Global loader -->
<div id="global-loader" class="d-flex flex-column align-items-center justify-content-center">
  <div class="spinner-border text-light" role="status">
    <span class="visually-hidden">Yuklanmoqda...</span>
  </div>
  <div class="loader-text">Ma’lumotlar yuklanmoqda...</div>
</div>

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

    <!-- Title -->
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-3">
      <div>
        <h3 class="mb-1">
          Mahsulotlar boshqaruvi
         
        </h3>
        <div class="text-muted">
          GTIN va blok konfiguratsiyasi markirovka tizimi uchun.
        </div>
      </div>
      <div class="mt-3 mt-md-0">
        <button id="btn-open-create" type="button" class="btn btn-primary">
          <i class="fa-solid fa-plus"></i> Yangi mahsulot
        </button>
      </div>
    </div>

    <!-- Filter + toolbar + table card -->
    <div class="card" id="export-area">
      <div class="card-body">

        <!-- Filter va toolbar qatori -->
        <div class="d-flex flex-column flex-xl-row justify-content-between gap-3 mb-3">
          <div>
            <div class="pill-heading mb-1">Filtrlar</div>
            <div class="d-flex flex-wrap gap-2 align-items-center">
              <select id="filter_category" class="form-select form-select-sm filter-select">
                <option value="">Barcha kategoriyalar</option>
                <?php foreach ($categories as $cat): ?>
                  <option value="<?= (int)$cat['id'] ?>">
                    <?= htmlspecialchars($cat['name']) ?>
                  </option>
                <?php endforeach; ?>
              </select>

              <select id="filter_generate" class="form-select form-select-sm filter-select">
                <option value="">Generate type (hammasi)</option>
                <option value="manual">Manual</option>
                <option value="auto">Auto</option>
              </select>

              <select id="filter_status" class="form-select form-select-sm filter-select">
                <option value="">Holat (hammasi)</option>
                <option value="1">Faol</option>
                <option value="0">No-faol</option>
              </select>
            </div>
          </div>

          <div class="d-flex flex-column align-items-start align-items-xl-end gap-2">
            <div class="d-flex flex-wrap gap-2 align-items-center">
              <input type="text" id="search" class="form-control form-control-sm search-input"
                     placeholder="Qidirish (nomi / GTIN / kategoriya)...">
            </div>
            <div class="d-flex flex-wrap gap-2">
              <div class="btn-group">
                <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle" data-bs-toggle="dropdown">
                  <i class="fa-solid fa-file-arrow-down"></i> Export
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><button class="dropdown-item" type="button" onclick="exportData('csv')">
                    <i class="fa-solid fa-file-csv me-2"></i>CSV
                  </button></li>
                  <li><button class="dropdown-item" type="button" onclick="exportData('xls')">
                    <i class="fa-regular fa-file-excel me-2"></i>XLS
                  </button></li>
                  <li><button class="dropdown-item" type="button" onclick="exportData('xlsx')">
                    <i class="fa-solid fa-file-excel me-2"></i>XLSX
                  </button></li>
                  <li><button class="dropdown-item" type="button" onclick="exportData('pdf')">
                    <i class="fa-regular fa-file-pdf me-2"></i>PDF
                  </button></li>
                  <li><button class="dropdown-item" type="button" onclick="exportData('doc')">
                    <i class="fa-regular fa-file-word me-2"></i>DOC
                  </button></li>
                  <li><hr class="dropdown-divider"></li>
                  <li><button class="dropdown-item" type="button" onclick="exportData('png')">
                    <i class="fa-regular fa-image me-2"></i>PNG
                  </button></li>
                  <li><button class="dropdown-item" type="button" onclick="exportData('jpg')">
                    <i class="fa-regular fa-image me-2"></i>JPG
                  </button></li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <!-- Jadval -->
        <div class="table-responsive" id="table-wrapper">
          <table class="table table-hover align-middle" id="products-table">
            <thead>
            <tr>
              <th>ID</th>
              <th>Kategoriya</th>
              <th>Mahsulot</th>
              <th>Blok unit</th>
              <th>GTIN</th>
              <th>GTIN2</th>
              <th>Generate</th>
              <th>Holat</th>
              <th>Yaratilgan</th>
              <th class="text-end">Amallar</th>
            </tr>
            </thead>
            <tbody>
              <tr><td colspan="10" class="text-center py-3 text-muted">Yuklanmoqda...</td></tr>
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <div class="d-flex justify-content-between align-items-center mt-3 flex-wrap gap-2">
          <div class="text-muted small" id="pagination-info"></div>
          <nav>
            <ul class="pagination pagination-sm mb-0" id="pagination"></ul>
          </nav>
        </div>

      </div>
    </div>

  </div>
</div>

<!-- PRODUCT MODAL (Create/Edit) -->
<div class="modal fade" id="productModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <form id="product-form" class="modal-content" enctype="multipart/form-data">
      <div class="modal-header">
        <h5 class="modal-title" id="productModalLabel">Yangi mahsulot qo‘shish</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="product_id" name="id" value="">

        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label" for="category_id">Kategoriya *</label>
            <select class="form-select" id="category_id" name="category_id" required>
              <option value="">Tanlang...</option>
              <?php foreach ($categories as $cat): ?>
                <option value="<?= (int)$cat['id'] ?>">
                  <?= htmlspecialchars($cat['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-4">
            <label class="form-label" for="name">Mahsulot nomi *</label>
            <input type="text" class="form-control" id="name" name="name" required>
          </div>

          <div class="col-md-4">
            <label class="form-label" for="product_block_unit">Blok unit (dona) *</label>
            <input type="number" min="1" class="form-control" id="product_block_unit" name="product_block_unit" required>
          </div>

          <div class="col-md-4">
            <label class="form-label" for="gtin_number">GTIN (iste’mol) *</label>
            <input type="text" class="form-control" id="gtin_number" name="gtin_number" required>
          </div>

          <div class="col-md-4">
            <label class="form-label" for="gtin2_number">GTIN2 (guruh / blok)</label>
            <input type="text" class="form-control" id="gtin2_number" name="gtin2_number">
          </div>

          <div class="col-md-4">
            <label class="form-label" for="product_image_file">Rasm *</label>
            <input
              type="file"
              class="form-control"
              id="product_image_file"
              name="product_image"
              accept="image/*"
            >
            <!-- Edit rejimi uchun eski rasm yo'li -->
            <input type="hidden" id="existing_image" name="existing_image" value="">

            <div class="mt-2">
              <img
                id="product_image_preview"
                src=""
                alt="Mahsulot rasmi"
                class="img-thumbnail d-none"
                style="max-height: 140px;"
              >
              <div
                id="product_image_placeholder"
                class="border rounded text-muted small text-center py-3"
              >
                Rasm tanlanmagan
              </div>
            </div>
            <div class="form-text">
              Yangi mahsulotda rasm majburiy. Tahrirlashda rasmni o‘zgartirish ixtiyoriy.
            </div>
          </div>

          <div class="col-md-4">
            <label class="form-label">Generate type *</label>
            <div class="form-check">
              <input class="form-check-input" type="radio" name="generate_type" id="gen_manual" value="manual" checked>
              <label class="form-check-label" for="gen_manual">
                Manual (guruh kodni skaner orqali kiritish)
              </label>
            </div>
            <div class="form-check mt-1">
              <input class="form-check-input" type="radio" name="generate_type" id="gen_auto" value="auto">
              <label class="form-check-label" for="gen_auto">
                Auto (SSCC18 avtomatik generatsiya)
              </label>
            </div>
          </div>

          <div class="col-md-4">
            <label class="form-label d-block">Holat</label>
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" role="switch" id="is_active" name="is_active" checked>
              <label class="form-check-label" for="is_active">Faol (markirovka sahifasida ko‘rinadi)</label>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Bekor qilish</button>
        <button type="submit" class="btn btn-primary" id="btn-save">
          <i class="fa-solid fa-floppy-disk"></i> Saqlash
        </button>
      </div>
    </form>
  </div>
</div>

<!-- DELETE CONFIRM MODAL -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title"><i class="fa-solid fa-triangle-exclamation"></i> Mahsulotni o‘chirish</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p class="mb-2">Mazkur mahsulotni rostdan ham o‘chirmoqchimisiz?</p>
        <p class="fw-semibold" id="deleteProductName"></p>
        <input type="hidden" id="deleteProductId" value="">
        <div class="alert alert-warning mb-0 small">
          <i class="fa-solid fa-circle-info"></i>
          Eslatma: agar bu mahsulot markirovka loglarida ishlatilayotgan bo‘lsa, backendda cheklov qo‘yish tavsiya etiladi.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Bekor qilish</button>
        <button type="button" class="btn btn-danger" id="btn-confirm-delete">
          <i class="fa-solid fa-trash-can"></i> O‘chirish
        </button>
      </div>
    </div>
  </div>
</div>

<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>

<!-- jsPDF + autoTable + html2canvas (PDF / PNG / JPG uchun) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.8.1/jspdf.plugin.autotable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
  const apiUrl = '/mark2/api/products.php';

  let allProducts = [];
  let filteredProducts = [];
  let currentPage = 1;
  const perPage = 10;

  let productModal;
  let deleteModal;

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

  // Loader helperlari — majburan ko‘rsat / yashir
  function showLoader() {
    const el = document.getElementById('global-loader');
    if (!el) return;
    el.style.setProperty('display', 'flex', 'important');
    el.style.opacity = '1';
  }

  function hideLoader() {
    const el = document.getElementById('global-loader');
    if (!el) return;
    el.style.setProperty('display', 'none', 'important');
    el.style.opacity = '0';
  }

  // Rasm preview helperlari
  function updateImagePreviewFromUrl(url) {
  const $img = $('#product_image_preview');
  const $ph  = $('#product_image_placeholder');

  if (url) {
    // boshiga /mark2/ qo‘shamiz
    const finalUrl = '/mark2/' + url.replace(/^\/+/, ''); // agar url boshida / bo'lsa, olib tashlaydi

    $img.attr('src', finalUrl).removeClass('d-none');
    $ph.addClass('d-none');
  } else {
    $img.attr('src', '').addClass('d-none');
    $ph.removeClass('d-none');
  }
}


  function updateImagePreviewFromFile(input) {
    const file = input.files && input.files[0];
    const $img = $('#product_image_preview');
    const $ph  = $('#product_image_placeholder');

    if (!file) {
      // Fayl tanlanmasa, eski previewni buzmaymiz
      return;
    }

    const reader = new FileReader();
    reader.onload = function (e) {
      $img.attr('src', e.target.result).removeClass('d-none');
      $ph.addClass('d-none');
    };
    reader.readAsDataURL(file);
  }

  $(function () {
    productModal = new bootstrap.Modal(document.getElementById('productModal'));
    deleteModal  = new bootstrap.Modal(document.getElementById('deleteModal'));

    // Fayl tanlanganda preview yangilash
    $('#product_image_file').on('change', function () {
      updateImagePreviewFromFile(this);
    });

    loadProducts();

    $('#btn-open-create').on('click', function () {
      resetForm();
      $('#productModalLabel').text('Yangi mahsulot qo‘shish');
      productModal.show();
    });

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

    $('#btn-confirm-delete').on('click', function () {
      confirmDelete();
    });

    // Filterlar
    $('#filter_category, #filter_generate, #filter_status').on('change', function () {
      safeApplyFilters();
    });

    // Search
    $('#search').on('input', function () {
      safeApplyFilters();
    });
  });

  // ==== Mahsulotlarni yuklash ====
  function loadProducts() {
    $('#products-table tbody').html(
      '<tr><td colspan="10" class="text-center py-3 text-muted">Yuklanmoqda...</td></tr>'
    );

    showLoader();

    $.ajax({
      url: apiUrl,
      method: 'GET',
      dataType: 'json',
      data: { action: 'list' }
    })
      .done(function (res) {
        if (!res || typeof res !== 'object') {
          toastr.error('Noto‘g‘ri server javobi (JSON emas)');
          $('#products-table tbody').html(
            '<tr><td colspan="10" class="text-center py-3 text-danger">Serverdan noto‘g‘ri javob keldi</td></tr>'
          );
          return;
        }

        if (res.status !== 'ok') {
          toastr.error(res.message || 'Xatolik');
          $('#products-table tbody').html(
            '<tr><td colspan="10" class="text-center py-3 text-danger">Ma’lumot yuklab bo‘lmadi</td></tr>'
          );
          return;
        }

        if (!Array.isArray(res.products)) {
          toastr.error('Serverdan noto‘g‘ri formatdagi "products" keldi');
          $('#products-table tbody').html(
            '<tr><td colspan="10" class="text-center py-3 text-danger">Ma’lumot formati xato</td></tr>'
          );
          return;
        }

        allProducts = res.products;
        safeApplyFilters();
      })
      .fail(function () {
        toastr.error('Mahsulotlarni yuklashda xatolik');
        $('#products-table tbody').html(
          '<tr><td colspan="10" class="text-center py-3 text-danger">Server xatosi yoki API topilmadi</td></tr>'
        );
      })
      .always(function () {
        hideLoader();
      });
  }

  // try/catch bilan filter
  function safeApplyFilters() {
    try {
      applyFilters();
    } catch (e) {
      console.error('applyFilters error:', e);
      toastr.error('Front-end xatolik (filterlash)');
      $('#products-table tbody').html(
        '<tr><td colspan="10" class="text-center py-3 text-danger">Front-end xatolik (filterlash)</td></tr>'
      );
      $('#pagination').empty();
      $('#pagination-info').text('');
    }
  }

  function applyFilters() {
    const catFilter   = $('#filter_category').val();
    const genFilter   = $('#filter_generate').val();
    const statFilter  = $('#filter_status').val();
    const searchQuery = ($('#search').val() || '').toLowerCase();

    if (!Array.isArray(allProducts)) {
      allProducts = [];
    }

    filteredProducts = allProducts.filter(p => {
      if (catFilter && String(p.category_id) !== String(catFilter)) return false;
      if (genFilter && String(p.generate_type) !== String(genFilter)) return false;
      if (statFilter !== '' && String(p.is_active) !== String(statFilter)) return false;

      if (searchQuery) {
        const txt = (
          (p.name || '') + ' ' +
          (p.category_name || '') + ' ' +
          (p.gtin_number || '') + ' ' +
          (p.gtin2_number || '')
        ).toLowerCase();
        if (txt.indexOf(searchQuery) === -1) return false;
      }
      return true;
    });

    currentPage = 1;
    renderTablePageSafe();
  }

  function renderTablePageSafe() {
    try {
      renderTablePage();
    } catch (e) {
      console.error('renderTablePage error:', e);
      toastr.error('Front-end xatolik (jadval)');
      $('#products-table tbody').html(
        '<tr><td colspan="10" class="text-center py-3 text-danger">Front-end xatolik (jadval)</td></tr>'
      );
      $('#pagination').empty();
      $('#pagination-info').text('');
    }
  }

  function renderTablePage() {
    const tbody = $('#products-table tbody');
    const total = Array.isArray(filteredProducts) ? filteredProducts.length : 0;

    if (!total) {
      tbody.html('<tr><td colspan="10" class="text-center py-3 text-muted">Mahsulotlar topilmadi</td></tr>');
      $('#pagination').empty();
      $('#pagination-info').text('0 ta mahsulot');
      return;
    }

    const totalPages = Math.ceil(total / perPage);
    if (currentPage > totalPages) currentPage = totalPages;

    const start = (currentPage - 1) * perPage;
    const end   = start + perPage;
    const pageItems = filteredProducts.slice(start, end);

    let html = '';
    pageItems.forEach(p => {
      const genBadge = p.generate_type === 'auto'
        ? '<span class="badge bg-success-subtle text-success badge-status"><i class="fa-solid fa-robot"></i> auto</span>'
        : '<span class="badge bg-primary-subtle text-primary badge-status"><i class="fa-solid fa-hand"></i> manual</span>';

      const activeBadge = p.is_active == 1
        ? '<span class="badge bg-success-subtle text-success badge-status">faol</span>'
        : '<span class="badge bg-secondary-subtle text-secondary badge-status">no-faol</span>';

      const imgHtml = p.product_image
        ? `<img src="/mark2/${escapeHtml(p.product_image)}" class="product-img-thumb" alt="">`
        : `<div class="product-img-thumb d-flex align-items-center justify-content-center text-muted">
            <i class="fa-regular fa-image"></i>
           </div>`;

      html += `
        <tr data-id="${p.id}">
          <td>${p.id}</td>
          <td>${escapeHtml(p.category_name || '-')}</td>
          <td>
            <div class="d-flex align-items-center gap-2">
              ${imgHtml}
              <div>
                <div>${escapeHtml(p.name || '')}</div>
                <div class="text-muted small">ID: ${p.id}</div>
              </div>
            </div>
          </td>
          <td>${p.product_block_unit}</td>
          <td><code>${escapeHtml(p.gtin_number || '')}</code></td>
          <td><code>${escapeHtml(p.gtin2_number || '')}</code></td>
          <td>${genBadge}</td>
          <td>${activeBadge}</td>
          <td class="small text-muted">${escapeHtml(p.created_at || '')}</td>
          <td class="text-end">
            <div class="btn-group btn-group-sm">
              <button type="button" data-permission="products.edit" class="btn btn-outline-primary" onclick="editProduct(${p.id})">
                <i class="fa-regular fa-pen-to-square" data-permission="products.edit"></i>
              </button>
              <button type="button" class="btn btn-outline-secondary" onclick="toggleProduct(${p.id})">
                ${p.is_active == 1
                  ? '<i class="fa-solid fa-eye-slash"></i>'
                  : '<i class="fa-solid fa-eye"></i>'
                }
              </button>
              <button type="button" class="btn btn-outline-danger" onclick="openDeleteModal(${p.id})">
                <i class="fa-solid fa-trash-can"></i>
              </button>
            </div>
          </td>
        </tr>
      `;
    });
    tbody.html(html);

    $('#pagination-info').text(
      `${total} ta mahsulotdan ${start + 1}–${Math.min(end, total)} oralig‘i`
    );

    renderPagination(totalPages);
  }

  function renderPagination(totalPages) {
    const ul = $('#pagination');
    ul.empty();
    if (totalPages <= 1) return;

    function pageItem(page, label = null, disabled = false, active = false) {
      label = label || page;
      const liClass = 'page-item' + (disabled ? ' disabled' : '') + (active ? ' active' : '');
      const btn = `<button class="page-link" type="button" ${disabled ? 'tabindex="-1"' : ''}>${label}</button>`;
      const $li = $(`<li class="${liClass}"></li>`).append(btn);
      if (!disabled && !active) {
        $li.on('click', function () {
          currentPage = page;
          renderTablePageSafe();
        });
      }
      ul.append($li);
    }

    // Prev
    pageItem(currentPage - 1, '&laquo;', currentPage === 1, false);

    for (let i = 1; i <= totalPages; i++) {
      if (
        i === 1 ||
        i === totalPages ||
        (i >= currentPage - 1 && i <= currentPage + 1)
      ) {
        pageItem(i, i, false, i === currentPage);
      } else if (
        (i === 2 && currentPage > 3) ||
        (i === totalPages - 1 && currentPage < totalPages - 2)
      ) {
        const li = $('<li class="page-item disabled"><span class="page-link">…</span></li>');
        ul.append(li);
      }
    }

    // Next
    pageItem(currentPage + 1, '&raquo;', currentPage === totalPages, false);
  }

  // ==== Saqlash (create/update) ====
  function saveProduct() {
    const id        = $('#product_id').val();
    const category_id        = $('#category_id').val();
    const name               = $('#name').val();
    const product_block_unit = $('#product_block_unit').val();
    const gtin_number        = $('#gtin_number').val();

    if (!category_id || !name || !product_block_unit || !gtin_number) {
      toastr.error('Kategoriya, nomi, blok unit va GTIN majburiy.');
      return;
    }

    const fileInput = document.getElementById('product_image_file');
    const hasFile   = fileInput && fileInput.files && fileInput.files[0];

    // Yangi mahsulot uchun rasm fayli majburiy
    if (!id && !hasFile) {
      toastr.error('Yangi mahsulot uchun rasm faylini tanlang.');
      return;
    }

    const formEl   = document.getElementById('product-form');
    const formData = new FormData(formEl);
    formData.append('action', 'save');

    $('#btn-save').prop('disabled', true);
    showLoader();

    $.ajax({
      url: apiUrl,
      method: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json'
    }).done(function (res) {
      if (!res || typeof res !== 'object') {
        toastr.error('Noto‘g‘ri server javobi');
        return;
      }
      if (res.status !== 'ok') {
        toastr.error(res.message || 'Saqlashda xatolik');
        return;
      }
      toastr.success(res.message || 'Saqlangan');
      productModal.hide();
      loadProducts();
    }).fail(function () {
      toastr.error('Server xatosi');
    }).always(function () {
      $('#btn-save').prop('disabled', false);
      hideLoader();
    });
  }

  function editProduct(id) {
    const p = allProducts.find(x => Number(x.id) === Number(id));
    if (!p) {
      toastr.error('Mahsulot topilmadi');
      return;
    }

    $('#product_id').val(p.id);
    $('#category_id').val(p.category_id);
    $('#name').val(p.name);
    $('#product_block_unit').val(p.product_block_unit);
    $('#gtin_number').val(p.gtin_number);
    $('#gtin2_number').val(p.gtin2_number);

    // Eski rasm yo'lini hiddenga yozamiz
    $('#existing_image').val(p.product_image || '');

    // Fayl inputni tozalaymiz
    $('#product_image_file').val('');
    // Previewni yangilaymiz
    updateImagePreviewFromUrl(p.product_image || '');

    $('input[name="generate_type"][value="' + (p.generate_type || 'manual') + '"]').prop('checked', true);
    $('#is_active').prop('checked', p.is_active == 1);

    $('#productModalLabel').text('Mahsulotni tahrirlash');
    productModal.show();
  }

  function toggleProduct(id) {
    showLoader();
    $.ajax({
      url: apiUrl,
      method: 'POST',
      dataType: 'json',
      data: { action: 'toggle', id: id }
    })
      .done(function (res) {
        if (!res || typeof res !== 'object') {
          toastr.error('Noto‘g‘ri server javobi');
          return;
        }
        if (res.status !== 'ok') {
          toastr.error(res.message || 'Xatolik');
          return;
        }
        toastr.info('Mahsulot holati yangilandi');
        loadProducts();
      })
      .fail(function () {
        toastr.error('Server xatosi (toggle)');
      })
      .always(function () {
        hideLoader();
      });
  }

  function openDeleteModal(id) {
    const p = Array.isArray(allProducts)
      ? allProducts.find(x => Number(x.id) === Number(id))
      : null;
    if (!p) {
      toastr.error('Mahsulot topilmadi');
      return;
    }
    $('#deleteProductId').val(p.id);
    $('#deleteProductName').text(p.name + ' (ID: ' + p.id + ')');
    deleteModal.show();
  }

  function confirmDelete() {
    const id = $('#deleteProductId').val();
    if (!id) return;

    $('#btn-confirm-delete').prop('disabled', true);
    showLoader();

    $.ajax({
      url: apiUrl,
      method: 'POST',
      dataType: 'json',
      data: { action: 'delete', id: id }
    })
      .done(function (res) {
        if (!res || typeof res !== 'object') {
          toastr.error('Noto‘g‘ri server javobi');
          return;
        }
        if (res.status !== 'ok') {
          if (res.code === 'product_used') {
            toastr.error(res.message || 'Mahsulot boshqa joyda ishlatilgan, o‘chirib bo‘lmaydi');
          } else {
            toastr.error(res.message || 'O‘chirishda xatolik');
          }
          return;
        }
        toastr.success('Mahsulot o‘chirildi');
        deleteModal.hide();
        loadProducts();
      })
      .fail(function () {
        toastr.error('Server xatosi (delete)');
      })
      .always(function () {
        $('#btn-confirm-delete').prop('disabled', false);
        hideLoader();
      });
  }

  function resetForm() {
    $('#product_id').val('');
    $('#product-form')[0].reset();
    $('#is_active').prop('checked', true);
    $('#gen_manual').prop('checked', true);

    $('#existing_image').val('');
    $('#product_image_file').val('');
    updateImagePreviewFromUrl('');
  }

  // ---- EXPORT FUNKSIYALAR ----

  function getExportData() {
    const header = [
      'ID',
      'Kategoriya',
      'Mahsulot',
      'BlokUnit',
      'GTIN',
      'GTIN2',
      'GenerateType',
      'Holat',
      'CreatedAt'
    ];

    const rows = (Array.isArray(filteredProducts) ? filteredProducts : []).map(p => ([
      p.id,
      p.category_name || '',
      p.name || '',
      p.product_block_unit || '',
      p.gtin_number || '',
      p.gtin2_number || '',
      p.generate_type || '',
      p.is_active == 1 ? 'faol' : 'no-faol',
      p.created_at || ''
    ]));

    return { header, rows };
  }

  function exportData(format) {
    if (!filteredProducts || !filteredProducts.length) {
      toastr.warning('Export qilish uchun mahsulot topilmadi');
      return;
    }
    const now = new Date();
    const ts = now.toISOString().slice(0,19).replace(/[:T]/g, '-');
    const fileBase = `products_export_${ts}`;

    switch (format) {
      case 'csv':
        exportCsv(fileBase + '.csv');
        break;
      case 'xls':
        exportExcelLike(fileBase + '.xls', 'application/vnd.ms-excel');
        break;
      case 'xlsx':
        exportExcelLike(fileBase + '.xlsx',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        break;
      case 'pdf':
        exportPdf(fileBase + '.pdf');
        break;
      case 'doc':
        exportDoc(fileBase + '.doc');
        break;
      case 'png':
        exportImage(fileBase + '.png', 'image/png');
        break;
      case 'jpg':
      case 'jpeg':
        exportImage(fileBase + '.jpg', 'image/jpeg');
        break;
    }
  }

  function exportCsv(filename) {
    const { header, rows } = getExportData();
    let csv = '';
    csv += header.join(';') + '\n';
    rows.forEach(r => {
      const line = r.map(v => {
        const s = String(v ?? '');
        if (s.includes(';') || s.includes('"') || s.includes('\n')) {
          return '"' + s.replace(/"/g, '""') + '"';
        }
        return s;
      }).join(';');
      csv += line + '\n';
    });

    const blob = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
    downloadBlob(blob, filename);
  }

  function exportExcelLike(filename, mimeType) {
    const { header, rows } = getExportData();
    let html = '<table border="1"><thead><tr>';
    header.forEach(h => {
      html += '<th>' + escapeHtml(h) + '</th>';
    });
    html += '</tr></thead><tbody>';
    rows.forEach(r => {
      html += '<tr>';
      r.forEach(v => {
        html += '<td>' + escapeHtml(String(v ?? '')) + '</td>';
      });
      html += '</tr>';
    });
    html += '</tbody></table>';

    const blob = new Blob([html], {type: mimeType});
    downloadBlob(blob, filename);
  }

  function exportDoc(filename) {
    const { header, rows } = getExportData();
    let tableHtml = '<table border="1" style="border-collapse:collapse;width:100%;">';
    tableHtml += '<thead><tr>';
    header.forEach(h => {
      tableHtml += '<th style="padding:4px;">' + escapeHtml(h) + '</th>';
    });
    tableHtml += '</tr></thead><tbody>';
    rows.forEach(r => {
      tableHtml += '<tr>';
      r.forEach(v => {
        tableHtml += '<td style="padding:4px;">' + escapeHtml(String(v ?? '')) + '</td>';
      });
      tableHtml += '</tr>';
    });
    tableHtml += '</tbody></table>';

    const html =
      '<html><head><meta charset="utf-8"></head><body>' +
      '<h3>Mahsulotlar eksporti</h3>' +
      tableHtml +
      '</body></html>';

    const blob = new Blob([html], {type: 'application/msword'});
    downloadBlob(blob, filename);
  }

  function exportPdf(filename) {
    const { header, rows } = getExportData();
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF('l', 'pt', 'a4');

    doc.setFontSize(14);
    doc.text('Mahsulotlar eksporti', 40, 40);

    doc.autoTable({
      head: [header],
      body: rows,
      startY: 60,
      margin: { left: 40, right: 40 },
      styles: { fontSize: 8 }
    });

    doc.save(filename);
  }

  function exportImage(filename, mime) {
    const node = document.getElementById('export-area');
    html2canvas(node, {scale: 2}).then(canvas => {
      canvas.toBlob(function (blob) {
        if (!blob) {
          toastr.error('Rasm generatsiyada xatolik');
          return;
        }
        downloadBlob(blob, filename);
      }, mime, 0.95);
    }).catch(() => {
      toastr.error('Rasm generatsiyada xatolik');
    });
  }

  function downloadBlob(blob, filename) {
    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);
  }

  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>
