<?php
require_once __DIR__ . '/includes/db.php';

$pageTitle  = 'Labeluri printabile';
$breadcrumb = [['label' => 'Labeluri printabile']];

$filterAccount = active_account_id();
$id = (int)($_GET['id'] ?? 0); // opțional: preselectează produsele dintr-o sesiune de recepție
$labelTitle = setting_get('fbe_label_title', 'Folie Sticlă Securizată') ?? '';

$products = [];
$preselectEans = [];
$dbError  = null;

try {
    $where  = ['p.emag_offer_status = 1'];
    $params = [];
    if ($filterAccount > 0) { $where[] = 'p.emag_account_id = ?'; $params[] = $filterAccount; }
    $whereSql = implode(' AND ', $where);

    $products = db_select(
        "SELECT p.id, p.ean, p.pnk, p.product_name, p.custom_name,
                (SELECT pb.name || ' ' || pm.name || ' ' || ps.name
                 FROM phone_series ps
                 JOIN phone_models pm ON pm.id = ps.model_id
                 JOIN phone_brands pb ON pb.id = pm.brand_id
                 WHERE ps.id = p.phone_series_id) AS phone_label,
                (SELECT GROUP_CONCAT(pb.name || ' ' || pm.name || ' ' || ps.name, ', ')
                 FROM product_phone_series_alt a
                 JOIN phone_series ps ON ps.id = a.phone_series_id
                 JOIN phone_models pm ON pm.id = ps.model_id
                 JOIN phone_brands pb ON pb.id = pm.brand_id
                 WHERE a.product_id = p.id) AS alt_labels
         FROM products p
         WHERE $whereSql
         ORDER BY (p.custom_name IS NULL), p.custom_name COLLATE NOCASE, p.product_name COLLATE NOCASE",
        $params
    );

    if ($id > 0) {
        $preselectEans = array_column(
            db_select("SELECT DISTINCT ean FROM fbe_reception_items WHERE reception_id = ? AND ean IS NOT NULL AND qty > 0", [$id]),
            'ean'
        );
    }
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

require __DIR__ . '/includes/header.php';
?>

<!-- JsBarcode pentru generarea codurilor de bare -->
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>

<style>
  .label {
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    box-sizing: border-box; padding: 1mm; overflow: hidden; background: #fff;
    border: 1px dashed #cbd5e1;
  }
  .label svg { max-width: 100%; height: auto; }
  .label-name  { font-size: 8px; line-height: 1.1; text-align: center; margin-top: 0.5mm; color: #334155; }
  .label-title { font-size: 9px; font-weight: 700; line-height: 1.1; text-align: center; margin-top: 0.5mm; color: #0f172a; }
  .label-phone { font-size: 9px; font-weight: 700; line-height: 1.1; text-align: center; margin-top: 0.3mm; color: #0f172a; }
  @media print {
    body * { visibility: hidden !important; }
    #labelArea, #labelArea * { visibility: visible !important; }
    #labelArea { position: absolute; left: 0; top: 0; margin: 0; padding: 0; gap: 0 !important; }
    .label { border: none !important; page-break-after: always; break-after: page; }
    .label:last-child { page-break-after: auto; break-after: auto; }
  }
</style>

<?php if ($dbError): ?>
  <div class="mb-6 bg-amber-50 border border-amber-200 rounded-xl p-4 text-sm text-amber-900">
    Eroare DB. <details class="mt-2"><summary class="cursor-pointer">Detalii</summary><pre class="mt-2 text-xs"><?= e($dbError) ?></pre></details>
  </div>
<?php endif; ?>

<div
  x-data="labelsPage({
    products: <?= htmlspecialchars(json_encode($products), ENT_QUOTES, 'UTF-8') ?>,
    preselectEans: <?= htmlspecialchars(json_encode($preselectEans), ENT_QUOTES, 'UTF-8') ?>,
    labelTitle: <?= htmlspecialchars(json_encode($labelTitle), ENT_QUOTES, 'UTF-8') ?>
  })"
  x-init="init()"
>
  <!-- @page-ul de print (dimensiunea labelului) — actualizat din JS -->
  <style x-ref="pageCss"></style>

  <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6 no-print">
    <div>
      <h1 class="text-2xl font-bold text-slate-900">Labeluri printabile</h1>
      <p class="text-sm text-slate-500 mt-0.5"><span x-text="selectedIds.length"></span> labeluri selectate</p>
    </div>
    <button @click="print()" :disabled="selectedIds.length === 0"
      class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg shadow-soft transition disabled:opacity-50 disabled:cursor-not-allowed">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
      Printează (<span x-text="selectedIds.length"></span>)
    </button>
  </div>

  <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">

    <!-- ====== Setări + selecție produse ====== -->
    <div class="lg:col-span-2 space-y-4 no-print">
      <!-- Setări label -->
      <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-4">
        <h2 class="font-semibold text-slate-900 mb-3">Dimensiune label termal</h2>
        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Lățime (mm)</label>
            <input type="number" min="10" max="200" step="1" x-model.number="widthMm" @change="reRender()"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 tabular-nums">
          </div>
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Înălțime (mm)</label>
            <input type="number" min="10" max="200" step="1" x-model.number="heightMm" @change="reRender()"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 tabular-nums">
          </div>
        </div>
        <div class="mt-2 flex flex-wrap gap-1.5">
          <template x-for="preset in presets" :key="preset.w + 'x' + preset.h">
            <button @click="widthMm = preset.w; heightMm = preset.h; reRender()"
              class="px-2 py-1 text-xs border border-slate-200 rounded hover:bg-slate-50 transition"
              x-text="preset.w + '×' + preset.h"></button>
          </template>
        </div>

        <div class="grid grid-cols-2 gap-3 mt-4">
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Cod de bare din</label>
            <select x-model="encode" @change="reRender()"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 bg-white">
              <option value="ean">EAN</option>
              <option value="pnk">PNK</option>
            </select>
          </div>
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Înălțime cod (px)</label>
            <input type="number" min="15" max="120" step="1" x-model.number="barHeight" @change="reRender()"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 tabular-nums">
          </div>
        </div>
        <div class="mt-3 flex flex-wrap gap-4">
          <label class="inline-flex items-center gap-2 text-sm text-slate-700 cursor-pointer">
            <input type="checkbox" x-model="showValue" @change="reRender()" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500">
            Arată codul (cifre)
          </label>
          <label class="inline-flex items-center gap-2 text-sm text-slate-700 cursor-pointer">
            <input type="checkbox" x-model="showName" @change="reRender()" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500">
            Arată numele
          </label>
        </div>
      </div>

      <!-- Selecție produse -->
      <div class="bg-white border border-slate-100 rounded-xl shadow-soft flex flex-col">
        <div class="px-4 py-3 border-b border-slate-100">
          <div class="flex items-center justify-between gap-2 mb-2">
            <h2 class="font-semibold text-slate-900">Produse</h2>
            <div class="flex gap-2 text-xs">
              <button @click="selectAllFiltered()" class="text-brand-600 hover:text-brand-700">Toate (filtrate)</button>
              <span class="text-slate-300">·</span>
              <button @click="clearSelection()" class="text-slate-500 hover:text-slate-700">Niciunul</button>
            </div>
          </div>
          <div class="relative">
            <svg class="w-4 h-4 absolute left-3 top-2.5 text-slate-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            <input type="text" x-model="search" placeholder="Caută după nume, EAN, PNK, model…" autocomplete="off"
              class="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
          </div>
        </div>
        <ul class="max-h-[60vh] overflow-y-auto divide-y divide-slate-100">
          <template x-if="filtered().length === 0">
            <li class="px-4 py-8 text-center text-slate-400 text-sm">Niciun produs.</li>
          </template>
          <template x-for="p in filtered()" :key="p.id">
            <li class="px-4 py-2.5 hover:bg-slate-50 transition">
              <label class="flex items-start gap-2.5 cursor-pointer">
                <input type="checkbox" :value="p.id" x-model.number="selectedIds"
                  class="mt-0.5 rounded border-slate-300 text-brand-600 focus:ring-brand-500">
                <div class="min-w-0">
                  <div class="text-sm text-slate-800 leading-snug" x-text="shortName(displayName(p))"></div>
                  <div class="text-[11px] text-slate-400 font-mono mt-0.5 flex flex-wrap gap-x-3">
                    <span x-show="p.ean" x-text="'EAN ' + p.ean"></span>
                    <span x-show="p.pnk" x-text="'PNK ' + p.pnk"></span>
                  </div>
                  <div class="text-[11px] text-sky-700 mt-0.5" x-show="compatLabel(p)" x-text="compatLabel(p)"></div>
                </div>
              </label>
            </li>
          </template>
        </ul>
      </div>
    </div>

    <!-- ====== Preview / zonă de print ====== -->
    <div class="lg:col-span-3">
      <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-4 no-print mb-3">
        <div class="text-sm text-slate-500">
          Previzualizare label <span class="font-medium text-slate-700" x-text="widthMm + '×' + heightMm + ' mm'"></span>.
          La print, fiecare label e o pagină separată (setat pe dimensiunea aleasă).
        </div>
      </div>

      <template x-if="selectedItems().length === 0">
        <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-10 text-center text-slate-400 no-print">
          Selectează produse din stânga ca să generezi labelurile.
        </div>
      </template>

      <!-- Zona efectiv printată -->
      <div id="labelArea" class="flex flex-wrap gap-2">
        <template x-for="p in selectedItems()" :key="'label-' + p.id">
          <div class="label" :style="`width:${widthMm}mm; height:${heightMm}mm`">
            <svg :id="'bc-' + p.id"></svg>
            <div class="label-name" x-show="showName" x-text="shortName(displayName(p), 40)"></div>
            <div class="label-title" x-show="labelTitle" x-text="labelTitle"></div>
            <div class="label-phone" x-text="compatLabel(p) || '—'"></div>
          </div>
        </template>
      </div>
    </div>
  </div>
</div>

<script>
function labelsPage({ products, preselectEans, labelTitle }) {
  return {
    products: products || [],
    preselectEans: preselectEans || [],
    labelTitle: labelTitle || '',
    search: '',
    selectedIds: [],
    widthMm: 40,
    heightMm: 30,
    barHeight: 38,
    encode: 'ean',
    showValue: true,
    showName: true,
    presets: [
      { w: 40, h: 30 }, { w: 50, h: 30 }, { w: 58, h: 40 }, { w: 60, h: 40 }, { w: 100, h: 50 },
    ],

    init() {
      if (this.preselectEans.length) {
        const set = new Set(this.preselectEans.map(e => String(e).trim()));
        this.selectedIds = this.products.filter(p => p.ean && set.has(String(p.ean).trim())).map(p => p.id);
      }
      this.updatePageCss();
      // Re-randează codurile de bare când se schimbă selecția.
      this.$watch('selectedIds', () => this.reRender());
      this.reRender();
    },

    displayName(p) { return p.custom_name || p.product_name || ''; },
    shortName(s, n) {
      n = n || 60;
      s = (s || '').toString();
      return s.length > n ? s.slice(0, n) + '…' : s;
    },
    compatLabel(p) {
      return [p.phone_label, p.alt_labels].filter(Boolean).join(', ');
    },
    barcodeValue(p) {
      return ((this.encode === 'pnk' ? p.pnk : p.ean) || '').toString().trim();
    },

    filtered() {
      const q = this.search.trim().toLowerCase();
      if (!q) return this.products;
      return this.products.filter(p =>
        (p.ean || '').toLowerCase().includes(q) ||
        (p.pnk || '').toLowerCase().includes(q) ||
        (this.displayName(p)).toLowerCase().includes(q) ||
        (this.compatLabel(p)).toLowerCase().includes(q)
      );
    },
    selectAllFiltered() {
      const ids = new Set(this.selectedIds);
      this.filtered().forEach(p => ids.add(p.id));
      this.selectedIds = [...ids];
    },
    clearSelection() { this.selectedIds = []; },
    selectedItems() { return this.products.filter(p => this.selectedIds.includes(p.id)); },

    updatePageCss() {
      if (this.$refs.pageCss) {
        this.$refs.pageCss.textContent =
          '@media print { @page { size: ' + this.widthMm + 'mm ' + this.heightMm + 'mm; margin: 0; } }';
      }
    },
    // Regenerează toate codurile de bare după ce DOM-ul s-a actualizat.
    reRender() {
      this.updatePageCss();
      this.$nextTick(() => {
        for (const p of this.selectedItems()) {
          const el = document.getElementById('bc-' + p.id);
          if (!el) continue;
          const val = this.barcodeValue(p);
          if (!val) { el.innerHTML = ''; continue; }
          let fmt = 'CODE128';
          if (/^\d{13}$/.test(val)) fmt = 'EAN13';
          else if (/^\d{12}$/.test(val)) fmt = 'UPC';
          const opts = { format: fmt, height: this.barHeight, width: 1.4, displayValue: this.showValue, fontSize: 12, margin: 2 };
          try {
            JsBarcode(el, val, opts);
          } catch (e) {
            try { JsBarcode(el, val, { ...opts, format: 'CODE128' }); }
            catch (_) { el.innerHTML = ''; }
          }
        }
      });
    },
    print() {
      if (this.selectedIds.length === 0) return;
      this.reRender();
      this.$nextTick(() => setTimeout(() => window.print(), 100));
    }
  };
}
</script>

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