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

$pageTitle  = 'Modele telefon';
$breadcrumb = [['label' => 'Modele telefon']];

$brands = [];
$models = [];
$series = [];
$dbError = null;
try {
    $brands = db_select("SELECT id, name, notes FROM phone_brands ORDER BY name COLLATE NOCASE ASC");
    $models = db_select("SELECT id, brand_id, name, notes FROM phone_models ORDER BY name COLLATE NOCASE ASC");
    $series = db_select("SELECT id, model_id, name, notes FROM phone_series ORDER BY name COLLATE NOCASE 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="phoneTree({
  brands: <?= htmlspecialchars(json_encode($brands), ENT_QUOTES, 'UTF-8') ?>,
  models: <?= htmlspecialchars(json_encode($models), ENT_QUOTES, 'UTF-8') ?>,
  series: <?= htmlspecialchars(json_encode($series), ENT_QUOTES, 'UTF-8') ?>,
  csrf: '<?= e(csrf_token()) ?>'
})">

  <div class="mb-6">
    <h1 class="text-2xl font-bold text-slate-900">Modele telefon</h1>
    <p class="text-sm text-slate-500 mt-0.5">
      Ierarhie cu 3 nivele: <strong>Brand</strong> (ex: Apple) → <strong>Model</strong> (ex: iPhone) → <strong>Serie</strong> (ex: 13, 13 Pro).
    </p>
  </div>

  <!-- 3 coloane drill-down -->
  <div class="grid grid-cols-1 md:grid-cols-3 gap-4">

    <!-- ============ COL 1: BRANDS ============ -->
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden flex flex-col" style="min-height: 500px;">
      <div class="px-4 py-3 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
        <div>
          <h2 class="text-sm font-semibold text-slate-900">Brand</h2>
          <div class="text-[11px] text-slate-500"><span x-text="brands.length"></span> total</div>
        </div>
        <div class="flex items-center gap-1">
          <button @click="openAdd('brand')"
            class="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1.5 text-white bg-brand-600 hover:bg-brand-700 rounded-md transition" title="Adaugă unul">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
            Adaugă
          </button>
          <button @click="openBulk('brand')"
            class="inline-flex items-center gap-1 text-xs font-medium px-2 py-1.5 text-brand-700 bg-brand-50 hover:bg-brand-100 rounded-md transition" title="Adaugă listă (unul pe linie)">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
            Listă
          </button>
        </div>
      </div>

      <div class="flex-1 overflow-y-auto divide-y divide-slate-100">
        <template x-if="brands.length === 0">
          <div class="p-8 text-center text-xs text-slate-400">Niciun brand încă.</div>
        </template>
        <template x-for="b in sortedBrands()" :key="b.id">
          <div @click="selectBrand(b.id)"
               class="px-3 py-2.5 flex items-center gap-2 cursor-pointer hover:bg-slate-50 group transition"
               :class="selectedBrandId === b.id ? 'bg-brand-50 hover:bg-brand-50' : ''">
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-slate-800 truncate" x-text="b.name"></div>
              <div class="text-[11px] text-slate-500" x-text="modelsCount(b.id) + ' modele'"></div>
            </div>
            <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition">
              <button @click.stop="openEdit('brand', b)" class="p-1 text-slate-400 hover:text-brand-600 rounded" title="Editează">
                <svg class="w-3.5 h-3.5" 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.stop="deleteItem('brand', b)" class="p-1 text-slate-400 hover:text-rose-600 rounded" title="Șterge">
                <svg class="w-3.5 h-3.5" 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>
            </div>
            <svg x-show="selectedBrandId === b.id" class="w-4 h-4 text-brand-500 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
          </div>
        </template>
      </div>
    </div>

    <!-- ============ COL 2: MODELS ============ -->
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden flex flex-col" style="min-height: 500px;">
      <div class="px-4 py-3 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
        <div>
          <h2 class="text-sm font-semibold text-slate-900">Model</h2>
          <div class="text-[11px] text-slate-500" x-text="selectedBrand() ? 'pentru ' + selectedBrand().name : 'selectează un brand'"></div>
        </div>
        <div class="flex items-center gap-1">
          <button @click="openAdd('model')" :disabled="!selectedBrandId"
            class="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1.5 text-white bg-brand-600 hover:bg-brand-700 rounded-md transition disabled:opacity-30 disabled:cursor-not-allowed" title="Adaugă unul">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
            Adaugă
          </button>
          <button @click="openBulk('model')" :disabled="!selectedBrandId"
            class="inline-flex items-center gap-1 text-xs font-medium px-2 py-1.5 text-brand-700 bg-brand-50 hover:bg-brand-100 rounded-md transition disabled:opacity-30 disabled:cursor-not-allowed" title="Adaugă listă (unul pe linie)">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
            Listă
          </button>
        </div>
      </div>

      <div class="flex-1 overflow-y-auto divide-y divide-slate-100">
        <template x-if="!selectedBrandId">
          <div class="p-8 text-center text-xs text-slate-400">Selectează un brand din stânga.</div>
        </template>
        <template x-if="selectedBrandId && filteredModels().length === 0">
          <div class="p-8 text-center text-xs text-slate-400">Niciun model încă pentru acest brand.</div>
        </template>
        <template x-for="m in filteredModels()" :key="m.id">
          <div @click="selectModel(m.id)"
               class="px-3 py-2.5 flex items-center gap-2 cursor-pointer hover:bg-slate-50 group transition"
               :class="selectedModelId === m.id ? 'bg-brand-50 hover:bg-brand-50' : ''">
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-slate-800 truncate" x-text="m.name"></div>
              <div class="text-[11px] text-slate-500" x-text="seriesCount(m.id) + ' serii'"></div>
            </div>
            <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition">
              <button @click.stop="openEdit('model', m)" class="p-1 text-slate-400 hover:text-brand-600 rounded" title="Editează">
                <svg class="w-3.5 h-3.5" 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.stop="deleteItem('model', m)" class="p-1 text-slate-400 hover:text-rose-600 rounded" title="Șterge">
                <svg class="w-3.5 h-3.5" 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>
            </div>
            <svg x-show="selectedModelId === m.id" class="w-4 h-4 text-brand-500 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
          </div>
        </template>
      </div>
    </div>

    <!-- ============ COL 3: SERIES ============ -->
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden flex flex-col" style="min-height: 500px;">
      <div class="px-4 py-3 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
        <div>
          <h2 class="text-sm font-semibold text-slate-900">Serie</h2>
          <div class="text-[11px] text-slate-500" x-text="selectedModel() ? 'pentru ' + selectedModel().name : 'selectează un model'"></div>
        </div>
        <div class="flex items-center gap-1">
          <button @click="openAdd('series')" :disabled="!selectedModelId"
            class="inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1.5 text-white bg-brand-600 hover:bg-brand-700 rounded-md transition disabled:opacity-30 disabled:cursor-not-allowed" title="Adaugă una">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
            Adaugă
          </button>
          <button @click="openBulk('series')" :disabled="!selectedModelId"
            class="inline-flex items-center gap-1 text-xs font-medium px-2 py-1.5 text-brand-700 bg-brand-50 hover:bg-brand-100 rounded-md transition disabled:opacity-30 disabled:cursor-not-allowed" title="Adaugă listă (una pe linie)">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
            Listă
          </button>
        </div>
      </div>

      <div class="flex-1 overflow-y-auto divide-y divide-slate-100">
        <template x-if="!selectedModelId">
          <div class="p-8 text-center text-xs text-slate-400">Selectează un model din mijloc.</div>
        </template>
        <template x-if="selectedModelId && filteredSeries().length === 0">
          <div class="p-8 text-center text-xs text-slate-400">Nicio serie încă pentru acest model.</div>
        </template>
        <template x-for="s in filteredSeries()" :key="s.id">
          <div class="px-3 py-2.5 flex items-center gap-2 group hover:bg-slate-50 transition">
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-slate-800 truncate" x-text="s.name"></div>
              <div class="text-[11px] text-slate-400 truncate" x-show="s.notes" x-text="s.notes"></div>
            </div>
            <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition">
              <button @click="openEdit('series', s)" class="p-1 text-slate-400 hover:text-brand-600 rounded" title="Editează">
                <svg class="w-3.5 h-3.5" 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="deleteItem('series', s)" class="p-1 text-slate-400 hover:text-rose-600 rounded" title="Șterge">
                <svg class="w-3.5 h-3.5" 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>
            </div>
          </div>
        </template>
      </div>
    </div>

  </div>

  <!-- Tips -->
  <div class="mt-4 bg-sky-50 border border-sky-200 rounded-xl p-3 text-xs text-sky-900">
    💡 <strong>Tip:</strong> Click pe un brand → se populează coloana Model. Click pe un model → se populează coloana Serie.
    Ștergerea unui brand șterge cascadat toate modelele și seriile lui.
  </div>

  <!-- ============== BULK ADD MODAL ============== -->
  <div x-show="bulkOpen" x-cloak @keydown.escape.window="bulkOpen = false"
       x-data="{ _bg: false }"
       @mousedown.self="_bg = true"
       @mouseup="if (_bg && $event.target === $el) bulkOpen = 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="submitBulk()">
        <div class="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
          <div>
            <h3 class="font-semibold text-slate-900" x-text="bulkTitle()"></h3>
            <p class="text-xs text-slate-500 mt-0.5" x-text="bulkSubtitle()"></p>
          </div>
          <button type="button" @click="bulkOpen = 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">Listă (un nume pe linie) *</label>
            <textarea x-model="bulkText" required rows="10"
              x-init="$nextTick(() => $el.focus())"
              :placeholder="bulkPlaceholder()"
              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="parsedBulkLines().length"></span> nume detectate ·
              cele care există deja vor fi sărite automat.
            </p>
          </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="bulkOpen = 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 || parsedBulkLines().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ă lista'"></span>
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- ============== ADD/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-md">
      <form @submit.prevent="submitForm()">
        <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="modalTitle()"></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 *</label>
            <input type="text" x-model="formData.name" required maxlength="255"
              x-init="$nextTick(() => $el.focus())"
              :placeholder="modalPlaceholder()"
              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">Notes (opțional)</label>
            <textarea x-model="formData.notes" rows="2" maxlength="500"
              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 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 phoneTree({ brands, models, series, csrf }) {
  return {
    brands, models, series, csrf,
    selectedBrandId: null,
    selectedModelId: null,
    modalOpen: false,
    saving: false,
    formLevel: 'brand',     // brand | model | series
    formData: { id: 0, name: '', notes: '', parent_id: 0 },
    bulkOpen: false,
    bulkLevel: 'brand',
    bulkText: '',
    bulkParentId: 0,

    sortedBrands() {
      return [...this.brands].sort((a,b) => a.name.localeCompare(b.name, 'ro'));
    },
    selectedBrand() { return this.brands.find(b => b.id === this.selectedBrandId); },
    selectedModel() { return this.models.find(m => m.id === this.selectedModelId); },

    filteredModels() {
      if (!this.selectedBrandId) return [];
      return this.models
        .filter(m => m.brand_id === this.selectedBrandId)
        .sort((a,b) => a.name.localeCompare(b.name, 'ro', { numeric: true }));
    },
    filteredSeries() {
      if (!this.selectedModelId) return [];
      return this.series
        .filter(s => s.model_id === this.selectedModelId)
        .sort((a,b) => a.name.localeCompare(b.name, 'ro', { numeric: true }));
    },

    modelsCount(brandId) { return this.models.filter(m => m.brand_id === brandId).length; },
    seriesCount(modelId) { return this.series.filter(s => s.model_id === modelId).length; },

    selectBrand(id) {
      this.selectedBrandId = id;
      this.selectedModelId = null;
    },
    selectModel(id) { this.selectedModelId = id; },

    // ---------- modal ----------
    modalTitle() {
      const labels = { brand: 'Brand', model: 'Model', series: 'Serie' };
      return (this.formData.id ? 'Editează ' : 'Adaugă ') + labels[this.formLevel].toLowerCase();
    },
    modalPlaceholder() {
      return { brand: 'ex: Apple', model: 'ex: iPhone', series: 'ex: 13 Pro' }[this.formLevel];
    },

    openAdd(level) {
      this.formLevel = level;
      const parent = level === 'model' ? this.selectedBrandId :
                     level === 'series' ? this.selectedModelId : 0;
      this.formData = { id: 0, name: '', notes: '', parent_id: parent };
      this.modalOpen = true;
    },
    openEdit(level, item) {
      this.formLevel = level;
      this.formData = {
        id: item.id, name: item.name, notes: item.notes || '',
        parent_id: level === 'model' ? item.brand_id : (level === 'series' ? item.model_id : 0)
      };
      this.modalOpen = true;
    },

    async submitForm() {
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('action', 'save');
        fd.append('level', this.formLevel);
        fd.append('id', this.formData.id);
        fd.append('name', this.formData.name);
        fd.append('notes', this.formData.notes);
        if (this.formLevel !== 'brand') fd.append('parent_id', this.formData.parent_id);

        const r = await fetch('<?= url('api/phone-tree.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);

        const list = this.formLevel === 'brand' ? this.brands
                   : this.formLevel === 'model' ? this.models
                   : this.series;
        const idx = list.findIndex(x => x.id == data.item.id);
        if (idx >= 0) list[idx] = data.item;
        else list.push(data.item);

        this.modalOpen = false;
      } catch (e) {
        alert('Eroare: ' + e.message);
      } finally {
        this.saving = false;
      }
    },

    // ---------- bulk modal ----------
    bulkTitle() {
      return 'Listă ' + { brand: 'branduri', model: 'modele', series: 'serii' }[this.bulkLevel];
    },
    bulkSubtitle() {
      if (this.bulkLevel === 'brand') return 'Va adăuga toate brand-urile noi.';
      if (this.bulkLevel === 'model') return 'Va adăuga modelele pentru: ' + (this.selectedBrand()?.name || '?');
      return 'Va adăuga seriile pentru: ' + (this.selectedModel()?.name || '?');
    },
    bulkPlaceholder() {
      return {
        brand:  "Apple\nSamsung\nXiaomi\nHuawei",
        model:  "iPhone\niPad\nAirPods",
        series: "13\n13 Pro\n13 Pro Max\n14\n14 Pro\n15",
      }[this.bulkLevel];
    },
    parsedBulkLines() {
      return [...new Set(
        this.bulkText.split(/\r?\n/).map(s => s.trim()).filter(Boolean)
      )];
    },

    openBulk(level) {
      this.bulkLevel = level;
      this.bulkParentId = level === 'model' ? this.selectedBrandId
                        : level === 'series' ? this.selectedModelId : 0;
      this.bulkText = '';
      this.bulkOpen = true;
    },

    async submitBulk() {
      const lines = this.parsedBulkLines();
      if (lines.length === 0) return;
      this.saving = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('action', 'bulk_save');
        fd.append('level', this.bulkLevel);
        if (this.bulkLevel !== 'brand') fd.append('parent_id', this.bulkParentId);
        lines.forEach(n => fd.append('names[]', n));

        const r = await fetch('<?= url('api/phone-tree.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);

        // Replace local rows pentru nivelul + parent-ul respectiv
        const list = this.bulkLevel === 'brand' ? 'brands'
                   : this.bulkLevel === 'model' ? 'models' : 'series';
        if (this.bulkLevel === 'brand') {
          // Lista returnată e completă (fără parent filter pentru brand)
          this[list] = data.items;
        } else {
          // Înlocuiesc doar items pentru parent-ul curent; păstrez restul
          const parentCol = this.bulkLevel === 'model' ? 'brand_id' : 'model_id';
          const others = this[list].filter(x => x[parentCol] !== this.bulkParentId);
          this[list] = [...others, ...data.items];
        }

        alert(`✓ ${data.added} adăugate, ${data.skipped} sărite (existau deja).`);
        this.bulkOpen = false;
      } catch (e) {
        alert('Eroare: ' + e.message);
      } finally {
        this.saving = false;
      }
    },

    async deleteItem(level, item) {
      const labels = { brand: 'brand-ul', model: 'modelul', series: 'seria' };
      const cascadeWarn = level === 'brand'
        ? '\n\nATENȚIE: vor fi șterse cascadat toate modelele și seriile lui!'
        : level === 'model' ? '\n\nATENȚIE: vor fi șterse cascadat toate seriile lui!' : '';
      if (!confirm(`Șterg ${labels[level]} „${item.name}"?${cascadeWarn}`)) return;

      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('action', 'delete');
        fd.append('level', level);
        fd.append('id', item.id);
        const r = await fetch('<?= url('api/phone-tree.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error);

        if (level === 'brand') {
          // cascade: scot și modelele/serii din state local
          const modelIds = this.models.filter(m => m.brand_id === item.id).map(m => m.id);
          this.series = this.series.filter(s => !modelIds.includes(s.model_id));
          this.models = this.models.filter(m => m.brand_id !== item.id);
          this.brands = this.brands.filter(b => b.id !== item.id);
          if (this.selectedBrandId === item.id) { this.selectedBrandId = null; this.selectedModelId = null; }
        } else if (level === 'model') {
          this.series = this.series.filter(s => s.model_id !== item.id);
          this.models = this.models.filter(m => m.id !== item.id);
          if (this.selectedModelId === item.id) this.selectedModelId = null;
        } else {
          this.series = this.series.filter(s => s.id !== item.id);
        }
      } catch (e) {
        alert('Eroare ștergere: ' + e.message);
      }
    }
  };
}
</script>

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