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

$pageTitle  = 'Categorii';
$breadcrumb = [['label' => 'Categorii']];

$categories = [];
$dbError    = null;
try {
    $categories = db_select(
        "SELECT c.*,
                (SELECT COUNT(*) FROM products p WHERE p.category_id = c.id) AS products_count
         FROM categories c
         ORDER BY products_count DESC, c.name ASC"
    );
} 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="categoriesPage(<?= htmlspecialchars(json_encode($categories), 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">Categorii</h1>
      <p class="text-sm text-slate-500 mt-0.5">
        Categoriile sunt create automat la sync din câmpul <code>category_id</code> al fiecărui produs eMAG.
      </p>
    </div>
    <div class="text-sm text-slate-500">
      <span x-text="all.length"></span> categorii ·
      <span x-text="excludedCount()"></span> excluse
    </div>
  </div>

  <!-- Info card -->
  <div class="bg-sky-50 border border-sky-200 rounded-xl p-4 mb-4 text-sm text-sky-900">
    <div class="flex items-start gap-2">
      <svg class="w-5 h-5 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/></svg>
      <div>
        <div class="font-semibold mb-1">Setări per categorie</div>
        <ul class="ml-4 list-disc space-y-0.5 text-xs text-sky-800">
          <li><strong>Nume custom</strong>: override afișat în loc de numele din eMAG (util când numele eMAG e prea tehnic).</li>
          <li><strong>Notes</strong>: observații interne despre categorie.</li>
          <li><strong>Exclude la sync</strong>: toate produsele acestei categorii vor fi ignorate la următoarele sincronizări.</li>
        </ul>
      </div>
    </div>
  </div>

  <!-- Filter 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ă nume, ID eMAG sau notes…"
          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">
        <select x-model="filterStatus" @change="applyFilters()"
          class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 bg-white">
          <option value="all">Toate</option>
          <option value="included">Doar incluse</option>
          <option value="excluded">Doar excluse</option>
        </select>
      </div>
    </div>
  </div>

  <!-- Tabel categorii -->
  <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-[11px] uppercase tracking-wide text-slate-500">
          <tr>
            <th class="px-3 py-2.5 text-left font-medium">ID eMAG</th>
            <th class="px-3 py-2.5 text-left font-medium">Nume categorie</th>
            <th class="px-3 py-2.5 text-left font-medium">Nume custom</th>
            <th class="px-3 py-2.5 text-right font-medium">Produse</th>
            <th class="px-3 py-2.5 text-left font-medium">Status</th>
            <th class="px-3 py-2.5 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="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/></svg>
              </div>
              <div x-text="all.length === 0 ? 'Nicio categorie încă. Rulează un sync pentru a popula.' : 'Niciun rezultat.'"></div>
            </td></tr>
          </template>

          <template x-for="c in filtered" :key="c.id">
            <tr class="row-hover">
              <td class="px-3 py-2.5">
                <span class="font-mono text-xs text-slate-600" x-text="c.emag_category_id || '—'"></span>
              </td>
              <td class="px-3 py-2.5">
                <div class="font-medium text-slate-900" x-text="c.name"></div>
                <div class="text-[11px] text-slate-400 mt-0.5" x-show="c.notes" x-text="c.notes"></div>
              </td>
              <td class="px-3 py-2.5">
                <span class="text-sm text-slate-700" x-text="c.custom_name || '—'"
                      :class="c.custom_name ? '' : 'text-slate-400'"></span>
              </td>
              <td class="px-3 py-2.5 text-right">
                <span class="text-sm font-semibold text-slate-900" x-text="c.products_count"></span>
              </td>
              <td class="px-3 py-2.5">
                <template x-if="parseInt(c.is_excluded) === 1">
                  <span class="inline-flex items-center gap-1 text-[10px] font-medium uppercase tracking-wide px-2 py-0.5 rounded-full bg-rose-100 text-rose-800">
                    <svg class="w-3 h-3" 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>
                    Exclusă
                  </span>
                </template>
                <template x-if="parseInt(c.is_excluded) !== 1">
                  <span class="inline-flex items-center gap-1 text-[10px] font-medium uppercase tracking-wide px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-800">Activă</span>
                </template>
              </td>
              <td class="px-3 py-2.5 text-right whitespace-nowrap">
                <a :href="'<?= url('products.php') ?>?category=' + c.id"
                   class="text-brand-600 hover:text-brand-700 p-1.5 rounded hover:bg-brand-50 transition inline-block"
                   title="Vezi produsele">
                  <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 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                </a>
                <button @click="openEdit(c)" class="text-brand-600 hover:text-brand-700 p-1.5 rounded hover:bg-brand-50 transition" title="Editează">
                  <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>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>

  <!-- ============== EDIT 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-lg">
      <form @submit.prevent="saveCategory()">
        <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
          <div>
            <h3 class="font-semibold text-slate-900">Editare categorie</h3>
            <p class="text-xs text-slate-500 mt-0.5" x-text="editing.name + (editing.emag_category_id ? ' · eMAG ID ' + editing.emag_category_id : '')"></p>
          </div>
          <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">Nume din eMAG</label>
            <input type="text" :value="editing.name" disabled
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg bg-slate-50 text-slate-500">
            <p class="text-xs text-slate-500 mt-1">Read-only — se actualizează la sync.</p>
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Nume custom (override)</label>
            <input type="text" x-model="editing.custom_name" maxlength="255"
              placeholder="ex: Telefoane (intern)"
              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">
            <p class="text-xs text-slate-500 mt-1">Afișat în loc de numele eMAG în tabela Produse.</p>
          </div>

          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Notes</label>
            <textarea x-model="editing.notes" rows="3"
              placeholder="Observații interne despre categorie…"
              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>

          <label class="flex items-start gap-3 cursor-pointer select-none p-3 border border-rose-200 bg-rose-50 rounded-lg">
            <input type="checkbox" x-model="editing.is_excluded" :true-value="1" :false-value="0"
                   class="mt-0.5 rounded border-rose-300 text-rose-600 focus:ring-rose-500">
            <div>
              <div class="text-sm font-medium text-rose-900">Exclude la sync</div>
              <div class="text-xs text-rose-700 mt-0.5">Toate produsele din această categorie vor fi ignorate complet la următoarele sincronizări.</div>
            </div>
          </label>
        </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"
            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 ? 'Salvez…' : 'Salvează'"></span>
          </button>
        </div>
      </form>
    </div>
  </div>

</div>

<script>
function categoriesPage(initial) {
  return {
    all: initial || [],
    filtered: [],
    search: '',
    filterStatus: 'all',
    modalOpen: false,
    saving: false,
    editing: {},
    csrf: '<?= e(csrf_token()) ?>',

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

    applyFilters() {
      const q = this.search.trim().toLowerCase();
      this.filtered = this.all.filter(c => {
        if (q) {
          const hay = (c.name + ' ' + (c.custom_name || '') + ' ' + (c.notes || '') + ' ' + (c.emag_category_id || '')).toLowerCase();
          if (!hay.includes(q)) return false;
        }
        if (this.filterStatus === 'excluded' && parseInt(c.is_excluded) !== 1) return false;
        if (this.filterStatus === 'included' && parseInt(c.is_excluded) === 1) return false;
        return true;
      });
    },

    excludedCount() {
      return this.all.filter(c => parseInt(c.is_excluded) === 1).length;
    },

    openEdit(c) {
      this.editing = {
        id: c.id,
        name: c.name,
        emag_category_id: c.emag_category_id,
        custom_name: c.custom_name || '',
        notes: c.notes || '',
        is_excluded: parseInt(c.is_excluded) || 0,
      };
      this.modalOpen = true;
    },

    async saveCategory() {
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        Object.entries({
          id: this.editing.id,
          custom_name: this.editing.custom_name,
          notes: this.editing.notes,
          is_excluded: this.editing.is_excluded,
        }).forEach(([k, v]) => fd.append(k, v ?? ''));
        const r = await fetch('<?= url('api/save-category.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error || 'Eroare');

        const idx = this.all.findIndex(x => x.id == data.category.id);
        if (idx >= 0) this.all[idx] = data.category;
        this.applyFilters();
        this.modalOpen = false;
      } catch (e) {
        alert('Eroare: ' + e.message);
      } finally {
        this.saving = false;
      }
    }
  };
}
</script>

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