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

$id    = (int)($_GET['id'] ?? 0);
$order = $id > 0 ? order_load($id) : null;

if (!$order) {
    $pageTitle  = 'Comandă';
    $breadcrumb = [['label' => 'Orders', 'url' => url('orders.php')], ['label' => 'Comandă']];
    require __DIR__ . '/includes/header.php';
    echo '<div class="bg-amber-50 border border-amber-200 rounded-xl p-4 text-sm text-amber-900">Comanda nu există. <a class="text-brand-600 hover:underline" href="' . e(url('orders.php')) . '">Înapoi la comenzi</a></div>';
    require __DIR__ . '/includes/footer.php';
    return;
}

$pageTitle  = 'Comanda ' . $order['order_no'];
$breadcrumb = [['label' => 'Orders', 'url' => url('orders.php')], ['label' => $order['order_no']]];

$goods    = db_select("SELECT id, sku, name, unit, default_price, supplier FROM goods WHERE is_active = 1 ORDER BY name COLLATE NOCASE");
$statuses = order_statuses();
$units    = order_units();
$company  = order_company();
$langs    = order_langs();
// Etichetele documentului pentru ambele limbi — JS alege după limba comenzii.
$labels   = ['ro' => order_labels('ro'), 'en' => order_labels('en')];
// Traducerea unităților de măsură pentru documentul în engleză (folosită la export).
$unitsEn  = [];
foreach ($units as $u) { $unitsEn[$u] = order_unit_label($u, 'en'); }

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

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

<div x-data="orderPage({
       order: <?= htmlspecialchars(json_encode($order), ENT_QUOTES, 'UTF-8') ?>,
       goods: <?= htmlspecialchars(json_encode($goods), ENT_QUOTES, 'UTF-8') ?>,
       units: <?= htmlspecialchars(json_encode($units), ENT_QUOTES, 'UTF-8') ?>,
       company: <?= htmlspecialchars(json_encode($company), ENT_QUOTES, 'UTF-8') ?>,
       labels: <?= htmlspecialchars(json_encode($labels), ENT_QUOTES, 'UTF-8') ?>,
       unitsEn: <?= htmlspecialchars(json_encode($unitsEn), ENT_QUOTES, 'UTF-8') ?>,
       csrf: '<?= e(csrf_token()) ?>'
     })">

  <!-- Antet pagină -->
  <div class="flex items-center gap-3 flex-wrap mb-4">
    <a href="<?= e(url('orders.php')) ?>" class="text-slate-400 hover:text-slate-700" title="Înapoi la comenzi">
      <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="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
    </a>
    <h1 class="text-2xl font-bold text-slate-900 font-mono"><?= e($order['order_no']) ?></h1>
    <!-- Starea salvării automate -->
    <span x-show="saving" x-cloak class="text-xs text-slate-400 font-medium">salvez…</span>
    <span x-show="!saving && dirty && !saveError" x-cloak class="text-xs text-amber-600 font-medium">• nesalvat</span>
    <span x-show="!saving && !dirty && savedOnce && !saveError" x-cloak class="text-xs text-emerald-600 font-medium">✓ salvat automat</span>
    <span x-show="saveError" x-cloak class="text-xs text-rose-600 font-medium" x-text="saveError"></span>
    <div class="flex-1"></div>

    <button @click="exportXlsx()"
      class="inline-flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-slate-600 hover:text-slate-900 border border-slate-200 hover:bg-slate-50 rounded-lg 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 10v6m0 0l-3-3m3 3l3-3M3 17V7a2 2 0 012-2h14a2 2 0 012 2v10a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
      XLS
    </button>
    <button @click="openPrint()"
      class="inline-flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-slate-600 hover:text-slate-900 border border-slate-200 hover:bg-slate-50 rounded-lg 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="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>
      PDF
    </button>
    <button @click="remove()"
      class="inline-flex items-center justify-center w-8 h-8 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition" title="Șterge comanda">
      <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>
    <button @click="save()" :disabled="saving"
      class="inline-flex items-center gap-2 px-3.5 py-1.5 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg transition disabled:opacity-50">
      <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="M5 13l4 4L19 7"/></svg>
      <span x-text="saving ? 'Salvez…' : 'Salvează'"></span>
    </button>
  </div>

  <!-- Antet comandă -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-4 mb-4">
    <div class="grid grid-cols-1 md:grid-cols-7 gap-3">
      <div class="md:col-span-2">
        <label class="block text-xs font-medium text-slate-600 mb-1">Furnizor</label>
        <input type="text" x-model="o.supplier" @input="touch()" list="suppliersList" placeholder="Nume furnizor"
          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">
        <datalist id="suppliersList">
          <template x-for="s in supplierOptions()" :key="s"><option :value="s"></option></template>
        </datalist>
      </div>
      <div>
        <label class="block text-xs font-medium text-slate-600 mb-1">Data comenzii</label>
        <input type="date" x-model="o.order_date" @change="touch()"
          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-600 mb-1">Livrare estimată</label>
        <input type="date" x-model="o.delivery_date" @change="touch()"
          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-600 mb-1">Status</label>
        <select x-model="o.status" @change="touch()"
          class="w-full px-2 py-2 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500">
          <?php foreach ($statuses as $k => $lbl): ?>
            <option value="<?= e($k) ?>"><?= e($lbl) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="md:col-span-2 grid grid-cols-4 gap-2">
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1">Monedă</label>
          <input type="text" x-model="o.currency" @input="touch()" maxlength="5"
            class="w-full px-2 py-2 text-sm uppercase 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-600 mb-1">TVA %</label>
          <input type="number" min="0" max="100" step="0.01" x-model="o.vat_rate" @input="touch()"
            class="w-full px-2 py-2 text-sm text-right tabular-nums 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-600 mb-1" title="Limba în care se generează PDF-ul și XLS-ul">Limbă doc.</label>
          <select x-model="o.lang" @change="touch()"
            class="w-full px-1 py-2 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500">
            <?php foreach ($langs as $code => $lbl): ?>
              <option value="<?= e($code) ?>"><?= e($lbl) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-600 mb-1"
                 title="Câte zecimale se păstrează la prețul unitar (pe ecran, la salvare și pe document)">Zecimale preț</label>
          <select x-model.number="o.price_decimals" @change="onDecimalsChange()"
            class="w-full px-1 py-2 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500">
            <?php for ($d = 0; $d <= 6; $d++): ?>
              <option value="<?= $d ?>"><?= $d ?></option>
            <?php endfor; ?>
          </select>
        </div>
      </div>
    </div>
    <div class="mt-3">
      <label class="block text-xs font-medium text-slate-600 mb-1">Observații (apar pe comanda printată)</label>
      <textarea x-model="o.notes" @input="touch()" rows="2" placeholder="ex: livrare la depozit, plata la 30 zile…"
        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"></textarea>
    </div>
  </div>

  <!-- Adaugă marfă -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-4 mb-4" @click.outside="pickerOpen = false">
    <div class="flex items-end gap-2 flex-wrap">
      <div class="relative flex-1 min-w-[240px]">
        <label class="block text-xs font-medium text-slate-600 mb-1">Adaugă marfă din catalog</label>
        <input type="text" x-model="pick" @focus="pickerOpen = true" @input="pickerOpen = true"
          @keydown.enter.prevent="addFirstMatch()" @keydown.escape="pickerOpen = false"
          placeholder="Caută după denumire sau cod…"
          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 x-show="pickerOpen && matches().length > 0" x-cloak
             class="absolute z-30 left-0 right-0 mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-64 overflow-y-auto">
          <template x-for="g in matches()" :key="g.id">
            <button type="button" @click="addGoods(g)"
              class="w-full text-left px-3 py-2 hover:bg-slate-50 transition flex items-center justify-between gap-3">
              <span class="min-w-0">
                <span class="block text-sm text-slate-800 truncate" x-text="g.name"></span>
                <span class="block text-[11px] text-slate-400 font-mono" x-text="[g.sku, g.supplier].filter(Boolean).join(' · ')"></span>
              </span>
              <span class="text-xs text-slate-500 tabular-nums whitespace-nowrap"
                    x-text="g.default_price != null ? fmtPrice(g.default_price) : '—'"></span>
            </button>
          </template>
        </div>
      </div>
      <button @click="addBlank()"
        class="px-3 py-2 text-sm font-medium text-slate-600 border border-slate-200 hover:bg-slate-50 rounded-lg transition">
        + Linie liberă
      </button>
      <a href="<?= e(url('marfa.php')) ?>" class="px-3 py-2 text-sm text-brand-600 hover:text-brand-700 font-medium">Gestionează marfa →</a>
    </div>
  </div>

  <!-- Linii comandă -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden mb-4">
    <div class="overflow-x-auto">
      <table class="w-full text-sm table-fixed">
        <thead>
          <tr class="border-b border-slate-100 bg-slate-50/60 text-left text-xs font-medium text-slate-500 uppercase tracking-wide">
            <th class="px-2 py-2.5 w-20">#</th>
            <th class="px-3 py-2.5 w-32">Cod</th>
            <th class="px-3 py-2.5">Denumire</th>
            <th class="px-3 py-2.5 w-20">UM</th>
            <th class="px-3 py-2.5 w-24 text-right">Cant.</th>
            <th class="px-3 py-2.5 w-28 text-right">Preț unitar</th>
            <th class="px-3 py-2.5 w-32 text-right">Valoare</th>
            <th class="px-3 py-2.5 w-14"></th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-50">
          <template x-for="(it, idx) in o.items" :key="it._k">
            <tr class="hover:bg-slate-50/50"
                :class="[dragKey === it._k ? 'opacity-40' : '', dragOverKey === it._k ? 'ring-2 ring-inset ring-brand-400' : '']"
                @dragover.prevent="dragKey !== null && dragKey !== it._k && (dragOverKey = it._k)"
                @dragleave="dragOverKey === it._k && (dragOverKey = null)"
                @drop.prevent="onDrop(idx)"
                @dragend="dragKey = null; dragOverKey = null">
              <td class="px-2 py-2">
                <div class="flex items-center gap-1">
                  <span draggable="true" title="Trage ca să muți linia" @dragstart="onDragStart(it, $event)"
                    class="cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500 select-none">
                    <svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20"><circle cx="7" cy="4" r="1.5"/><circle cx="13" cy="4" r="1.5"/><circle cx="7" cy="10" r="1.5"/><circle cx="13" cy="10" r="1.5"/><circle cx="7" cy="16" r="1.5"/><circle cx="13" cy="16" r="1.5"/></svg>
                  </span>
                  <input type="number" min="1" :max="o.items.length" :value="idx + 1"
                    @change="moveLine(idx, $event.target.value)" @keydown.enter="$event.target.blur()"
                    title="Scrie poziția dorită și apasă Enter"
                    class="w-11 px-1 py-1 text-xs text-right tabular-nums text-slate-400 border border-transparent hover:border-slate-200 focus:border-brand-500 focus:text-slate-700 rounded-md focus:outline-none">
                </div>
              </td>
              <td class="px-3 py-2">
                <input type="text" x-model="it.sku" @input="touch()"
                  class="w-full px-2 py-1 text-sm font-mono border border-transparent hover:border-slate-200 focus:border-brand-500 rounded-md focus:outline-none">
              </td>
              <td class="px-3 py-2">
                <input type="text" x-model="it.name" @input="touch()"
                  class="w-full px-2 py-1 text-sm font-medium border border-transparent hover:border-slate-200 focus:border-brand-500 rounded-md focus:outline-none">
              </td>
              <td class="px-3 py-2">
                <select x-model="it.unit" @change="touch()"
                  class="w-full px-1 py-1 text-sm bg-transparent border border-transparent hover:border-slate-200 focus:border-brand-500 rounded-md focus:outline-none">
                  <template x-for="u in units" :key="u"><option :value="u" x-text="u"></option></template>
                </select>
              </td>
              <td class="px-3 py-2">
                <input type="number" min="0" step="0.001" x-model.number="it.qty" @input="touch()"
                  class="w-full px-2 py-1 text-sm text-right tabular-nums border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-500">
              </td>
              <td class="px-3 py-2">
                <input type="number" min="0" :step="priceStep()" x-model.number="it.unit_price" @input="touch()"
                  class="w-full px-2 py-1 text-sm text-right tabular-nums border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-500">
              </td>
              <td class="px-3 py-2 text-right font-semibold tabular-nums" x-text="fmt(lineTotal(it))"></td>
              <td class="px-3 py-2 text-center">
                <button @click="removeLine(idx)" title="Șterge linia"
                  class="inline-flex items-center justify-center w-8 h-8 text-slate-300 hover:text-rose-600 hover:bg-rose-50 rounded-lg 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="M6 18L18 6M6 6l12 12"/></svg>
                </button>
              </td>
            </tr>
          </template>
          <template x-if="o.items.length === 0">
            <tr><td colspan="8" class="px-4 py-12 text-center text-sm text-slate-400">Nicio linie. Adaugă marfă din catalog mai sus.</td></tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Totaluri — bară lipită de marginea de jos a ecranului -->
  <div class="sticky bottom-0 z-30 -mx-6 mt-4 px-6 py-2.5 bg-white/95 backdrop-blur border-t border-slate-200 shadow-[0_-2px_12px_rgba(15,23,42,0.07)]">
    <div class="flex items-end gap-x-7 gap-y-2 flex-wrap">

      <div>
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Linii</div>
        <div class="text-base font-semibold text-slate-900 tabular-nums" x-text="o.items.length"></div>
      </div>
      <div>
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Produse</div>
        <div class="text-base font-semibold text-slate-900 tabular-nums">
          <span x-text="fmtQty(totalQty())"></span> <span class="text-xs font-normal text-slate-400">buc</span>
        </div>
      </div>

      <div class="flex-1"></div>

      <div class="text-right">
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Subtotal</div>
        <div class="text-sm font-medium text-slate-600 tabular-nums" x-text="fmt(subtotal())"></div>
      </div>
      <div class="text-right" x-show="Number(o.vat_rate) > 0">
        <div class="text-[10px] uppercase tracking-wide text-slate-400">TVA <span x-text="Number(o.vat_rate)"></span>%</div>
        <div class="text-sm font-medium text-slate-600 tabular-nums" x-text="fmt(vat())"></div>
      </div>
      <div class="text-right">
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Total</div>
        <div class="text-lg font-bold text-slate-900 tabular-nums leading-6">
          <span x-text="fmt(total())"></span> <span class="text-xs font-normal text-slate-400" x-text="o.currency"></span>
        </div>
      </div>

      <!-- Curs BNR pentru data comenzii -->
      <template x-if="!bnr.loading && bnr.rate">
        <div class="flex items-end gap-5 pl-5 border-l border-slate-200">
          <div class="text-right">
            <div class="text-[10px] uppercase tracking-wide text-slate-400">
              Curs BNR <span class="tabular-nums" x-text="dmy(bnr.date)"></span>
            </div>
            <div class="text-sm font-medium text-slate-600 tabular-nums"
                 x-text="'1 ' + bnr.currency + ' = ' + rateFmt(bnr.rate)"></div>
          </div>
          <div class="text-right" x-show="o.currency.toUpperCase() !== 'RON'">
            <div class="text-[10px] uppercase tracking-wide text-slate-400">Total în RON</div>
            <div class="text-lg font-bold text-slate-900 tabular-nums leading-6">
              <span x-text="fmt(total() * bnr.rate)"></span> <span class="text-xs font-normal text-slate-400">RON</span>
            </div>
          </div>
        </div>
      </template>

      <template x-if="!bnr.loading && !bnr.rate">
        <div class="text-xs text-slate-400 pl-5 border-l border-slate-200">
          <span x-text="bnr.error || 'Curs BNR indisponibil'"></span>
          <button @click="loadBnr(true)" class="text-brand-600 hover:text-brand-700 font-medium">reîncearcă</button>
        </div>
      </template>
    </div>

    <p x-show="!bnr.loading && bnr.rate && !bnr.exact && !bnr.stale" x-cloak class="text-[11px] text-slate-400 mt-1">
      BNR nu publică în weekend și de sărbători — e cursul din
      <span x-text="dmy(bnr.date)"></span>, ultimul dinaintea datei comenzii.
    </p>
    <p x-show="!bnr.loading && bnr.rate && bnr.stale" x-cloak class="text-[11px] text-amber-600 mt-1">
      Data comenzii e în viitor — deocamdată e cel mai recent curs publicat
      (<span x-text="dmy(bnr.date)"></span>).
    </p>
  </div>
</div>

<script>
function orderPage(cfg) {
  return {
    o: {
      ...cfg.order,
      lang: cfg.order.lang || 'ro',
      price_decimals: cfg.order.price_decimals != null ? Number(cfg.order.price_decimals) : 2,
      delivery_date: cfg.order.delivery_date || '',
      supplier: cfg.order.supplier || '',
      notes: cfg.order.notes || '',
      // `_k` = cheie stabilă doar pentru randare (Alpine) — nu se salvează în DB.
      items: (cfg.order.items || []).map((i, n) => ({
        _k: 'k' + n,
        goods_id: i.goods_id, name: i.name, sku: i.sku || '', unit: i.unit || 'buc',
        qty: Number(i.qty), unit_price: Number(i.unit_price)
      }))
    },
    goods: cfg.goods,
    units: cfg.units,
    company: cfg.company,
    labels: cfg.labels,
    unitsEn: cfg.unitsEn,
    csrf: cfg.csrf,
    saving: false,
    dirty: false,
    savedOnce: false,
    saveError: '',
    saveTimer: null,
    keySeq: 0,
    dragKey: null,
    dragOverKey: null,
    pick: '',
    pickerOpen: false,
    bnr: { loading: true, rate: 0, currency: 'EUR', date: '', exact: true, stale: false, error: '' },
    bnrKey: '',

    init() {
      this.keySeq = this.o.items.length;
      this.loadBnr();
      // Cursul depinde de data comenzii și de monedă — îl reîncărcăm când se schimbă.
      this.$watch('o.order_date', () => this.loadBnr());
      this.$watch('o.currency',   () => this.loadBnr());
      // Dacă utilizatorul închide pagina cu o salvare încă în aer, îl avertizăm.
      window.addEventListener('beforeunload', (e) => {
        if (this.dirty || this.saving) { e.preventDefault(); e.returnValue = ''; }
      });
    },

    newKey() { return 'k' + (++this.keySeq); },

    // --- Salvare automată ---
    // Orice modificare programează o salvare; adăugările/ștergerile/mutările
    // cer delay 0, ca să se salveze imediat.
    touch(delay = 900) {
      this.dirty = true;
      this.saveError = '';
      clearTimeout(this.saveTimer);
      this.saveTimer = setTimeout(() => this.autosave(), delay);
    },

    async autosave() {
      if (!this.dirty) return;
      if (this.saving) {                     // o salvare e deja în curs — reîncearcă după ea
        clearTimeout(this.saveTimer);
        this.saveTimer = setTimeout(() => this.autosave(), 400);
        return;
      }
      await this.save(true);
    },

    // --- Formatare ---
    fmt(v)     { return Number(v || 0).toLocaleString('ro-RO', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); },
    fmtQty(v)  { return Number(v || 0).toLocaleString('ro-RO', { maximumFractionDigits: 3 }); },
    rateFmt(v) { return Number(v || 0).toLocaleString('ro-RO', { minimumFractionDigits: 4, maximumFractionDigits: 4 }); },

    // Prețul unitar respectă numărul de zecimale ales pe comandă;
    // valorile și totalurile rămân la 2 zecimale (sume de bani).
    decimals()   { const d = Number(this.o.price_decimals); return Number.isFinite(d) ? Math.min(6, Math.max(0, d)) : 2; },
    priceStep()  { const d = this.decimals(); return d === 0 ? '1' : '0.' + '0'.repeat(d - 1) + '1'; },
    fmtPrice(v)  { const d = this.decimals(); return Number(v || 0).toLocaleString('ro-RO', { minimumFractionDigits: d, maximumFractionDigits: d }); },

    // La schimbarea zecimalelor rotunjim prețurile existente, ca ce vezi pe ecran
    // să fie exact ce se salvează (altfel ar rămâne cifre ascunse dincolo de afișare).
    onDecimalsChange() {
      const d = this.decimals();
      const f = Math.pow(10, d);
      this.o.items.forEach(it => { it.unit_price = Math.round((Number(it.unit_price) || 0) * f) / f; });
      this.touch(0);
    },
    dmy(d)     { if (!d) return ''; const p = String(d).split('-'); return p.length === 3 ? `${p[2]}.${p[1]}.${p[0]}` : d; },

    // --- Curs BNR pentru data comenzii ---
    // Pentru comenzile în RON afișăm cursul EUR al zilei, ca reper.
    async loadBnr(force = false) {
      const cur  = (this.o.currency || 'RON').toUpperCase();
      const want = cur === 'RON' ? 'EUR' : cur;
      const date = this.o.order_date || '';
      if (!date) return;

      const key = date + '|' + want;
      if (!force && key === this.bnrKey) return;
      this.bnrKey = key;
      this.bnr = { loading: true, rate: 0, currency: want, date: '', exact: true, stale: false, error: '' };

      try {
        const url = '<?= url('api/bnr-rate.php') ?>?date=' + encodeURIComponent(date) + '&currency=' + encodeURIComponent(want);
        const j = await (await fetch(url)).json();
        if (!j.ok) throw new Error(j.error || 'Eroare');
        const r = j.rates && j.rates[want];
        if (!r) { this.bnr = { loading: false, rate: 0, currency: want, error: want + ' nu e cotat de BNR' }; return; }
        this.bnr = {
          loading: false, rate: Number(r.rate), currency: want,
          date: r.date, exact: !!r.exact, stale: !!r.stale, error: ''
        };
      } catch (e) {
        this.bnrKey = '';                      // permite reîncercarea
        this.bnr = { loading: false, rate: 0, currency: want, error: 'Curs BNR indisponibil' };
      }
    },

    // --- Calcule ---
    lineTotal(it) { return (Number(it.qty) || 0) * (Number(it.unit_price) || 0); },
    subtotal()    { return this.o.items.reduce((s, it) => s + this.lineTotal(it), 0); },
    vat()         { return this.subtotal() * (Number(this.o.vat_rate) || 0) / 100; },
    total()       { return this.subtotal() + this.vat(); },
    totalQty()    { return this.o.items.reduce((s, it) => s + (Number(it.qty) || 0), 0); },

    supplierOptions() {
      return [...new Set(this.goods.map(g => g.supplier).filter(Boolean))];
    },

    // --- Adăugare linii ---
    matches() {
      const q = this.pick.trim().toLowerCase();
      const list = q === '' ? this.goods
        : this.goods.filter(g => (g.name || '').toLowerCase().includes(q) || (g.sku || '').toLowerCase().includes(q));
      return list.slice(0, 12);
    },
    addFirstMatch() {
      const m = this.matches();
      if (m.length > 0) this.addGoods(m[0]);
    },
    addGoods(g) {
      const existing = this.o.items.find(i => i.goods_id === g.id);
      if (existing) {
        existing.qty = (Number(existing.qty) || 0) + 1;
      } else {
        this.o.items.push({
          _k: this.newKey(),
          goods_id: g.id, name: g.name, sku: g.sku || '', unit: g.unit || 'buc',
          qty: 1, unit_price: g.default_price != null ? Number(g.default_price) : 0
        });
      }
      this.pick = '';
      this.pickerOpen = false;
      this.touch(0);          // marfa adăugată se salvează imediat
    },
    addBlank() {
      this.o.items.push({ _k: this.newKey(), goods_id: null, name: '', sku: '', unit: 'buc', qty: 1, unit_price: 0 });
      // Linia goală e ignorată la salvare (nu are denumire), dar salvăm oricum ca
      // starea să rămână „curată” — se scrie în DB imediat ce-i dai un nume.
      this.touch(0);
    },
    removeLine(idx) {
      this.o.items.splice(idx, 1);
      this.touch(0);
    },

    // --- Reordonare linii ---
    onDragStart(it, ev) {
      this.dragKey = it._k;
      if (!ev.dataTransfer) return;
      ev.dataTransfer.effectAllowed = 'move';
      try { ev.dataTransfer.setData('text/plain', String(it._k)); } catch (e) {}
      const tr = ev.target.closest('tr');
      if (tr && ev.dataTransfer.setDragImage) ev.dataTransfer.setDragImage(tr, 20, 12);
    },
    onDrop(to) {
      const from = this.o.items.findIndex(i => i._k === this.dragKey);
      this.dragOverKey = null;
      this.dragKey = null;
      if (from < 0 || to < 0 || from === to) return;
      this.moveIndex(from, to);
    },
    moveLine(from, value) {
      let to = parseInt(value, 10);
      if (!Number.isFinite(to)) return;
      to = Math.max(1, Math.min(to, this.o.items.length)) - 1;
      if (to === from) return;
      this.moveIndex(from, to);
    },
    moveIndex(from, to) {
      const [moved] = this.o.items.splice(from, 1);
      this.o.items.splice(to, 0, moved);
      this.touch(0);
    },

    // --- Salvare ---
    async save(silent = false) {
      if (this.saving) return false;
      clearTimeout(this.saveTimer);
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', this.o.id);
        fd.append('supplier', this.o.supplier || '');
        fd.append('order_date', this.o.order_date || '');
        fd.append('delivery_date', this.o.delivery_date || '');
        fd.append('status', this.o.status);
        fd.append('currency', this.o.currency || 'RON');
        fd.append('vat_rate', this.o.vat_rate || 0);
        fd.append('lang', this.o.lang || 'ro');
        fd.append('price_decimals', this.decimals());
        fd.append('notes', this.o.notes || '');
        fd.append('items', JSON.stringify(this.o.items));
        const r = await fetch('<?= url('api/save-order.php') ?>', { method: 'POST', body: fd });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error || 'Eroare');
        this.dirty = false;
        this.savedOnce = true;
        this.saveError = '';
        return true;
      } catch (e) {
        // La salvarea automată nu blocăm scrisul cu un alert — arătăm eroarea în antet
        // și reîncercăm; `dirty` rămâne true, deci nimic nu se pierde.
        if (silent) {
          this.saveError = '⚠ nu s-a salvat: ' + e.message;
          this.saveTimer = setTimeout(() => this.autosave(), 5000);
        } else {
          alert('Eroare la salvare: ' + e.message);
        }
        return false;
      } finally {
        this.saving = false;
      }
    },

    async remove() {
      if (!confirm(`Ștergi comanda ${this.o.order_no}? Acțiunea nu poate fi anulată.`)) return;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', this.o.id);
        const r = await fetch('<?= url('api/delete-order.php') ?>', { method: 'POST', body: fd });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error || 'Eroare');
        clearTimeout(this.saveTimer);
        this.dirty = false;                       // comanda nu mai există — fără avertisment la ieșire
        window.location = '<?= url('orders.php') ?>';
      } catch (e) {
        alert('Eroare la ștergere: ' + e.message);
      }
    },

    // Salvează întâi (ca PDF-ul să arate ce vezi pe ecran), apoi deschide pagina de print.
    async openPrint() {
      if (this.dirty && !(await this.save())) return;
      window.open('<?= url('order-print.php') ?>?id=' + this.o.id, '_blank');
    },

    // --- Export .xlsx ---
    async exportXlsx() {
      if (typeof XLSX === 'undefined') { alert('Biblioteca de export nu s-a încărcat încă. Reîncearcă în câteva secunde.'); return; }
      if (this.dirty && !(await this.save())) return;

      const t = this.labels[this.o.lang] || this.labels.ro;
      const c = this.company;
      const aoa = [];
      if (c.name) aoa.push([c.name]);
      const idLine = [c.cui ? `${t.vat_id}: ${c.cui}` : '', c.reg ? `${t.reg}: ${c.reg}` : ''].filter(Boolean).join(' · ');
      if (idLine) aoa.push([idLine]);
      const addr = [c.address, c.city, c.country].filter(Boolean).join(', ');
      if (addr) aoa.push([addr]);
      const contact = [c.phone ? `${t.phone}: ${c.phone}` : '', c.email ? `${t.email}: ${c.email}` : '', c.web].filter(Boolean).join(' · ');
      if (contact) aoa.push([contact]);
      const bank = [c.bank, c.iban ? `${t.iban}: ${c.iban}` : ''].filter(Boolean).join(' · ');
      if (bank) aoa.push([bank]);
      if (aoa.length) aoa.push([]);

      aoa.push([t.doc_title, this.o.order_no]);
      aoa.push([t.order_date, this.o.order_date]);
      if (this.o.delivery_date) aoa.push([t.delivery, this.o.delivery_date]);
      aoa.push([t.supplier, this.o.supplier || '—']);
      aoa.push([]);
      aoa.push([t.idx, t.code, t.name, t.unit, t.qty, t.unit_price, t.amount]);

      const priceRowFrom = aoa.length;      // prima linie de articol (0-based)
      this.o.items.forEach((it, i) => {
        const unit = this.o.lang === 'en' ? (this.unitsEn[it.unit] || it.unit) : it.unit;
        aoa.push([
          i + 1, it.sku || '', it.name, unit,
          Number(it.qty) || 0, Number(it.unit_price) || 0, Number(this.lineTotal(it).toFixed(2))
        ]);
      });

      aoa.push([]);
      aoa.push(['', '', '', '', '', t.subtotal, Number(this.subtotal().toFixed(2))]);
      if (Number(this.o.vat_rate) > 0) {
        aoa.push(['', '', '', '', '', `${t.vat} ${Number(this.o.vat_rate)}%`, Number(this.vat().toFixed(2))]);
      }
      aoa.push(['', '', '', '', '', `${t.total} (${this.o.currency})`, Number(this.total().toFixed(2))]);
      if (this.o.notes) { aoa.push([]); aoa.push([t.notes, this.o.notes]); }

      const priceRowTo = priceRowFrom + this.o.items.length - 1;

      const ws = XLSX.utils.aoa_to_sheet(aoa);
      ws['!cols'] = [{ wch: 5 }, { wch: 16 }, { wch: 52 }, { wch: 8 }, { wch: 12 }, { wch: 14 }, { wch: 16 }];

      // Coloana de preț unitar primește formatul cu zecimalele alese pe comandă.
      const dec = this.decimals();
      const zPrice = dec > 0 ? '0.' + '0'.repeat(dec) : '0';
      for (let r = priceRowFrom; r <= priceRowTo; r++) {
        const addr = XLSX.utils.encode_cell({ r: r, c: 5 });
        if (ws[addr]) ws[addr].z = zPrice;
      }
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, this.o.lang === 'en' ? 'Order' : 'Comanda');
      XLSX.writeFile(wb, this.o.order_no + '.xlsx');
    }
  };
}
</script>

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