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

$pageTitle  = 'Marfă';
$breadcrumb = [['label' => 'Orders', 'url' => url('orders.php')], ['label' => 'Marfă']];

$dbError = null;
$search  = trim((string)($_GET['q'] ?? ''));
$goods   = [];

$allowedPer = [50, 100, 200, 500];
$perPage    = (int)($_GET['per_page'] ?? 100);
if (!in_array($perPage, $allowedPer, true)) $perPage = 100;
$pageNum    = max(1, (int)($_GET['page'] ?? 1));
$total      = 0;
$totalPages = 1;

try {
    $where  = [];
    $params = [];
    if ($search !== '') {
        $where[] = '(name LIKE ? OR sku LIKE ? OR supplier LIKE ?)';
        $q = '%' . $search . '%';
        array_push($params, $q, $q, $q);
    }
    $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    $total      = (int)db_scalar("SELECT COUNT(*) FROM goods g $whereSql", $params);
    $totalPages = max(1, (int)ceil($total / $perPage));
    if ($pageNum > $totalPages) $pageNum = $totalPages;
    $offset = ($pageNum - 1) * $perPage;

    $goods = db_select(
        "SELECT g.*,
                (SELECT COUNT(*) FROM order_items oi WHERE oi.goods_id = g.id) AS used_count
         FROM goods g
         $whereSql
         ORDER BY g.position, g.name COLLATE NOCASE, g.id
         LIMIT ? OFFSET ?",
        array_merge($params, [$perPage, $offset])
    );
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

// Comenzile în care se poate adăuga marfă direct din listă (cele mai recente primele).
$orderList = [];
try {
    $orderList = db_select(
        "SELECT id, order_no, supplier, status, order_date
           FROM orders
          ORDER BY date(order_date) DESC, id DESC
          LIMIT 100"
    );
} catch (Throwable $ex) {
    // fără comenzi disponibile — selectorul rămâne gol
}
$orderStatuses = order_statuses();

function marfa_url(array $overrides = []): string {
    $current = [
        'q'        => $_GET['q']        ?? null,
        'page'     => $_GET['page']     ?? null,
        'per_page' => $_GET['per_page'] ?? null,
    ];
    $merged = array_filter(array_merge($current, $overrides), fn($v) => $v !== null && $v !== '');
    return '?' . http_build_query($merged);
}

$startRow = $total > 0 ? (($pageNum - 1) * $perPage) + 1 : 0;
$endRow   = min($pageNum * $perPage, $total);

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

<?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="goodsPage({
       rows: <?= htmlspecialchars(json_encode($goods), ENT_QUOTES, 'UTF-8') ?>,
       units: <?= htmlspecialchars(json_encode(order_units()), ENT_QUOTES, 'UTF-8') ?>,
       csrf: '<?= e(csrf_token()) ?>',
       startRow: <?= (int)$startRow ?>,
       total: <?= (int)$total ?>,
       q: <?= htmlspecialchars(json_encode($search), ENT_QUOTES, 'UTF-8') ?>,
       orders: <?= htmlspecialchars(json_encode(array_map(fn($o) => [
                    'id'       => (int)$o['id'],
                    'order_no' => $o['order_no'],
                    'label'    => $o['order_no']
                                  . ($o['supplier'] ? ' · ' . $o['supplier'] : '')
                                  . ' · ' . ($orderStatuses[$o['status']] ?? $o['status']),
                  ], $orderList)), ENT_QUOTES, 'UTF-8') ?>,
       orderUrl: '<?= e(url('order.php')) ?>'
     })">

  <div class="flex items-center gap-3 flex-wrap mb-4">
    <h1 class="text-2xl font-bold text-slate-900">Marfă</h1>
    <span class="text-sm text-slate-400"><?= number_format($total, 0, ',', '.') ?> articole în catalog<?= $search !== '' ? ' (filtrate)' : '' ?></span>
  </div>

  <?= order_tabs('marfa') ?>

  <!-- Adaugă marfă -->
  <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-12 gap-2">
      <input type="text" x-model="form.sku" placeholder="Cod" @keydown.enter="add()"
        class="md:col-span-2 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
      <input type="text" x-model="form.name" placeholder="Denumire marfă *" @keydown.enter="add()"
        class="md:col-span-4 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
      <select x-model="form.unit"
        class="md:col-span-1 px-2 py-2 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500">
        <template x-for="u in units" :key="u"><option :value="u" x-text="u"></option></template>
      </select>
      <input type="number" min="0" step="any" x-model="form.default_price" placeholder="Preț" @keydown.enter="add()"
        class="md:col-span-2 px-3 py-2 text-sm text-right tabular-nums border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
      <input type="text" x-model="form.supplier" placeholder="Furnizor" @keydown.enter="add()"
        class="md:col-span-2 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
      <button @click="add()" :disabled="saving"
        class="md:col-span-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 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="M12 4v16m8-8H4"/></svg>
        <span class="md:hidden">Adaugă</span>
      </button>
    </div>
    <p class="text-[11px] text-slate-400 mt-2">Prețul e doar valoarea implicită propusă la adăugarea în comandă — îl poți schimba pe fiecare comandă.</p>
  </div>

  <!-- Comanda în care se adaugă marfa cu butonul „+” de pe fiecare rând -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-3 mb-4 flex items-center gap-2 flex-wrap">
    <label class="text-xs font-medium text-slate-600">Adaugă în comanda</label>
    <select x-model="orderId" @change="rememberOrder()"
      class="px-2 py-1.5 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 max-w-md">
      <option value="">— alege o comandă —</option>
      <template x-for="o in orders" :key="o.id">
        <option :value="o.id" x-text="o.label"></option>
      </template>
    </select>

    <input type="number" min="0.001" step="0.001" x-model="addQty" title="Cantitatea adăugată la fiecare click pe „+”"
      class="w-20 px-2 py-1.5 text-sm text-right tabular-nums border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">

    <a x-show="orderId" x-cloak :href="orderUrl + '?id=' + orderId"
       class="text-sm text-brand-600 hover:text-brand-700 font-medium">Deschide comanda →</a>

    <template x-if="orders.length === 0">
      <span class="text-xs text-slate-400">Nu există comenzi —
        <a href="<?= e(url('orders.php')) ?>" class="text-brand-600 hover:underline">creează una</a>.</span>
    </template>

    <span class="flex-1"></span>
    <span class="text-[11px] text-slate-400">Butonul <strong>+</strong> de pe fiecare rând adaugă marfa pe comanda aleasă.</span>
  </div>

  <!-- Căutare -->
  <form method="get" data-ajax-filters class="mb-4 flex items-center gap-2 flex-wrap">
    <input type="text" name="q" value="<?= e($search) ?>" placeholder="Caută marfă, cod sau furnizor…"
      class="w-full max-w-md px-3 py-1.5 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
    <select name="per_page" onchange="this.form.requestSubmit()"
      class="px-2 py-1.5 text-sm border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500">
      <?php foreach ($allowedPer as $pp): ?>
        <option value="<?= $pp ?>" <?= $perPage === $pp ? 'selected' : '' ?>><?= $pp ?>/pag</option>
      <?php endforeach; ?>
    </select>
  </form>

  <!-- Tabel -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden">
    <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-3 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-24">UM</th>
            <th class="px-3 py-2.5 w-28 text-right">Preț</th>
            <th class="px-3 py-2.5 w-40">Furnizor</th>
            <th class="px-3 py-2.5 w-24 text-center">Comenzi</th>
            <th class="px-3 py-2.5 w-28 text-center">Acțiune</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-50">
          <template x-for="(g, i) in rows" :key="g.id">
            <tr class="hover:bg-slate-50/50"
                :class="[g.is_active == 0 ? 'opacity-50' : '', dragId === g.id ? 'opacity-40' : '', dragOverId === g.id ? 'ring-2 ring-inset ring-brand-400' : '']"
                @dragover.prevent="dragId !== null && dragId !== g.id && (dragOverId = g.id)"
                @dragleave="dragOverId === g.id && (dragOverId = null)"
                @drop.prevent="onDrop(g)"
                @dragend="dragId = null; dragOverId = null">
              <td class="px-3 py-2">
                <div class="flex items-center gap-1">
                  <span draggable="true" title="Trage ca să muți rândul" @dragstart="onDragStart(g, $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="total" :value="startRow + i"
                    @change="moveTo(g, $event.target.value, startRow + i)"
                    @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="g.sku" @change="save(g)"
                  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="g.name" @change="save(g)"
                  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="g.unit" @change="save(g)"
                  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="any" x-model="g.default_price" @change="save(g)"
                  class="w-full px-2 py-1 text-sm text-right tabular-nums 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="g.supplier" @change="save(g)"
                  class="w-full px-2 py-1 text-sm border border-transparent hover:border-slate-200 focus:border-brand-500 rounded-md focus:outline-none">
              </td>
              <td class="px-3 py-2 text-center text-xs text-slate-400 tabular-nums" x-text="g.used_count || 0"></td>
              <td class="px-3 py-2 text-center whitespace-nowrap">
                <button @click="addToOrder(g)" :disabled="!orderId || addingId === g.id"
                  :title="orderId ? 'Adaugă în comanda aleasă' : 'Alege întâi o comandă sus'"
                  class="inline-flex items-center justify-center w-8 h-8 text-slate-300 hover:text-brand-600 hover:bg-brand-50 rounded-lg transition disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-slate-300">
                  <span x-show="addingId === g.id" class="spinner"></span>
                  <svg x-show="addingId !== g.id" 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>
                </button>
                <button @click="remove(g)" title="Șterge marfa"
                  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="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>
          <template x-if="rows.length === 0">
            <tr><td colspan="8" class="px-4 py-12 text-center text-sm text-slate-400"><?= $search !== '' ? 'Nicio marfă găsită pentru căutarea curentă.' : 'Nicio marfă în catalog. Adaugă prima de mai sus.' ?></td></tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Paginare -->
  <?php if ($total > 0): ?>
    <div class="mt-4 flex items-center justify-between gap-3 flex-wrap text-sm">
      <div class="text-slate-500">Afișez <strong><?= $startRow ?>–<?= $endRow ?></strong> din <strong><?= number_format($total, 0, ',', '.') ?></strong></div>
      <?php if ($totalPages > 1): ?>
        <div class="flex items-center gap-1">
          <?php if ($pageNum > 1): ?>
            <a href="<?= e(marfa_url(['page' => 1])) ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50">« Prima</a>
            <a href="<?= e(marfa_url(['page' => $pageNum - 1])) ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50">‹ Anterior</a>
          <?php endif; ?>
          <span class="px-3 py-1.5 text-slate-500">Pagina <?= $pageNum ?> / <?= $totalPages ?></span>
          <?php if ($pageNum < $totalPages): ?>
            <a href="<?= e(marfa_url(['page' => $pageNum + 1])) ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50">Următor ›</a>
            <a href="<?= e(marfa_url(['page' => $totalPages])) ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50">Ultima »</a>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>
  <?php endif; ?>

  <!-- Confirmare „adăugat în comandă” -->
  <div x-show="toast" x-cloak x-transition.opacity
       class="fixed bottom-5 right-5 z-50 max-w-sm px-4 py-3 rounded-xl shadow-lg text-sm"
       :class="toastErr ? 'bg-rose-600 text-white' : 'bg-slate-900 text-white'">
    <span x-text="toast"></span>
    <a x-show="!toastErr && orderId" :href="orderUrl + '?id=' + orderId"
       class="ml-2 underline underline-offset-2 opacity-80 hover:opacity-100">vezi comanda</a>
  </div>
</div>

<script>
function goodsPage(cfg) {
  return {
    rows: cfg.rows,
    units: cfg.units,
    csrf: cfg.csrf,
    startRow: cfg.startRow || 1,
    total: cfg.total || 0,
    q: cfg.q || '',
    saving: false,
    dragId: null,
    dragOverId: null,
    orders: cfg.orders || [],
    orderUrl: cfg.orderUrl,
    orderId: '',
    addQty: 1,
    addingId: null,
    toast: '',
    toastErr: false,
    toastTimer: null,

    init() {
      // Reținem ultima comandă aleasă, ca să nu o reselectezi la fiecare pagină.
      const saved = localStorage.getItem('marfa.orderId');
      if (saved && this.orders.some(o => String(o.id) === String(saved))) this.orderId = saved;
    },

    rememberOrder() {
      if (this.orderId) localStorage.setItem('marfa.orderId', this.orderId);
      else localStorage.removeItem('marfa.orderId');
    },

    say(msg, isErr = false) {
      this.toast = msg;
      this.toastErr = isErr;
      clearTimeout(this.toastTimer);
      this.toastTimer = setTimeout(() => (this.toast = ''), 3500);
    },

    async addToOrder(g) {
      if (!this.orderId) { this.say('Alege întâi o comandă din selectorul de sus.', true); return; }
      if (this.addingId) return;
      this.addingId = g.id;
      try {
        const j = await this.post('<?= url('api/add-goods-to-order.php') ?>', {
          order_id: this.orderId, goods_id: g.id, qty: this.addQty || 1
        });
        if (j.created) g.used_count = (Number(g.used_count) || 0) + 1;
        this.say(`„${j.name}” în ${j.order_no} — acum ${j.qty} ${j.unit}`);
      } catch (e) {
        this.say('Nu s-a adăugat: ' + e.message, true);
      } finally {
        this.addingId = null;
      }
    },
    form: { sku: '', name: '', unit: 'buc', default_price: '', supplier: '' },

    async post(url, data) {
      const fd = new FormData();
      fd.append('csrf_token', this.csrf);
      for (const [k, v] of Object.entries(data)) fd.append(k, v ?? '');
      const r = await fetch(url, { method: 'POST', body: fd });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error || 'Eroare');
      return j;
    },

    async add() {
      if (this.saving) return;
      if (!this.form.name.trim()) { alert('Completează denumirea mărfii.'); return; }
      this.saving = true;
      try {
        const j = await this.post('<?= url('api/save-goods.php') ?>', { id: 0, ...this.form });
        this.rows.unshift({ ...j.goods, used_count: 0 });
        this.total++;
        this.form = { sku: '', name: '', unit: 'buc', default_price: '', supplier: '' };
      } catch (e) {
        alert('Eroare la salvare: ' + e.message);
      } finally {
        this.saving = false;
      }
    },

    async save(g) {
      try {
        await this.post('<?= url('api/save-goods.php') ?>', {
          id: g.id, sku: g.sku, name: g.name, unit: g.unit,
          default_price: g.default_price, supplier: g.supplier, is_active: g.is_active ? 1 : 0
        });
      } catch (e) {
        alert('Eroare la salvare: ' + e.message);
      }
    },

    // ---- Reordonare -------------------------------------------------------

    // Se trage doar de „mâner”, ca inputurile din rând să rămână editabile.
    onDragStart(g, ev) {
      this.dragId = g.id;
      if (!ev.dataTransfer) return;
      ev.dataTransfer.effectAllowed = 'move';
      try { ev.dataTransfer.setData('text/plain', String(g.id)); } catch (e) {}
      const tr = ev.target.closest('tr');
      if (tr && ev.dataTransfer.setDragImage) ev.dataTransfer.setDragImage(tr, 20, 12);
    },

    onDrop(target) {
      const from = this.rows.findIndex(r => r.id === this.dragId);
      const to   = this.rows.findIndex(r => r.id === target.id);
      this.dragOverId = null;
      this.dragId = null;
      if (from < 0 || to < 0 || from === to) return;
      const moved = this.rows[from];
      this.rows.splice(from, 1);            // mutare optimistă în pagina curentă
      this.rows.splice(to, 0, moved);
      this.persistMove(moved, this.startRow + to, this.startRow + from);
    },

    // Mutare prin scrierea poziției — ținta poate fi pe altă pagină, deci
    // după salvare reîncărcăm lista.
    moveTo(g, value, current) {
      let to = parseInt(value, 10);
      if (!Number.isFinite(to)) { this.refresh(); return; }
      to = Math.max(1, Math.min(to, this.total));
      if (to === current) return;
      this.persistMove(g, to, current, true);
    },

    async persistMove(g, to, from, reload) {
      try {
        await this.post('<?= url('api/reorder-goods.php') ?>', { id: g.id, to: to, q: this.q });
        if (reload) this.refresh();
      } catch (e) {
        alert('Eroare la mutare: ' + e.message);
        this.refresh();
      }
    },

    refresh() {
      if (window.ajaxNav) window.ajaxNav(location.pathname + location.search, false);
      else location.reload();
    },

    async remove(g) {
      const warn = (g.used_count > 0)
        ? `\n\nApare în ${g.used_count} linii de comandă — comenzile rămân neschimbate.`
        : '';
      if (!confirm(`Ștergi „${g.name}" din catalog?${warn}`)) return;
      try {
        await this.post('<?= url('api/delete-goods.php') ?>', { id: g.id });
        this.rows = this.rows.filter(x => x.id !== g.id);
        this.total--;
      } catch (e) {
        alert('Eroare la ștergere: ' + e.message);
      }
    }
  };
}
</script>

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