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

$pageTitle  = 'Generare recepție';
$breadcrumb = [['label' => 'Generare recepție']];

// Scopul = contul activ (selectat din header). 0 = toate conturile.
$filterAccount = active_account_id();

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

try {
    // Doar produsele ACTIVE pe eMAG (emag_offer_status = 1). La FBE trimitem
    // doar ofertele pornite. Sortăm întâi cele care au deja cantitate setată.
    $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.product_name, p.custom_name, p.pnk, p.fbe_qty,
                p.phone_series_id, p.units_per_box,
                (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,
                a.account_name
         FROM products p
         LEFT JOIN emag_accounts a ON a.id = p.emag_account_id
         WHERE $whereSql
         ORDER BY (p.fbe_qty IS NULL), (p.custom_name IS NULL), p.custom_name COLLATE NOCASE,
                  p.product_name COLLATE NOCASE",
        $params
    );

    // Sesiunile de recepție salvate (cu items atașate, în ordine).
    $receptions = db_select(
        "SELECT r.*,
                (SELECT COUNT(*) FROM fbe_reception_items WHERE reception_id = r.id) AS items_count,
                (SELECT COALESCE(SUM(qty),0) FROM fbe_reception_items WHERE reception_id = r.id) AS total_qty
         FROM fbe_receptions r
         ORDER BY r.created_at DESC"
    );
    if ($receptions) {
        $allItems = db_select(
            "SELECT reception_id, ean, qty, product_id, product_name
             FROM fbe_reception_items ORDER BY reception_id ASC, position ASC"
        );
        $byRec = [];
        foreach ($allItems as $it) {
            $byRec[(int)$it['reception_id']][] = [
                'ean' => $it['ean'], 'qty' => $it['qty'],
                'product_id' => $it['product_id'], 'product_name' => $it['product_name'],
            ];
        }
        foreach ($receptions as &$r) {
            $r['items'] = $byRec[(int)$r['id']] ?? [];
        }
        unset($r);
    }
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

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

<!-- SheetJS pentru generarea fișierului Excel (.xlsx) -->
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<?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="receptiePage({
    rows: <?= htmlspecialchars(json_encode($products), ENT_QUOTES, 'UTF-8') ?>,
    sessions: <?= htmlspecialchars(json_encode($receptions), ENT_QUOTES, 'UTF-8') ?>,
    accountId: <?= (int)$filterAccount ?>,
    csrf: '<?= e(csrf_token()) ?>'
  })"
>

  <!-- ================= VEDERE LISTĂ (istoric sesiuni) ================= -->
  <div x-show="view === 'list'">
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
      <div>
        <h1 class="text-2xl font-bold text-slate-900">Recepții FBE</h1>
        <p class="text-sm text-slate-500 mt-0.5"><span x-text="sessions.length"></span> sesiuni salvate</p>
      </div>
      <button @click="openNewSession()"
        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">
        <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="M12 4v16m8-8H4"/></svg>
        Generează sesiune nouă
      </button>
    </div>

    <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden">
      <div class="overflow-x-auto">
        <table class="text-sm w-full">
          <thead class="bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
            <tr class="divide-x divide-slate-200">
              <th class="px-3 py-2.5 text-left font-medium w-10">#</th>
              <th class="px-3 py-2.5 text-left font-medium">Nume</th>
              <th class="px-3 py-2.5 text-left font-medium whitespace-nowrap">Nr. recepție</th>
              <th class="px-3 py-2.5 text-right font-medium whitespace-nowrap">EAN-uri</th>
              <th class="px-3 py-2.5 text-right font-medium whitespace-nowrap">Total buc.</th>
              <th class="px-3 py-2.5 text-left font-medium whitespace-nowrap">Creată</th>
              <th class="px-3 py-2.5 text-right font-medium w-40">Acțiuni</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-slate-100">
            <template x-if="sessions.length === 0">
              <tr><td colspan="7" class="px-4 py-12 text-center text-slate-400">
                Nicio sesiune salvată încă. Apasă <span class="font-medium text-slate-600">„Generează sesiune nouă"</span> ca să începi.
              </td></tr>
            </template>
            <template x-for="(s, idx) in sessions" :key="s.id">
              <tr class="row-hover divide-x divide-slate-100">
                <td class="px-3 py-2.5 text-xs text-slate-400 font-mono tabular-nums" x-text="idx + 1"></td>
                <td class="px-3 py-2.5 text-slate-800 font-medium" x-text="s.name"></td>
                <td class="px-3 py-2.5">
                  <span x-show="s.reception_number" class="inline-block font-mono text-xs bg-slate-100 text-slate-700 px-1.5 py-0.5 rounded" x-text="s.reception_number"></span>
                  <span x-show="!s.reception_number" class="text-slate-300">—</span>
                </td>
                <td class="px-3 py-2.5 text-right tabular-nums text-slate-600" x-text="s.items_count"></td>
                <td class="px-3 py-2.5 text-right tabular-nums font-semibold text-slate-800" x-text="s.total_qty"></td>
                <td class="px-3 py-2.5 text-xs text-slate-500 whitespace-nowrap" x-text="formatDate(s.created_at)"></td>
                <td class="px-3 py-2.5 text-right whitespace-nowrap">
                  <a :href="'<?= url('impachetare.php') ?>?id=' + s.id" class="inline-block text-sky-600 hover:text-sky-700 p-1.5 rounded hover:bg-sky-50 transition" title="Pagina de împachetare">
                    <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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
                  </a>
                  <button @click="editSession(s)" class="text-brand-600 hover:text-brand-700 p-1.5 rounded hover:bg-brand-50 transition" title="Editează sesiunea">
                    <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="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                  </button>
                  <button @click="downloadSession(s)" class="text-emerald-700 hover:text-emerald-800 p-1.5 rounded hover:bg-emerald-50 transition" title="Descarcă Excel recepție">
                    <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="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 10l5 5 5-5M12 15V3"/></svg>
                  </button>
                  <button @click="downloadPacking(s)" class="text-indigo-600 hover:text-indigo-700 p-1.5 rounded hover:bg-indigo-50 transition" title="Descarcă Excel împachetare">
                    <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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/></svg>
                  </button>
                  <button @click="deleteSession(s)" class="text-rose-600 hover:text-rose-700 p-1.5 rounded hover:bg-rose-50 transition" title="Șterge sesiunea">
                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"/></svg>
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- ================= VEDERE EDITOR (tabel produse) ================= -->
  <div x-show="view === 'editor'" x-cloak>
    <!-- Header sesiune -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
      <div class="flex items-center gap-3 min-w-0">
        <button @click="backToList()" class="flex-shrink-0 inline-flex items-center justify-center w-9 h-9 text-slate-500 hover:text-brand-600 hover:bg-slate-100 rounded-lg transition" title="Înapoi la listă">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/></svg>
        </button>
        <div class="min-w-0">
          <h1 class="text-2xl font-bold text-slate-900 truncate">
            <span x-text="currentSession.id ? 'Editare sesiune' : 'Sesiune nouă'"></span>
          </h1>
          <p class="text-sm text-slate-500 mt-0.5 truncate">
            <span x-text="currentSession.name"></span>
            <span x-show="currentSession.reception_number"> · Nr. <span class="font-mono" x-text="currentSession.reception_number"></span></span>
          </p>
        </div>
      </div>
      <div class="flex items-center gap-2 flex-shrink-0">
        <button @click="editDetails()" class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-200 hover:bg-slate-50 rounded-lg shadow-soft transition" title="Editează nume / nr. recepție">
          <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="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
          Detalii
        </button>
        <a x-show="currentSession.id" :href="'<?= url('impachetare.php') ?>?id=' + currentSession.id"
          class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-sky-700 bg-sky-50 border border-sky-100 hover:bg-sky-100 rounded-lg shadow-soft transition" title="Deschide pagina de împachetare">
          <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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
          Împachetare
        </a>
        <button @click="generateExcel()" :disabled="parsedEans().length === 0"
          class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-200 hover:bg-slate-50 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="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 10l5 5 5-5M12 15V3"/></svg>
          Doar Excel
        </button>
        <button @click="generatePacking()" :disabled="parsedEans().length === 0"
          class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-indigo-700 bg-indigo-50 border border-indigo-100 hover:bg-indigo-100 rounded-lg shadow-soft transition disabled:opacity-50 disabled:cursor-not-allowed"
          title="Export pentru împachetare (nume + numărătoare, produsele legate grupate)">
          <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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/></svg>
          Împachetare
        </button>
        <button @click="saveSession()" :disabled="saving || parsedEans().length === 0"
          class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-lg shadow-soft transition disabled:opacity-50 disabled:cursor-not-allowed">
          <span x-show="saving" class="spinner"></span>
          <svg x-show="!saving" 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="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1-4l-4 4m0 0L8 3m4 4V3"/></svg>
          Salvează și descarcă
        </button>
      </div>
    </div>

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

      <!-- ============ STÂNGA: setare cantități per produs ============ -->
      <div class="lg:col-span-3 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-3">
            <h2 class="font-semibold text-slate-900">1. Câte bucăți trimitem la FBE</h2>
            <label class="inline-flex items-center gap-2 text-xs text-slate-600 cursor-pointer select-none">
              <input type="checkbox" x-model="onlyWithQty" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500">
              Doar cele cu cantitate
            </label>
          </div>
          <div class="relative mt-2">
            <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…" 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 focus:border-transparent">
          </div>
        </div>

        <div class="overflow-x-auto max-h-[70vh] overflow-y-auto">
          <table class="text-sm w-full">
            <thead class="bg-slate-50 text-xs uppercase tracking-wide text-slate-500 sticky top-0 z-10">
              <tr class="divide-x divide-slate-200">
                <th class="px-2 py-2.5 text-left font-medium w-10">#</th>
                <th class="px-3 py-2.5 text-left font-medium">Produs</th>
                <th class="px-3 py-2.5 text-left font-medium whitespace-nowrap">EAN</th>
                <th class="px-3 py-2.5 text-right font-medium w-28">Bucăți FBE</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
              <template x-if="filteredRows().length === 0">
                <tr><td colspan="4" class="px-4 py-12 text-center text-slate-400">Niciun produs activ nu corespunde căutării.</td></tr>
              </template>
              <template x-for="(p, idx) in filteredRows()" :key="p.id">
                <tr class="row-hover align-top divide-x divide-slate-100">
                  <td class="px-2 py-2 align-top text-xs text-slate-400 font-mono tabular-nums" x-text="idx + 1"></td>
                  <td class="px-3 py-2 align-top">
                    <div class="text-slate-800 break-words leading-snug"
                         :title="p.custom_name || p.product_name"
                         x-text="shortName(p.custom_name || p.product_name)"></div>
                    <div class="text-[10px] text-slate-400 font-mono mt-0.5" x-show="p.pnk" x-text="p.pnk"></div>
                  </td>
                  <td class="px-3 py-2 align-top">
                    <span class="font-mono text-xs text-slate-600" x-text="p.ean || '—'"></span>
                  </td>
                  <td class="px-3 py-2 align-top text-right">
                    <div class="inline-flex items-center gap-1.5 justify-end">
                      <input type="number" min="0" step="1"
                        :value="p.fbe_qty ?? ''"
                        @change="saveQty(p, $event.target.value)"
                        @keydown.enter.prevent="$event.target.blur()"
                        class="w-20 px-2 py-1 text-sm text-right border rounded focus:outline-none focus:ring-2 focus:ring-brand-500 tabular-nums"
                        :class="(p.fbe_qty != null && p.fbe_qty !== '') ? 'border-emerald-300 bg-emerald-50' : 'border-slate-200'">
                      <span x-show="savingIds.includes(p.id)" class="spinner"></span>
                    </div>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
      </div>

      <!-- ============ DREAPTA: listă EAN ============ -->
      <div class="lg:col-span-2 space-y-4">
        <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-4">
          <h2 class="font-semibold text-slate-900 mb-1">2. Lista de EAN-uri</h2>
          <p class="text-xs text-slate-500 mb-3">Lipește EAN-urile, unul sub altul. Ordinea din Excel va fi exact ordinea de aici.</p>
          <textarea x-model="eanInput" rows="12" spellcheck="false"
            placeholder="5901234567890&#10;4006381333931&#10;…"
            class="w-full px-3 py-2 text-sm font-mono border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 resize-y"></textarea>

          <!-- Sumar -->
          <div class="mt-3 grid grid-cols-3 gap-2 text-center">
            <div class="bg-slate-50 rounded-lg py-2">
              <div class="text-lg font-bold text-slate-800 tabular-nums" x-text="parsedEans().length"></div>
              <div class="text-[10px] uppercase tracking-wide text-slate-400">EAN-uri</div>
            </div>
            <div class="bg-emerald-50 rounded-lg py-2">
              <div class="text-lg font-bold text-emerald-700 tabular-nums" x-text="matchedCount()"></div>
              <div class="text-[10px] uppercase tracking-wide text-emerald-600">cu cantitate</div>
            </div>
            <div class="bg-amber-50 rounded-lg py-2">
              <div class="text-lg font-bold text-amber-700 tabular-nums" x-text="notFoundEans().length"></div>
              <div class="text-[10px] uppercase tracking-wide text-amber-600">fără / negăsite</div>
            </div>
          </div>

          <div class="mt-2 text-xs text-slate-500" x-show="parsedEans().length > 0">
            Total bucăți: <span class="font-semibold text-slate-700 tabular-nums" x-text="totalPieces()"></span>
          </div>
        </div>

        <!-- Avertisment EAN negăsite / fără cantitate -->
        <div x-show="notFoundEans().length > 0" x-cloak
             class="bg-amber-50 border border-amber-200 rounded-xl p-4 text-sm text-amber-900">
          <div class="font-medium mb-1.5"><span x-text="notFoundEans().length"></span> EAN-uri fără cantitate (rândul lor rămâne gol în Excel):</div>
          <ul class="max-h-40 overflow-y-auto font-mono text-xs space-y-0.5">
            <template x-for="ean in notFoundEans()" :key="ean">
              <li class="flex items-center gap-1.5">
                <span x-text="ean"></span>
                <span class="text-amber-500 text-[10px]" x-text="eanMap().has(ean) ? '(fără cantitate setată)' : '(negăsit în produse active)'"></span>
              </li>
            </template>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- ============ MODAL: detalii sesiune (id de sesiune) ============ -->
  <div x-show="detailsModalOpen" x-cloak @keydown.escape.window="detailsModalOpen = false"
       class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm"
       @mousedown.self="detailsModalOpen = false">
    <div class="modal-enter bg-white rounded-2xl shadow-2xl w-full max-w-md">
      <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
        <h3 class="font-semibold text-slate-900" x-text="detailsMode === 'new' ? 'Sesiune nouă de recepție' : 'Detalii sesiune'"></h3>
        <button type="button" @click="detailsModalOpen = false" class="text-slate-400 hover:text-slate-600 p-1">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
        </button>
      </div>
      <div class="p-6 space-y-4">
        <!-- Sesiune nouă: doar id-ul (numele se generează automat) -->
        <template x-if="detailsMode === 'new'">
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Id sesiune <span class="text-rose-500">*</span></label>
            <input type="text" x-model="formId" placeholder="ex: 241435" inputmode="numeric"
              @keydown.enter="confirmDetails()"
              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 font-mono">
            <p class="text-[11px] text-slate-400 mt-1">
              Numele se generează automat: <span class="font-medium text-slate-500" x-text="formId.trim() ? autoName(formId.trim()) : 'Recepție <id> · ' + new Date().toLocaleDateString('ro-RO')"></span>
            </p>
          </div>
        </template>
        <!-- Editare detalii: nume + nr. recepție -->
        <template x-if="detailsMode === 'edit'">
          <div class="space-y-4">
            <div>
              <label class="block text-xs font-medium text-slate-700 mb-1">Nume sesiune <span class="text-rose-500">*</span></label>
              <input type="text" x-model="formName" @keydown.enter="confirmDetails()"
                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">
            </div>
            <div>
              <label class="block text-xs font-medium text-slate-700 mb-1">Nr. recepție</label>
              <input type="text" x-model="formRecNumber" placeholder="ex: 241435"
                @keydown.enter="confirmDetails()"
                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 font-mono">
              <p class="text-[11px] text-slate-400 mt-1">Apare în Excel (numele fișierului).</p>
            </div>
          </div>
        </template>
      </div>
      <div class="px-6 py-4 border-t border-slate-100 flex items-center justify-end gap-2">
        <button type="button" @click="detailsModalOpen = false" class="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-800 transition">Anulează</button>
        <button type="button" @click="confirmDetails()"
          :disabled="detailsMode === 'new' ? formId.trim() === '' : formName.trim() === ''"
          class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
          x-text="detailsMode === 'new' ? 'Continuă' : 'Salvează detaliile'"></button>
      </div>
    </div>
  </div>
</div>

<script>
function receptiePage({ rows, sessions, accountId, csrf }) {
  return {
    rows: rows || [],
    sessions: sessions || [],
    accountId: accountId || 0,
    csrf,
    view: 'list',                 // 'list' | 'editor'
    currentSession: { id: 0, name: '', reception_number: '' },
    search: '',
    onlyWithQty: false,
    savingIds: [],
    eanInput: '',
    saving: false,
    // modal detalii
    detailsModalOpen: false,
    detailsMode: 'new',           // 'new' | 'edit'
    formId: '',                   // id-ul introdus la sesiune nouă (ex: 241435)
    formName: '',
    formRecNumber: '',

    // ---- navigare vederi ----
    // Sesiune nouă: întrebăm id-ul sesiunii (ex: 241435); numele îl generăm automat.
    openNewSession() {
      this.detailsMode = 'new';
      this.formId = '';
      this.detailsModalOpen = true;
    },
    editDetails() {
      this.detailsMode = 'edit';
      this.formName = this.currentSession.name;
      this.formRecNumber = this.currentSession.reception_number || '';
      this.detailsModalOpen = true;
    },
    // Numele generat automat din id-ul sesiunii + data de azi. Ex: „Recepție 241435 · 15.06.2026".
    autoName(id) {
      return 'Recepție ' + id + ' · ' + new Date().toLocaleDateString('ro-RO');
    },
    confirmDetails() {
      if (this.detailsMode === 'new') {
        const id = this.formId.trim();
        if (id === '') { alert('Introdu id-ul sesiunii (ex: 241435).'); return; }
        this.currentSession = {
          id: 0,
          name: this.autoName(id),
          reception_number: id,
        };
        this.eanInput = '';
        this.search = '';
        this.detailsModalOpen = false;
        this.view = 'editor';
        window.scrollTo({ top: 0 });
      } else {
        const name = this.formName.trim();
        if (name === '') { alert('Numele sesiunii este obligatoriu.'); return; }
        this.currentSession.name = name;
        this.currentSession.reception_number = this.formRecNumber.trim();
        this.detailsModalOpen = false;
      }
    },
    editSession(s) {
      this.currentSession = { id: s.id, name: s.name, reception_number: s.reception_number || '' };
      this.eanInput = (s.items || []).map(it => it.ean).join('\n');
      this.view = 'editor';
      window.scrollTo({ top: 0 });
    },
    backToList() {
      this.view = 'list';
      this.search = '';
    },

    // ---- tabel setare cantități ----
    shortName(s) {
      s = (s || '').toString();
      return s.length > 60 ? s.slice(0, 60) + '…' : s;
    },
    rowsWithQty() {
      return this.rows.filter(p => p.fbe_qty != null && p.fbe_qty !== '');
    },
    filteredRows() {
      let r = this.rows;
      if (this.onlyWithQty) r = this.rowsWithQty();
      const q = this.search.trim().toLowerCase();
      if (q) {
        r = r.filter(p =>
          (p.ean || '').toLowerCase().includes(q) ||
          (p.custom_name || p.product_name || '').toLowerCase().includes(q) ||
          (p.pnk || '').toLowerCase().includes(q)
        );
      }
      return r;
    },
    async saveQty(p, val) {
      const raw = (val ?? '').toString().trim();
      let qty = '';
      if (raw !== '') {
        const n = parseInt(raw, 10);
        qty = (isNaN(n) || n < 0) ? 0 : n;
      }
      if (this.savingIds.includes(p.id)) return;
      this.savingIds.push(p.id);
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', p.id);
        fd.append('qty', qty);
        const r = await fetch('<?= url('api/save-fbe-qty.php') ?>', { method: 'POST', body: fd, credentials: 'same-origin' });
        const d = await r.json();
        if (!d.ok) throw new Error(d.error || 'Eroare');
        p.fbe_qty = d.fbe_qty;
      } catch (e) {
        alert('Nu am putut salva cantitatea: ' + e.message);
      } finally {
        this.savingIds = this.savingIds.filter(x => x !== p.id);
      }
    },

    // ---- listă EAN ----
    eanMap() {
      const m = new Map();
      for (const p of this.rows) {
        const key = (p.ean || '').toString().trim();
        if (!key) continue;
        const existing = m.get(key);
        const hasQty = (p.fbe_qty != null && p.fbe_qty !== '');
        if (!existing || (hasQty && (existing.fbe_qty == null || existing.fbe_qty === ''))) {
          m.set(key, p);
        }
      }
      return m;
    },
    parsedEans() {
      return this.eanInput.split(/\r?\n/).map(s => s.trim()).filter(s => s !== '');
    },
    matchedCount() {
      const m = this.eanMap();
      return this.parsedEans().filter(e => {
        const p = m.get(e);
        return p && p.fbe_qty != null && p.fbe_qty !== '';
      }).length;
    },
    notFoundEans() {
      const m = this.eanMap();
      return this.parsedEans().filter(e => {
        const p = m.get(e);
        return !p || p.fbe_qty == null || p.fbe_qty === '';
      });
    },
    totalPieces() {
      const m = this.eanMap();
      let t = 0;
      for (const e of this.parsedEans()) {
        const p = m.get(e);
        if (p && p.fbe_qty != null && p.fbe_qty !== '') t += Number(p.fbe_qty) || 0;
      }
      return t;
    },

    // Items {ean, qty, product_id, product_name} din EAN-urile lipite + cantitățile curente.
    currentItems() {
      const m = this.eanMap();
      return this.parsedEans().map(e => {
        const p = m.get(e);
        const qty = (p && p.fbe_qty != null && p.fbe_qty !== '') ? Number(p.fbe_qty) : null;
        return {
          ean: e, qty: qty,
          product_id: p ? p.id : null,
          product_name: p ? (p.custom_name || p.product_name) : null,
        };
      });
    },
    buildExcel(items, recNumber) {
      if (typeof XLSX === 'undefined') { alert('Biblioteca de export nu s-a încărcat încă. Reîncearcă în câteva secunde.'); return; }
      if (!items || !items.length) { alert('Lipește cel puțin un EAN.'); return; }
      const rec = (recNumber || '').toString().trim();
      const aoa = [['EAN', 'Bucăți', 'Nr recepție']];
      for (const it of items) {
        const hasQty = (it.qty != null && it.qty !== '');
        const qty = hasQty ? Number(it.qty) : '';
        // Nr. recepție se pune doar pe rândurile cu cantitate (la fel ca bucățile).
        aoa.push([String(it.ean), qty, hasQty ? rec : '']);
      }
      const ws = XLSX.utils.aoa_to_sheet(aoa);
      ws['!cols'] = [{ wch: 18 }, { wch: 10 }, { wch: 14 }];
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Recepție FBE');
      const safe = (recNumber || '').toString().trim().replace(/[^\w.\-]+/g, '_');
      XLSX.writeFile(wb, 'receptie-fbe' + (safe ? '-' + safe : '') + '.xlsx');
    },
    generateExcel() {
      this.buildExcel(this.currentItems(), this.currentSession.reception_number);
    },

    // Export pentru ÎMPACHETARE: nume produs + numărătoare, doar ce are cantitate,
    // cu produsele LEGATE (același model telefon = phone_series_id) grupate unul sub
    // altul ca să se vadă variantele împreună la împachetat.
    buildPackingExcel(items, recNumber) {
      if (typeof XLSX === 'undefined') { alert('Biblioteca de export nu s-a încărcat încă. Reîncearcă în câteva secunde.'); return; }
      const m = this.eanMap();
      const withQty = (items || []).filter(it => it.qty != null && it.qty !== '' && Number(it.qty) > 0);
      if (!withQty.length) { alert('Nu există produse cu cantitate de împachetat.'); return; }
      // Grupare pe phone_series_id, păstrând ordinea de apariție a grupurilor.
      const groups = new Map();
      withQty.forEach((it, i) => {
        const p = m.get(String(it.ean).trim());
        const key = (p && p.phone_series_id != null) ? ('g' + p.phone_series_id) : ('solo' + i);
        if (!groups.has(key)) groups.set(key, { first: i, rows: [] });
        groups.get(key).rows.push({ it, p });
      });
      const ordered = [...groups.values()].sort((a, b) => a.first - b.first);
      const aoa = [['Nr', 'Nume produs', 'Model telefon', 'EAN', 'PNK', 'Buc/cutie', 'Bucăți']];
      let n = 0;
      for (const g of ordered) {
        for (const { it, p } of g.rows) {
          n++;
          const name  = p ? (p.custom_name || p.product_name) : (it.product_name || '');
          const phone = (p && p.phone_label) ? p.phone_label : '';
          const pnk   = p ? (p.pnk || '') : '';
          const upb   = (p && p.units_per_box != null && p.units_per_box !== '') ? Number(p.units_per_box) : '';
          aoa.push([n, name, phone, String(it.ean), pnk, upb, Number(it.qty)]);
        }
      }
      const ws = XLSX.utils.aoa_to_sheet(aoa);
      ws['!cols'] = [{ wch: 5 }, { wch: 50 }, { wch: 22 }, { wch: 18 }, { wch: 14 }, { wch: 10 }, { wch: 8 }];
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Împachetare');
      const safe = (recNumber || '').toString().trim().replace(/[^\w.\-]+/g, '_');
      XLSX.writeFile(wb, 'impachetare' + (safe ? '-' + safe : '') + '.xlsx');
    },
    generatePacking() {
      this.buildPackingExcel(this.currentItems(), this.currentSession.reception_number);
    },
    downloadPacking(s) {
      this.buildPackingExcel(s.items || [], s.reception_number);
    },

    // ---- salvare sesiune (insert/update) ----
    updateSessionInList(session) {
      const i = this.sessions.findIndex(x => x.id === session.id);
      if (i >= 0) this.sessions.splice(i, 1, session);
      else this.sessions.unshift(session);
    },
    async saveSession() {
      if (this.saving) return;
      const name = (this.currentSession.name || '').trim();
      if (name === '') { this.editDetails(); return; }
      const items = this.currentItems();
      if (!items.length) { alert('Sesiunea nu are niciun EAN.'); return; }
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', this.currentSession.id || 0);
        fd.append('name', name);
        fd.append('reception_number', this.currentSession.reception_number || '');
        fd.append('account_id', this.accountId);
        fd.append('items', JSON.stringify(items));
        const r = await fetch('<?= url('api/save-reception.php') ?>', { method: 'POST', body: fd, credentials: 'same-origin' });
        const d = await r.json();
        if (!d.ok) throw new Error(d.error || 'Eroare');
        this.currentSession.id = d.session.id;
        this.updateSessionInList(d.session);
        this.buildExcel(d.session.items, d.session.reception_number);
      } catch (e) {
        alert('Nu am putut salva sesiunea: ' + e.message);
      } finally {
        this.saving = false;
      }
    },
    downloadSession(s) {
      this.buildExcel(s.items || [], s.reception_number);
    },
    async deleteSession(s) {
      if (!confirm('Ștergi sesiunea „' + s.name + '"?')) return;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', s.id);
        const r = await fetch('<?= url('api/delete-reception.php') ?>', { method: 'POST', body: fd, credentials: 'same-origin' });
        const d = await r.json();
        if (!d.ok) throw new Error(d.error || 'Eroare');
        this.sessions = this.sessions.filter(x => x.id !== s.id);
      } catch (e) {
        alert('Nu am putut șterge sesiunea: ' + e.message);
      }
    },
    formatDate(s) {
      if (!s) return '';
      const d = new Date(s.replace(' ', 'T'));
      if (isNaN(d)) return s;
      return d.toLocaleDateString('ro-RO') + ' ' + d.toLocaleTimeString('ro-RO', { hour: '2-digit', minute: '2-digit' });
    }
  };
}
</script>

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