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

$pageTitle  = 'Comparație conturi';
$breadcrumb = [['label' => 'Comparație conturi']];

$dbError = null;
$plan    = ['accounts' => [], 'groups' => [], 'stats' => ['total' => 0, 'ok' => 0, 'diff' => 0, 'missing' => 0], 'fields' => []];
try {
    $plan = compare_build_plan();
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

$accounts = $plan['accounts'];
$fields   = $plan['fields'] ?? [];

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; ?>

<?php
  // Metadata grupuri pentru filtrarea reactivă (folosită și de x-data mai jos).
  $jsItems = [];
  foreach ($plan['groups'] as $g) {
    $parts = [$g['label'], $g['rep_name']];
    foreach ($g['by_account'] as $members) {
      foreach ($members as $m) {
        $parts[] = $m['product_name']; $parts[] = $m['ean'];
        $parts[] = $m['pnk']; $parts[] = $m['emag_part_number'];
      }
    }
    $jsItems[] = ['status' => $g['status'], 'blob' => mb_strtolower(implode(' ', array_filter($parts)))];
  }
?>
<div x-data="comparePage(<?= htmlspecialchars(json_encode(array_map(fn($a) => ['id' => (int)$a['id'], 'account_name' => $a['account_name'], 'is_fbe' => (int)$a['is_fbe']], $accounts)), ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars(json_encode($jsItems), 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">Comparație produse între conturi</h1>
      <p class="text-sm text-slate-500 mt-0.5 max-w-3xl">
        Verifică <strong>nume</strong>, <code>EAN</code>, <code>PNK</code> și <strong>cod produs</strong> pentru
        același produs pe conturile eMAG. Produsele se potrivesc după EAN sau PNK; diferențele sunt
        <span class="px-1 rounded bg-amber-100 text-amber-800">evidențiate</span>.
      </p>
    </div>
  </div>

  <!-- Sync + 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">
      <!-- Butoane sync per cont -->
      <div class="flex items-center gap-2 flex-wrap">
        <template x-for="acc in accounts" :key="acc.id">
          <button @click="syncOne(acc.id)" :disabled="running"
            class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium rounded-lg shadow-soft transition disabled:opacity-50 disabled:cursor-not-allowed"
            :class="acc.is_fbe ? 'text-violet-700 bg-violet-50 hover:bg-violet-100' : 'text-sky-700 bg-sky-50 hover:bg-sky-100'">
            <span x-show="running && syncingId === acc.id" class="spinner"></span>
            <svg x-show="!(running && syncingId === acc.id)" 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 ' + acc.account_name"></span>
          </button>
        </template>
        <button @click="syncAll()" :disabled="running || accounts.length < 2"
          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 && syncingId === 'all'" class="spinner"></span>
          <svg x-show="!(running && syncingId === 'all')" 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>
          Sync ambele conturi
        </button>
      </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">Diferențe</div>
          <div class="text-xl font-bold text-amber-900 mt-0.5"><?= (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ă cont</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"><?= (int)$plan['stats']['ok'] ?></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 — reîncarc comparația…</span>
            <span x-show="syncError" class="text-rose-700">✗ Sync eșuat</span>
          </div>
          <div class="text-xs text-slate-500" x-show="running">Pagina <span x-text="currentPage"></span></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>

  <?php if (count($accounts) < 2): ?>
    <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 cel puțin 2 conturi active</h2>
      <p class="text-sm text-slate-500">Activează ambele conturi eMAG în <a href="<?= url('settings.php') ?>" class="text-brand-600 hover:underline">Setări</a> pentru a compara.</p>
    </div>
  <?php elseif (empty($plan['groups'])): ?>
    <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">Niciun produs de comparat</h2>
      <p class="text-sm text-slate-500">Rulează un sync pentru fiecare cont ca să populezi produsele.</p>
    </div>
  <?php else: ?>

  <!-- Filtre -->
  <div class="flex items-center gap-1.5 mb-4 flex-wrap">
    <?php
      $tabs = [
        'diff'    => ['Diferențe', (int)$plan['stats']['diff'], 'amber'],
        'missing' => ['Lipsă cont', (int)$plan['stats']['missing'], 'rose'],
        'ok'      => ['Identice', (int)$plan['stats']['ok'], 'emerald'],
        'all'     => ['Toate', (int)$plan['stats']['total'], 'slate'],
      ];
      foreach ($tabs as $key => [$lbl, $cnt, $color]):
    ?>
      <button @click="filter = '<?= $key ?>'"
        class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg transition"
        :class="filter === '<?= $key ?>' ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'">
        <?= e($lbl) ?>
        <span class="text-xs px-1.5 py-0.5 rounded-full"
          :class="filter === '<?= $key ?>' ? 'bg-white/20' : 'bg-slate-100 text-slate-500'"><?= $cnt ?></span>
      </button>
    <?php endforeach; ?>
    <div class="flex-1"></div>
    <input type="search" x-model="search" placeholder="Caută nume / EAN / PNK / cod…"
      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>

  <!-- Grupuri -->
  <div class="space-y-3">
    <?php foreach ($plan['groups'] as $gi => $g):
      $statusMeta = [
        'diff'    => ['border-amber-200',  'bg-amber-50/40',  'text-amber-700',   'Diferențe'],
        'missing' => ['border-rose-200',   'bg-rose-50/40',   'text-rose-700',    'Lipsă într-un cont'],
        'ok'      => ['border-slate-100',  'bg-white',        'text-emerald-600', 'Identice'],
      ][$g['status']];
      // Text de căutare (nume + toate valorile)
      $searchParts = [$g['label'], $g['rep_name']];
      foreach ($g['by_account'] as $members) {
        foreach ($members as $m) {
          $searchParts[] = $m['product_name']; $searchParts[] = $m['ean'];
          $searchParts[] = $m['pnk']; $searchParts[] = $m['emag_part_number'];
        }
      }
      $searchBlob = mb_strtolower(implode(' ', array_filter($searchParts)));
    ?>
      <div class="border rounded-xl shadow-soft overflow-hidden <?= $statusMeta[0] ?> <?= $statusMeta[1] ?>"
           x-show="matches('<?= $g['status'] ?>', <?= htmlspecialchars(json_encode($searchBlob), ENT_QUOTES) ?>)"
           x-cloak>
        <!-- Header grup -->
        <div class="px-4 py-2.5 flex items-center justify-between gap-3 border-b border-slate-100/70 bg-white/50">
          <div class="flex items-center gap-2 text-sm min-w-0 flex-1">
            <span class="text-[10px] uppercase tracking-wide font-semibold text-slate-400 flex-shrink-0"><?= e($g['label_kind'] ?? '—') ?></span>
            <span class="font-mono font-semibold text-slate-900 flex-shrink-0"><?= e($g['label'] ?? '—') ?></span>
            <span class="text-slate-300 flex-shrink-0">·</span>
            <span class="text-slate-500 truncate min-w-0" title="<?= e($g['rep_name'] ?? '') ?>"><?= e($g['rep_name'] ?? '') ?></span>
          </div>
          <span class="inline-flex items-center gap-1 text-xs font-medium whitespace-nowrap flex-shrink-0 <?= $statusMeta[2] ?>">
            <?php if ($g['status'] === 'ok'): ?>
              <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>
            <?php else: ?>
              <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="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
            <?php endif; ?>
            <?= e($statusMeta[3]) ?>
          </span>
        </div>

        <!-- Tabel câmp × cont -->
        <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">
                <th class="px-4 py-2 w-28">Câmp</th>
                <?php foreach ($accounts as $a): ?>
                  <th class="px-3 py-2">
                    <span class="inline-flex items-center gap-1.5">
                      <span class="w-2 h-2 rounded-full <?= (int)$a['is_fbe'] ? 'bg-violet-400' : 'bg-sky-400' ?>"></span>
                      <?= e($a['account_name']) ?>
                    </span>
                  </th>
                <?php endforeach; ?>
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
              <?php foreach ($fields as $fkey => $flabel):
                $isDiff = $g['field_diffs'][$fkey] ?? false;
              ?>
                <tr class="<?= $isDiff ? 'bg-amber-50/70' : '' ?>">
                  <td class="px-4 py-2 text-xs font-medium <?= $isDiff ? 'text-amber-700' : 'text-slate-400' ?> align-top">
                    <?= e($flabel) ?>
                    <?php if ($isDiff): ?><span class="ml-1">≠</span><?php endif; ?>
                  </td>
                  <?php foreach ($accounts as $a):
                    $aid = (int)$a['id'];
                    $members = $g['by_account'][$aid] ?? [];
                    if (!$members):
                  ?>
                    <td class="px-3 py-2">
                      <span class="text-xs text-rose-400 italic">lipsește</span>
                    </td>
                  <?php else:
                      // Valori distincte pe câmp în cadrul contului (de regulă una singură).
                      $vals = [];
                      foreach ($members as $m) {
                        $v = $m[$fkey];
                        if ($v !== null) $vals[$v] = true;
                      }
                      $vals = array_keys($vals);
                      $mono = in_array($fkey, ['ean', 'pnk', 'emag_part_number'], true);
                  ?>
                    <td class="px-3 py-2 <?= $mono ? 'font-mono' : '' ?> <?= $isDiff ? 'text-amber-900 font-medium' : 'text-slate-700' ?>">
                      <?php if (!$vals): ?>
                        <span class="text-slate-300">—</span>
                      <?php else: ?>
                        <?php foreach ($vals as $v): ?>
                          <div class="<?= $fkey === 'product_name' ? 'max-w-[420px]' : '' ?> break-words"><?= e($v) ?></div>
                        <?php endforeach; ?>
                      <?php endif; ?>
                    </td>
                  <?php endif; endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endforeach; ?>

    <!-- Gol după filtrare -->
    <div x-show="!anyVisible()" x-cloak class="bg-white border border-slate-100 rounded-xl shadow-soft p-10 text-center text-sm text-slate-500">
      Niciun rezultat pentru filtrul curent.
    </div>
  </div>

  <?php endif; ?>

</div>

<script>
function comparePage(accounts, items) {
  return {
    accounts,
    items: items || [],
    filter: <?= (int)$plan['stats']['diff'] > 0 ? "'diff'" : ((int)$plan['stats']['missing'] > 0 ? "'missing'" : "'all'") ?>,
    search: '',
    csrf: '<?= e(csrf_token()) ?>',

    // sync state
    running: false,
    syncingId: null,
    syncDone: false,
    syncError: false,
    currentPage: 0,
    logLines: [],

    matches(status, blob) {
      if (this.filter !== 'all' && this.filter !== status) return false;
      const q = this.search.trim().toLowerCase();
      if (q && !blob.includes(q)) return false;
      return true;
    },

    anyVisible() {
      return this.items.some(it => this.matches(it.status, it.blob));
    },

    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 syncAccount(accountId, accountName) {
      this.log(`Start sync „${accountName}”`, 'info');
      let page = 1, safety = 200;
      const totals = { new: 0, updated: 0, errors: 0, excluded: 0, processed: 0 };

      while (safety-- > 0) {
        this.currentPage = page;
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('action', 'page');
        fd.append('account_id', accountId);
        fd.append('page', page);
        const r = await fetch('<?= url('api/emag-sync.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error || 'Eroare necunoscută');

        totals.new += data.stats.new;
        totals.updated += data.stats.updated;
        totals.errors += data.stats.errors;
        totals.excluded += (data.stats.excluded || 0) + (data.stats.excluded_category || 0);
        totals.processed += data.processed;
        this.log(`  ✓ pag ${page}: ${data.processed} produse | +${data.stats.new} noi · ~${data.stats.updated} update · ${data.stats.errors} erori`, 'success');
        (data.errors_log || []).forEach(m => this.log(`  ⚠ ${m}`, 'error'));

        if (!data.has_more || data.processed === 0) break;
        page = data.next_page;
      }

      // Finalize
      const status = totals.errors === 0 ? 'success' : (totals.new + totals.updated > 0 ? 'partial' : 'failed');
      const fd2 = new FormData();
      fd2.append('csrf_token', this.csrf);
      fd2.append('action', 'finalize');
      fd2.append('account_id', accountId);
      fd2.append('new', totals.new);
      fd2.append('updated', totals.updated);
      fd2.append('errors', totals.errors);
      fd2.append('status', status);
      await fetch('<?= url('api/emag-sync.php') ?>', { method: 'POST', body: fd2 });
      this.log(`✓ „${accountName}”: ${totals.new} noi, ${totals.updated} actualizate, ${totals.errors} erori`, 'success');
      return totals;
    },

    async run(ids, syncingId) {
      if (this.running) return;
      this.running = true;
      this.syncDone = false;
      this.syncError = false;
      this.syncingId = syncingId;
      this.currentPage = 0;
      this.logLines = [];
      try {
        for (const id of ids) {
          const acc = this.accounts.find(a => a.id == id);
          await this.syncAccount(id, acc ? acc.account_name : ('#' + id));
        }
        this.syncDone = true;
        this.log('Reîncarc pagina pentru a recalcula comparația…', 'info');
        setTimeout(() => window.location.reload(), 900);
      } catch (e) {
        this.log(`✗ EROARE: ${e.message}`, 'error');
        this.syncError = true;
      } finally {
        this.running = false;
      }
    },

    syncOne(id) { this.run([id], id); },
    syncAll() { this.run(this.accounts.map(a => a.id), 'all'); },
  };
}
</script>

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