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

$pageTitle  = 'EAN-uri excluse';
$breadcrumb = [['label' => 'EAN-uri excluse']];

$excluded = [];
$dbError  = null;
try {
    $excluded = db_select(
        "SELECT id, ean, product_name, reason, created_at
         FROM excluded_eans
         ORDER BY created_at DESC
         LIMIT 2000"
    );
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

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. Detalii: <pre class="mt-2 text-xs"><?= e($dbError) ?></pre>
  </div>
<?php endif; ?>

<div
  x-data="excludedPage(<?= htmlspecialchars(json_encode($excluded), ENT_QUOTES, 'UTF-8') ?>)"
  x-init="init()"
>

  <div class="flex items-center justify-between mb-4">
    <div>
      <h1 class="text-2xl font-bold text-slate-900">EAN-uri excluse</h1>
      <p class="text-sm text-slate-500 mt-0.5">
        Produsele cu aceste EAN-uri sunt ignorate complet la sincronizarea cu eMAG.
      </p>
    </div>
    <button @click="openAdd()"
      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>
      Adaugă EAN(uri)
    </button>
  </div>

  <!-- Info card -->
  <div class="bg-rose-50 border border-rose-200 rounded-xl p-4 mb-4 text-sm text-rose-900">
    <div class="flex items-start gap-2">
      <svg class="w-5 h-5 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728L5.636 5.636m12.728 12.728L18.364 5.636M5.636 18.364l12.728-12.728"/></svg>
      <div>
        <div class="font-semibold mb-1">Cum funcționează</div>
        <ul class="ml-4 list-disc space-y-0.5 text-rose-800 text-xs">
          <li>EAN-urile listate aici sunt anulate la fiecare sincronizare — produsul nu se va mai importa.</li>
          <li>Adăugarea unui EAN aici șterge automat produsul corespunzător din tabela <strong>products</strong>.</li>
          <li>Scoaterea unui EAN din listă NU re-importă produsul automat — trebuie să rulezi un sync nou.</li>
        </ul>
      </div>
    </div>
  </div>

  <!-- Filters + bulk bar -->
  <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-3">
      <div class="md:col-span-9 relative">
        <svg class="w-4 h-4 absolute left-3 top-3 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" @input.debounce.150ms="applyFilters()"
          placeholder="Caută după EAN, nume sau motiv…"
          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 class="md:col-span-3 text-right text-sm text-slate-500 self-center">
        <span x-text="filtered.length"></span> din <span x-text="all.length"></span>
      </div>
    </div>

    <div x-show="selected.length > 0" x-cloak class="mt-3 pt-3 border-t border-slate-100 flex items-center gap-3 text-sm">
      <span class="font-medium text-slate-700"><span x-text="selected.length"></span> selectate</span>
      <button @click="bulkRemove()" class="inline-flex items-center gap-1.5 px-3 py-1.5 text-rose-700 bg-rose-50 hover:bg-rose-100 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="M5 13l4 4L19 7"/></svg>
        Scoate din excluse
      </button>
      <button @click="selected = []" class="text-slate-500 hover:text-slate-700">Anulează</button>
    </div>
  </div>

  <!-- 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">
        <thead class="bg-slate-50 text-xs uppercase tracking-wide text-slate-500">
          <tr>
            <th class="px-4 py-3 text-left w-10">
              <input type="checkbox" @change="toggleAll($event)" :checked="selected.length === filtered.length && filtered.length > 0" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500">
            </th>
            <th class="px-4 py-3 text-left font-medium">EAN</th>
            <th class="px-4 py-3 text-left font-medium">Nume produs (la momentul excluderii)</th>
            <th class="px-4 py-3 text-left font-medium">Motiv</th>
            <th class="px-4 py-3 text-left font-medium">Data</th>
            <th class="px-4 py-3 text-right font-medium">Acțiuni</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
          <template x-if="filtered.length === 0">
            <tr><td colspan="6" class="px-4 py-12 text-center text-slate-400">
              <div class="mx-auto w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
                <svg class="w-6 h-6 text-slate-400" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728L5.636 5.636m12.728 12.728L18.364 5.636M5.636 18.364l12.728-12.728"/></svg>
              </div>
              <div x-text="all.length === 0 ? 'Niciun EAN exclus.' : 'Niciun rezultat pentru filtru.'"></div>
              <div x-show="all.length === 0" class="mt-2 text-xs">Adaugă EAN-uri pentru a le bloca la import.</div>
            </td></tr>
          </template>

          <template x-for="r in filtered" :key="r.id">
            <tr class="row-hover">
              <td class="px-4 py-3">
                <input type="checkbox" :value="r.id" x-model="selected" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500">
              </td>
              <td class="px-4 py-3 font-mono text-xs font-medium text-slate-900" x-text="r.ean"></td>
              <td class="px-4 py-3 text-slate-700 max-w-md truncate" x-text="r.product_name || '—'"></td>
              <td class="px-4 py-3 text-slate-500 text-xs max-w-xs truncate" x-text="r.reason || '—'"></td>
              <td class="px-4 py-3 text-slate-500 text-xs" x-text="formatDate(r.created_at)"></td>
              <td class="px-4 py-3 text-right">
                <button @click="removeOne(r)" class="text-rose-600 hover:text-rose-700 p-1.5 rounded hover:bg-rose-50 transition" title="Scoate din excluse">
                  <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>
        </tbody>
      </table>
    </div>
  </div>

  <!-- ============== ADD MODAL ============== -->
  <div x-show="modalOpen" x-cloak @keydown.escape.window="modalOpen = false"
       x-data="{ _bg: false }"
       @mousedown.self="_bg = true"
       @mouseup="if (_bg && $event.target === $el) modalOpen = false; _bg = false"
       class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
    <div class="modal-enter bg-white rounded-2xl shadow-2xl w-full max-w-xl">
      <form @submit.prevent="submitAdd()">
        <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
          <h3 class="font-semibold text-slate-900">Adaugă EAN-uri excluse</h3>
          <button type="button" @click="modalOpen = 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">
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">EAN-uri *</label>
            <textarea x-model="addText" required rows="6"
              placeholder="Un EAN per linie, sau separate prin virgulă:&#10;5901234123457&#10;5947123456789, 5938765432101"
              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"></textarea>
            <p class="text-xs text-slate-500 mt-1">
              <span x-text="parsedEans().length"></span> EAN-uri detectate.
              Cele care există deja vor fi ignorate.
            </p>
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Motiv (opțional)</label>
            <input type="text" x-model="addReason" maxlength="255"
              placeholder="ex: produse descontinuate"
              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 class="bg-amber-50 border border-amber-200 rounded-lg p-3 text-xs text-amber-900">
            <strong>Atenție:</strong> Adăugarea acestor EAN-uri va șterge automat produsele corespunzătoare din tabela Produse.
          </div>
        </div>

        <div class="px-6 py-4 border-t border-slate-100 bg-slate-50 flex items-center justify-end gap-2 rounded-b-2xl">
          <button type="button" @click="modalOpen = false" class="px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200 rounded-lg transition">Anulează</button>
          <button type="submit" :disabled="saving || parsedEans().length === 0"
            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 shadow-soft transition disabled:opacity-50">
            <span x-show="saving" class="spinner"></span>
            <span x-text="saving ? 'Adaug…' : 'Adaugă în excluse'"></span>
          </button>
        </div>
      </form>
    </div>
  </div>

</div>

<script>
function excludedPage(initial) {
  return {
    all: initial || [],
    filtered: [],
    selected: [],
    search: '',
    modalOpen: false,
    saving: false,
    addText: '',
    addReason: '',
    csrf: '<?= e(csrf_token()) ?>',

    init() { this.applyFilters(); },

    applyFilters() {
      const q = this.search.trim().toLowerCase();
      if (!q) { this.filtered = this.all; return; }
      this.filtered = this.all.filter(r =>
        (r.ean || '').toLowerCase().includes(q) ||
        (r.product_name || '').toLowerCase().includes(q) ||
        (r.reason || '').toLowerCase().includes(q)
      );
    },

    formatDate(s) {
      if (!s) return '—';
      const d = new Date(s.replace(' ', 'T'));
      return d.toLocaleDateString('ro-RO') + ' ' + d.toLocaleTimeString('ro-RO', {hour:'2-digit', minute:'2-digit'});
    },

    toggleAll(e) {
      this.selected = e.target.checked ? this.filtered.map(r => r.id) : [];
    },

    openAdd() {
      this.addText = '';
      this.addReason = '';
      this.modalOpen = true;
    },

    parsedEans() {
      return [...new Set(
        this.addText.split(/[\s,;]+/).map(s => s.trim()).filter(Boolean)
      )];
    },

    async submitAdd() {
      const eans = this.parsedEans();
      if (eans.length === 0) return;
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        if (this.addReason) fd.append('reason', this.addReason);
        eans.forEach(e => fd.append('eans[]', e));
        const r = await fetch('<?= url('api/exclude.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error || 'Eroare');

        // Reload local — simplu și sigur (numărul e mic)
        window.location.reload();
      } catch (e) {
        alert('Eroare: ' + e.message);
        this.saving = false;
      }
    },

    async removeOne(r) {
      if (!confirm(`Scoți EAN-ul „${r.ean}" din lista de excluse?\n\nNu reimportă automat produsul.`)) return;
      await this._remove([r.id]);
    },

    async bulkRemove() {
      if (!this.selected.length) return;
      if (!confirm(`Scoți ${this.selected.length} EAN-uri din lista de excluse?`)) return;
      await this._remove(this.selected);
    },

    async _remove(ids) {
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        ids.forEach(id => fd.append('ids[]', id));
        const r = await fetch('<?= url('api/unexclude.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);
        this.all = this.all.filter(x => !ids.includes(x.id));
        this.selected = [];
        this.applyFilters();
      } catch (e) {
        alert('Eroare: ' + e.message);
      }
    }
  };
}
</script>

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