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

$pageTitle  = 'Adaugă produs';
$breadcrumb = [['label' => 'Produse', 'url' => url('products.php')], ['label' => 'Adaugă']];

$accounts = [];
try {
    $accounts = db_select("SELECT id, account_name FROM emag_accounts ORDER BY account_name ASC");
} catch (Throwable $ex) {}

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

<div x-data="addProductForm()" class="max-w-3xl">

  <div class="mb-6">
    <h1 class="text-2xl font-bold text-slate-900">Adaugă produs manual</h1>
    <p class="text-sm text-slate-500 mt-0.5">Pentru import din eMAG folosește <a href="<?= url('import-emag.php') ?>" class="text-brand-600 hover:underline">pagina de sync</a>.</p>
  </div>

  <form @submit.prevent="submit()" class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden">

    <!-- Secțiunea 1: identificare -->
    <div class="p-6 border-b border-slate-100">
      <h2 class="text-sm font-semibold text-slate-900 mb-4 flex items-center gap-2">
        <span class="w-6 h-6 rounded-full bg-brand-100 text-brand-700 text-xs flex items-center justify-center font-bold">1</span>
        Identificare produs
      </h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="md:col-span-2">
          <label class="block text-xs font-medium text-slate-700 mb-1">Nume produs *</label>
          <input type="text" x-model="form.product_name" required maxlength="500"
            placeholder="ex: Cablu USB-C 2m"
            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="mt-1 text-xs text-slate-400" x-show="form.product_name.length > 400" x-cloak>
            <span x-text="500 - form.product_name.length"></span> caractere rămase
          </p>
        </div>

        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">EAN</label>
          <input type="text" x-model="form.ean" maxlength="20"
            pattern="[0-9]*" inputmode="numeric"
            placeholder="ex: 5901234123457"
            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>

        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">Categorie</label>
          <input type="text" x-model="form.category" maxlength="255"
            placeholder="ex: Cabluri & Adaptoare"
            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>

    <!-- Secțiunea 2: coduri eMAG / Oblio -->
    <div class="p-6 border-b border-slate-100">
      <h2 class="text-sm font-semibold text-slate-900 mb-4 flex items-center gap-2">
        <span class="w-6 h-6 rounded-full bg-brand-100 text-brand-700 text-xs flex items-center justify-center font-bold">2</span>
        Coduri eMAG / Oblio
      </h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">PNK (Part Number Key)</label>
          <input type="text" x-model="form.pnk" maxlength="100"
            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>
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">Cod Oblio</label>
          <input type="text" x-model="form.cod_oblio" maxlength="100"
            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>
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">Nr. bucăți / cutie</label>
          <input type="number" x-model="form.units_per_box" min="0" step="1"
            placeholder="ex: 12"
            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">Editat manual — păstrat la sync.</p>
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">eMAG ID</label>
          <input type="text" x-model="form.emag_id" maxlength="100"
            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>
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">Cod produs (PN)</label>
          <input type="text" x-model="form.emag_part_number" maxlength="100"
            placeholder="ex: EA_S25ULTRA_2B_V3"
            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">
          <p class="text-xs text-slate-500 mt-1">SKU intern al sellerului (în eMAG: <code>part_number</code>).</p>
        </div>
      </div>
    </div>

    <!-- Secțiunea 3: meta -->
    <div class="p-6 border-b border-slate-100">
      <h2 class="text-sm font-semibold text-slate-900 mb-4 flex items-center gap-2">
        <span class="w-6 h-6 rounded-full bg-brand-100 text-brand-700 text-xs flex items-center justify-center font-bold">3</span>
        Atribuire & status
      </h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">Cont eMAG</label>
          <select x-model="form.emag_account_id" 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="">— Niciun cont —</option>
            <?php foreach ($accounts as $acc): ?>
              <option value="<?= (int)$acc['id'] ?>"><?= e($acc['account_name']) ?></option>
            <?php endforeach; ?>
          </select>
          <?php if (!$accounts): ?>
            <p class="text-xs text-amber-600 mt-1">Niciun cont configurat. <a href="<?= url('settings.php') ?>" class="underline">Adaugă unul</a>.</p>
          <?php endif; ?>
        </div>
        <div>
          <label class="block text-xs font-medium text-slate-700 mb-1">Status *</label>
          <select x-model="form.status" required 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="draft">Draft</option>
            <option value="active">Active</option>
            <option value="synced">Synced</option>
          </select>
        </div>
        <div class="md:col-span-2">
          <label class="block text-xs font-medium text-slate-700 mb-1">Notes</label>
          <textarea x-model="form.notes" rows="3"
            placeholder="Observații interne, varianta de nume optimizată pentru eMAG, etc."
            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>
    </div>

    <!-- Footer -->
    <div class="px-6 py-4 bg-slate-50 flex items-center justify-between gap-2">
      <div class="text-xs text-slate-500" x-show="lastSavedName" x-cloak>
        <span class="text-emerald-600">✓</span> Salvat: <span class="font-medium" x-text="lastSavedName"></span>
      </div>
      <div class="flex-1"></div>
      <a href="<?= url('products.php') ?>" class="px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200 rounded-lg transition">Anulează</a>
      <button type="submit" name="saveAndNew" @click="saveAndNew = true" :disabled="saving"
        class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-200 hover:bg-slate-50 rounded-lg transition disabled:opacity-50">
        Salvează & adaugă altul
      </button>
      <button type="submit" @click="saveAndNew = false" :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>

<script>
function addProductForm() {
  return {
    form: {
      id: 0,
      product_name: '',
      ean: '',
      pnk: '',
      cod_oblio: '',
      emag_id: '',
      emag_part_number: '',
      category: '',
      emag_account_id: '',
      status: 'draft',
      notes: '',
      units_per_box: '',
    },
    saving: false,
    saveAndNew: false,
    lastSavedName: '',
    csrf: '<?= e(csrf_token()) ?>',

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

        this.lastSavedName = data.product.product_name;
        if (this.saveAndNew) {
          // resetează formularul, păstrează contul/statusul curent
          const keep = { emag_account_id: this.form.emag_account_id, status: this.form.status };
          this.form = { id: 0, product_name: '', ean: '', pnk: '', cod_oblio: '', emag_id: '', emag_part_number: '', category: '', notes: '', units_per_box: '', ...keep };
          window.scrollTo({ top: 0, behavior: 'smooth' });
        } else {
          window.location.href = '<?= url('products.php') ?>';
        }
      } catch (e) {
        alert('Eroare: ' + e.message);
      } finally {
        this.saving = false;
      }
    }
  };
}
</script>

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