<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/cod-produs-sync.php';

$pageTitle  = 'Cod produs sync';
$breadcrumb = [
    ['label' => 'Comparație conturi', 'url' => url('compare.php')],
    ['label' => 'Cod produs sync'],
];

$dbError = null;
$plan = ['normal' => null, 'fbe' => null, 'rows' => [], 'stats' => ['total' => 0, 'same' => 0, 'diff' => 0, 'missing' => 0, 'syncable' => 0]];
try {
    $plan = cps_build_plan();
} 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.
    <details class="mt-2"><summary class="cursor-pointer">Detalii</summary><pre class="mt-2 text-xs"><?= e($dbError) ?></pre></details>
  </div>
<?php endif; ?>

<div x-data="codProdusSync(
       <?= htmlspecialchars(json_encode($plan['rows']), ENT_QUOTES, 'UTF-8') ?>,
       <?= htmlspecialchars(json_encode($plan['normal']), ENT_QUOTES, 'UTF-8') ?>,
       <?= htmlspecialchars(json_encode($plan['fbe']), ENT_QUOTES, 'UTF-8') ?>
     )">

  <!-- Header -->
  <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-900">Cod produs sync</h1>
      <p class="text-sm text-slate-500 mt-0.5 max-w-3xl">
        Compară <strong>codul de produs</strong> (<code>part_number</code>) al aceluiași produs pe contul
        <span class="font-medium text-sky-700"><?= e($plan['normal']['account_name'] ?? 'normal') ?></span> și pe
        <span class="font-medium text-violet-700"><?= e($plan['fbe']['account_name'] ?? 'FBE') ?></span>.
        Produsele se potrivesc după PNK / EAN. Apasă <strong>Sync →</strong> ca să împingi codul din contul normal pe FBE.
      </p>
    </div>
  </div>

  <?php if (!$plan['normal'] || !$plan['fbe']): ?>
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-12 text-center">
      <h2 class="font-semibold text-slate-900 mb-1">Sunt necesare un cont normal și un cont FBE active</h2>
      <p class="text-sm text-slate-500">Activează ambele conturi eMAG (unul normal, unul FBE) în
        <a href="<?= url('settings.php') ?>" class="text-brand-600 hover:underline">Setări</a>.</p>
    </div>
  <?php else: ?>

  <!-- Sync all + sumar -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-5 mb-5">
    <div class="flex items-start justify-between gap-4 flex-wrap">
      <div class="flex items-center gap-2 flex-wrap">
        <button @click="syncAll()" :disabled="running || syncableCount() === 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 disabled:cursor-not-allowed">
          <span x-show="running" class="spinner"></span>
          <svg x-show="!running" 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="M4 4v5h.582M20 20v-5h-.581M5.5 9a7.5 7.5 0 0113 -2.5M18.5 15a7.5 7.5 0 01-13 2.5"/></svg>
          <span x-text="'Sync all (' + syncableCount() + ')'"></span>
        </button>
        <span class="text-xs text-slate-500">împinge codul din <?= e($plan['normal']['account_name']) ?> → <?= e($plan['fbe']['account_name']) ?></span>
      </div>

      <!-- Statistici -->
      <div class="grid grid-cols-4 gap-2.5 flex-1 min-w-[300px]">
        <div class="bg-slate-50 rounded-lg p-2.5">
          <div class="text-[10px] uppercase tracking-wide text-slate-500 font-medium">Total</div>
          <div class="text-xl font-bold text-slate-900 mt-0.5"><?= (int)$plan['stats']['total'] ?></div>
        </div>
        <div class="bg-amber-50 rounded-lg p-2.5">
          <div class="text-[10px] uppercase tracking-wide text-amber-700 font-medium">Diferite</div>
          <div class="text-xl font-bold text-amber-900 mt-0.5" x-text="countBy('diff')"><?= (int)$plan['stats']['diff'] ?></div>
        </div>
        <div class="bg-rose-50 rounded-lg p-2.5">
          <div class="text-[10px] uppercase tracking-wide text-rose-700 font-medium">Lipsă</div>
          <div class="text-xl font-bold text-rose-900 mt-0.5"><?= (int)$plan['stats']['missing'] ?></div>
        </div>
        <div class="bg-emerald-50 rounded-lg p-2.5">
          <div class="text-[10px] uppercase tracking-wide text-emerald-700 font-medium">Identice</div>
          <div class="text-xl font-bold text-emerald-900 mt-0.5" x-text="countBy('same')"><?= (int)$plan['stats']['same'] ?></div>
        </div>
      </div>
    </div>

    <!-- Progres sync -->
    <template x-if="running || syncDone">
      <div class="mt-4 pt-4 border-t border-slate-100">
        <div class="flex items-center justify-between text-sm mb-2">
          <div class="font-medium text-slate-700">
            <span x-show="running">Sincronizare în progres…</span>
            <span x-show="syncDone && !syncError" class="text-emerald-700">✓ Sync finalizat</span>
            <span x-show="syncError" class="text-rose-700">✗ Sync finalizat cu erori</span>
          </div>
          <div class="text-xs text-slate-500" x-show="running" x-text="doneCount + ' / ' + totalToSync"></div>
        </div>
        <div class="bg-slate-900 text-slate-300 font-mono text-[12px] rounded-lg p-3 max-h-52 overflow-y-auto" x-ref="logBox">
          <template x-for="(line, i) in logLines" :key="i">
            <div class="leading-relaxed" :class="line.type === 'error' ? 'text-rose-400' : (line.type === 'success' ? 'text-emerald-400' : 'text-slate-400')">
              <span class="text-slate-600" x-text="line.time"></span><span x-text="line.text"></span>
            </div>
          </template>
        </div>
      </div>
    </template>
  </div>

  <!-- Filtre -->
  <div class="flex items-center gap-1.5 mb-4 flex-wrap">
    <template x-for="tab in [
        {key:'diff', label:'Diferite'},
        {key:'same', label:'Identice'},
        {key:'missing', label:'Lipsă'},
        {key:'all', label:'Toate'}
      ]" :key="tab.key">
      <button @click="filter = tab.key"
        class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg transition"
        :class="filter === tab.key ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'">
        <span x-text="tab.label"></span>
        <span class="text-xs px-1.5 py-0.5 rounded-full"
          :class="filter === tab.key ? 'bg-white/20' : 'bg-slate-100 text-slate-500'" x-text="tabCount(tab.key)"></span>
      </button>
    </template>
    <div class="flex-1"></div>
    <input type="search" x-model="search" placeholder="Caută nume / cod / PNK…"
      class="px-3 py-1.5 text-sm border border-slate-200 rounded-lg w-64 focus:outline-none focus:ring-2 focus:ring-brand-200 focus:border-brand-400">
  </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>
          <tr class="text-left text-[11px] font-medium text-slate-400 uppercase tracking-wide border-b border-slate-100">
            <th class="px-4 py-3">Produs</th>
            <th class="px-3 py-3">
              <span class="inline-flex items-center gap-1.5"><span class="w-2 h-2 rounded-full bg-sky-400"></span>Cod <?= e($plan['normal']['account_name']) ?></span>
            </th>
            <th class="px-3 py-3">
              <span class="inline-flex items-center gap-1.5"><span class="w-2 h-2 rounded-full bg-violet-400"></span>Cod <?= e($plan['fbe']['account_name']) ?></span>
            </th>
            <th class="px-3 py-3 text-center">Status</th>
            <th class="px-4 py-3 text-right">Acțiune</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-50">
          <template x-for="(row, idx) in rows" :key="idx">
            <tr x-show="visible(row)" x-cloak
                :class="row.status === 'diff' ? 'bg-amber-50/40' : ''">
              <!-- Produs -->
              <td class="px-4 py-3 align-top">
                <div class="font-medium text-slate-800 max-w-[360px] break-words" x-text="row.name || '—'"></div>
                <div class="text-[11px] text-slate-400 font-mono mt-0.5">
                  PNK <span x-text="row.pnk || '—'"></span>
                </div>
              </td>
              <!-- Cod normal -->
              <td class="px-3 py-3 align-top font-mono">
                <div class="text-slate-800" x-text="row.normal_code || '—'"
                     :class="!row.normal_code ? 'text-slate-300' : ''"></div>
                <div class="text-[11px] text-slate-400 mt-0.5">PNK <span x-text="row.normal_pnk || '—'"></span></div>
              </td>
              <!-- Cod FBE -->
              <td class="px-3 py-3 align-top font-mono">
                <div x-text="row.fbe_code || '—'"
                     :class="row.status === 'diff' ? 'text-amber-800 font-semibold' : (!row.fbe_code ? 'text-slate-300' : 'text-slate-800')"></div>
                <div class="text-[11px] text-slate-400 mt-0.5">PNK <span x-text="row.fbe_pnk || '—'"></span></div>
              </td>
              <!-- Status -->
              <td class="px-3 py-3 align-top text-center whitespace-nowrap">
                <span x-show="row.status === 'same'" class="inline-flex items-center gap-1 text-xs font-medium text-emerald-600">
                  <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="M5 13l4 4L19 7"/></svg>
                  Identice
                </span>
                <span x-show="row.status === 'diff'" class="inline-flex items-center gap-1 text-xs font-medium text-amber-700">≠ Diferite</span>
                <span x-show="row.status === 'no_source'" class="text-xs font-medium text-slate-400">fără cod sursă</span>
                <span x-show="row.status === 'missing_fbe'" class="text-xs font-medium text-rose-500">lipsă pe FBE</span>
                <span x-show="row.status === 'missing_normal'" class="text-xs font-medium text-rose-500">lipsă pe normal</span>
              </td>
              <!-- Acțiune -->
              <td class="px-4 py-3 align-top text-right">
                <button x-show="row.syncable" @click="syncOne(idx)" :disabled="running || row._syncing"
                  class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-violet-700 bg-violet-50 hover:bg-violet-100 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed">
                  <span x-show="row._syncing" class="spinner"></span>
                  <svg x-show="!row._syncing" 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="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
                  Sync →
                </button>
                <span x-show="!row.syncable && row.status === 'same'" class="text-xs text-emerald-500">✓</span>
                <span x-show="!row.syncable && row.status !== 'same'" class="text-xs text-slate-300">—</span>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
    <div x-show="!anyVisible()" x-cloak class="p-10 text-center text-sm text-slate-500">
      Niciun rezultat pentru filtrul curent.
    </div>
  </div>

  <?php endif; ?>
</div>

<script>
function codProdusSync(rows, normal, fbe) {
  return {
    rows: (rows || []).map(r => ({ ...r, _syncing: false })),
    normal: normal || {},
    fbe: fbe || {},
    csrf: '<?= e(csrf_token()) ?>',
    filter: 'all',
    search: '',

    // sync state
    running: false,
    syncDone: false,
    syncError: false,
    doneCount: 0,
    totalToSync: 0,
    logLines: [],

    countBy(status) { return this.rows.filter(r => r.status === status).length; },
    syncableCount() { return this.rows.filter(r => r.syncable).length; },
    tabCount(key) {
      if (key === 'missing') return this.rows.filter(r => r.status === 'missing_fbe' || r.status === 'missing_normal').length;
      if (key === 'all') return this.rows.length;
      return this.countBy(key);
    },

    visible(row) {
      if (this.filter === 'diff' && row.status !== 'diff') return false;
      if (this.filter === 'same' && row.status !== 'same') return false;
      if (this.filter === 'missing' && !(row.status === 'missing_fbe' || row.status === 'missing_normal')) return false;
      const q = this.search.trim().toLowerCase();
      if (q) {
        const blob = [row.name, row.pnk, row.ean, row.normal_code, row.fbe_code, row.normal_pnk, row.fbe_pnk]
          .filter(Boolean).join(' ').toLowerCase();
        if (!blob.includes(q)) return false;
      }
      return true;
    },
    anyVisible() { return this.rows.some(r => this.visible(r)); },

    log(text, type = 'info') {
      const t = new Date().toLocaleTimeString('ro-RO');
      this.logLines.push({ time: `[${t}] `, text, type });
      this.$nextTick(() => { if (this.$refs.logBox) this.$refs.logBox.scrollTop = this.$refs.logBox.scrollHeight; });
    },

    async pushRow(row) {
      const fd = new FormData();
      fd.append('csrf_token', this.csrf);
      fd.append('normal_product_id', row.normal_id);
      fd.append('fbe_product_id', row.fbe_id);
      const r = await fetch('<?= url('api/cod-produs-sync.php') ?>', { method: 'POST', body: fd });
      const data = await r.json();
      if (!data.ok) throw new Error(data.error || 'Eroare necunoscută');
      // reflectă noul cod în tabel
      row.fbe_code = data.code;
      row.status = 'same';
      row.syncable = false;
      return data;
    },

    async syncOne(idx) {
      const row = this.rows[idx];
      if (!row || !row.syncable || this.running) return;
      row._syncing = true;
      try {
        await this.pushRow(row);
      } catch (e) {
        alert('Sync eșuat: ' + e.message);
      } finally {
        row._syncing = false;
      }
    },

    async syncAll() {
      if (this.running) return;
      const targets = this.rows.filter(r => r.syncable);
      if (targets.length === 0) return;

      this.running = true;
      this.syncDone = false;
      this.syncError = false;
      this.doneCount = 0;
      this.totalToSync = targets.length;
      this.logLines = [];
      this.log(`Start sync all — ${targets.length} produse`, 'info');

      for (const row of targets) {
        row._syncing = true;
        try {
          const data = await this.pushRow(row);
          this.log(`  ✓ ${row.name || row.pnk}: cod → ${data.code}`, 'success');
        } catch (e) {
          this.syncError = true;
          this.log(`  ✗ ${row.name || row.pnk}: ${e.message}`, 'error');
        } finally {
          row._syncing = false;
          this.doneCount++;
        }
      }

      this.running = false;
      this.syncDone = true;
      this.log(`Gata: ${this.doneCount} procesate.`, this.syncError ? 'error' : 'success');
    },
  };
}
</script>

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