<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/template-engine.php';

$pageTitle  = 'Șabloane nume produs';
$breadcrumb = [['label' => 'Șabloane']];

$templates = [];
$dbError = null;
try {
    $templates = db_select(
        "SELECT id, name, template, description, created_at, updated_at
         FROM name_templates
         ORDER BY name COLLATE NOCASE ASC"
    );
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

$placeholders = template_placeholders();

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="templatesPage(<?= htmlspecialchars(json_encode($templates), 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">Șabloane nume produs</h1>
      <p class="text-sm text-slate-500 mt-0.5">
        Definește șabloane reutilizabile cu placeholders. Aplică-le din pagina Produse → bulk „Aplică șablon".
      </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>
      Șablon nou
    </button>
  </div>

  <!-- Placeholders disponibile -->
  <div class="bg-sky-50 border border-sky-200 rounded-xl p-4 mb-4 text-sm text-sky-900">
    <div class="font-semibold mb-2">Placeholders disponibile</div>
    <div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
      <?php foreach ($placeholders as $ph => $desc): ?>
        <div class="flex items-baseline gap-1.5">
          <code class="font-mono bg-white px-1.5 py-0.5 rounded border border-sky-200 text-sky-800"><?= e($ph) ?></code>
          <span class="text-sky-700 truncate"><?= e($desc) ?></span>
        </div>
      <?php endforeach; ?>
    </div>
    <p class="text-xs text-sky-700 mt-2">💡 Placeholders care nu au valoare sunt înlocuiți cu string gol și spațiile multiple sunt colapsate automat.</p>
  </div>

  <!-- Listă șabloane -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden">
    <template x-if="all.length === 0">
      <div class="p-10 text-center text-sm text-slate-400">
        Niciun șablon. Adaugă unul ca să-l poți folosi în pagina Produse.
      </div>
    </template>
    <template x-if="all.length > 0">
      <table class="w-full text-sm">
        <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">Nume</th>
            <th class="px-3 py-2.5 text-left font-medium">Template</th>
            <th class="px-3 py-2.5 text-left font-medium">Preview</th>
            <th class="px-3 py-2.5 text-right font-medium w-24">Acțiuni</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-100">
          <template x-for="t in all" :key="t.id">
            <tr class="hover:bg-slate-50 align-top divide-x divide-slate-100">
              <td class="px-3 py-2.5 align-top">
                <div class="font-medium text-slate-900" x-text="t.name"></div>
                <div class="text-[11px] text-slate-400 mt-0.5" x-show="t.description" x-text="t.description"></div>
              </td>
              <td class="px-3 py-2.5 align-top">
                <code class="font-mono text-xs text-slate-700 bg-slate-50 px-2 py-1 rounded break-all" x-text="t.template"></code>
              </td>
              <td class="px-3 py-2.5 align-top">
                <div class="text-xs text-slate-700 italic" x-text="renderPreview(t.template)"></div>
              </td>
              <td class="px-3 py-2.5 text-right whitespace-nowrap">
                <button @click="openEdit(t)" 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>
                <button @click="deleteTpl(t)" class="text-rose-600 hover:text-rose-700 p-1.5 rounded hover:bg-rose-50 transition" title="Șterge">
                  <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>
    </template>
  </div>

  <!-- ============== 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-2xl">
      <form @submit.prevent="saveTpl()">
        <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="editing.id ? 'Editare șablon' : 'Șablon nou'"></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">Nume șablon *</label>
            <input type="text" x-model="editing.name" required maxlength="100"
              placeholder="ex: Husa silicon"
              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">Template *</label>
            <input type="text" x-model="editing.template" required maxlength="500"
              x-ref="templateInput"
              placeholder="ex: Husa silicon pentru {brand} {model} {series}"
              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">
            <div class="mt-2 flex flex-wrap gap-1">
              <?php foreach ($placeholders as $ph => $desc): ?>
                <button type="button" @click="insertPlaceholder('<?= e($ph) ?>')"
                  class="text-[10px] font-mono px-1.5 py-0.5 bg-slate-100 hover:bg-brand-100 text-slate-700 rounded transition"
                  title="<?= e($desc) ?>">+ <?= e($ph) ?></button>
              <?php endforeach; ?>
            </div>
          </div>
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Preview (cu valori sample)</label>
            <div class="px-3 py-2 text-sm bg-slate-50 border border-slate-200 rounded-lg text-slate-700 italic min-h-[42px]" x-text="renderPreview(editing.template) || '—'"></div>
          </div>
          <div>
            <label class="block text-xs font-medium text-slate-700 mb-1">Descriere (opțional)</label>
            <input type="text" x-model="editing.description" maxlength="255"
              placeholder="Pentru ce produse e potrivit acest șablon?"
              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>
        <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 templatesPage(initial) {
  // Date sample pentru preview
  const SAMPLE = {
    brand: 'Apple', model: 'iPhone', series: '13 Pro',
    compatible: '13, 14, 15',
    compatible_slash: '13 / 14 / 15',
    all_series: '13 Pro / 13 / 14 / 15',
    name: 'Husa silicon premium', ean: '5940741370350',
    pnk: 'D9T0KBMBM', pn: 'EA_S25ULTRA_2B_V3', cod_oblio: 'OBL-1234'
  };

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

    init() {},

    renderPreview(tpl) {
      if (!tpl) return '';
      let out = tpl;
      Object.entries(SAMPLE).forEach(([k, v]) => {
        out = out.replaceAll('{' + k + '}', v);
      });
      return out.replace(/\s+/g, ' ').trim();
    },

    insertPlaceholder(ph) {
      const input = this.$refs.templateInput;
      const start = input.selectionStart, end = input.selectionEnd;
      const before = this.editing.template.substring(0, start);
      const after  = this.editing.template.substring(end);
      this.editing.template = before + ph + after;
      this.$nextTick(() => {
        input.focus();
        input.selectionStart = input.selectionEnd = start + ph.length;
      });
    },

    openAdd() {
      this.editing = { id: 0, name: '', template: '', description: '' };
      this.modalOpen = true;
    },
    openEdit(t) {
      this.editing = { id: t.id, name: t.name, template: t.template, description: t.description || '' };
      this.modalOpen = true;
    },

    async saveTpl() {
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        Object.entries(this.editing).forEach(([k, v]) => fd.append(k, v ?? ''));
        const r = await fetch('<?= url('api/save-template.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);
        const idx = this.all.findIndex(x => x.id == data.template.id);
        if (idx >= 0) this.all[idx] = data.template;
        else this.all.push(data.template);
        this.modalOpen = false;
      } catch (e) {
        alert('Eroare: ' + e.message);
      } finally {
        this.saving = false;
      }
    },

    async deleteTpl(t) {
      if (!confirm(`Ștergi șablonul „${t.name}"?`)) return;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', t.id);
        const r = await fetch('<?= url('api/delete-template.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);
        this.all = this.all.filter(x => x.id != t.id);
      } catch (e) {
        alert('Eroare: ' + e.message);
      }
    }
  };
}
</script>

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