<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/cross-account.php';

$pageTitle  = 'Metadate între conturi';
$breadcrumb = [['label' => 'Metadate între conturi']];

$dbError = null;
$plan    = ['groups' => [], 'stats' => ['eans' => 0, 'fills' => 0, 'conflicts' => 0]];
try {
    $plan = cross_account_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="crossAccountPage()">

  <!-- Header -->
  <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
    <div>
      <h1 class="text-2xl font-bold text-slate-900">Metadate între conturi</h1>
      <p class="text-sm text-slate-500 mt-0.5 max-w-3xl">
        Produsele cu același <code>EAN</code> din conturi diferite ar trebui să aibă aceleași date de produs.
        Aici completăm <strong>golurile</strong> dintr-un cont cu valorile setate în celălalt
        (Cod Oblio, nr. buc/cutie, compatibilitate telefon, volumetrie, notițe).
        <span class="text-slate-400">Valorile existente nu se suprascriu; diferențele reale se raportează ca „conflicte".</span>
      </p>
    </div>
  </div>

  <!-- Sumar + acțiune globală -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-5 mb-5">
    <div class="flex items-center justify-between gap-4 flex-wrap">
      <div class="grid grid-cols-3 gap-3 flex-1 min-w-[260px]">
        <div class="bg-slate-50 rounded-lg p-3">
          <div class="text-[11px] uppercase tracking-wide text-slate-500 font-medium">EAN-uri comune</div>
          <div class="text-2xl font-bold text-slate-900 mt-0.5"><?= (int)$plan['stats']['eans'] ?></div>
        </div>
        <div class="bg-sky-50 rounded-lg p-3">
          <div class="text-[11px] uppercase tracking-wide text-sky-700 font-medium">Completări propuse</div>
          <div class="text-2xl font-bold text-sky-900 mt-0.5"><?= (int)$plan['stats']['fills'] ?></div>
        </div>
        <div class="bg-amber-50 rounded-lg p-3">
          <div class="text-[11px] uppercase tracking-wide text-amber-700 font-medium">Conflicte</div>
          <div class="text-2xl font-bold text-amber-900 mt-0.5"><?= (int)$plan['stats']['conflicts'] ?></div>
        </div>
      </div>
      <?php if ((int)$plan['stats']['fills'] > 0): ?>
      <button @click="propagate(null, $event)" :disabled="busy"
        class="inline-flex items-center gap-2 px-4 py-2.5 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 whitespace-nowrap">
        <span x-show="busy" class="spinner"></span>
        <svg x-show="!busy" 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="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
        <span x-text="busy ? 'Propag…' : 'Propagă toate completările (<?= (int)$plan['stats']['fills'] ?>)'"></span>
      </button>
      <?php endif; ?>
    </div>
  </div>

  <?php if (empty($plan['groups'])): ?>
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-12 text-center">
      <div class="mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center mb-4">
        <svg class="w-7 h-7 text-emerald-600" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
      </div>
      <h2 class="font-semibold text-slate-900 mb-1">Nimic de propagat</h2>
      <p class="text-sm text-slate-500">Nu există EAN-uri prezente în mai multe conturi cu goluri de completat, sau totul e deja sincronizat.</p>
    </div>
  <?php else: ?>

  <div class="space-y-4">
    <?php foreach ($plan['groups'] as $g):
      $fillCount = count($g['fills']);
      $hasConflict = !empty($g['conflicts']);
    ?>
      <div class="bg-white border border-slate-100 rounded-xl shadow-soft overflow-hidden" data-ean="<?= e($g['ean']) ?>">
        <div class="px-5 py-3 border-b border-slate-100 bg-slate-50/60 flex items-center justify-between gap-3 flex-wrap">
          <div class="flex items-center gap-2 text-sm">
            <span class="text-slate-500">EAN</span>
            <span class="font-mono font-semibold text-slate-900"><?= e($g['ean']) ?></span>
            <span class="text-slate-400">·</span>
            <span class="text-slate-500"><?= count($g['members']) ?> conturi</span>
          </div>
          <?php if ($fillCount > 0): ?>
            <button @click="propagate('<?= e($g['ean']) ?>', $event)" :disabled="busy"
              class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-brand-700 bg-brand-50 hover:bg-brand-100 rounded-lg transition disabled:opacity-50">
              <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="M5 12h14M12 5l7 7-7 7"/></svg>
              Propagă (<?= $fillCount ?>)
            </button>
          <?php endif; ?>
        </div>

        <!-- Membri (valori curente per cont) -->
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="text-left text-xs font-medium text-slate-500 uppercase tracking-wide border-b border-slate-100">
                <th class="px-5 py-2.5">Cont</th>
                <th class="px-3 py-2.5">Produs</th>
                <th class="px-3 py-2.5">Cod Oblio</th>
                <th class="px-3 py-2.5 text-right">Nr. buc</th>
                <th class="px-3 py-2.5">Telefon</th>
                <th class="px-3 py-2.5 text-center">Volum.</th>
                <th class="px-3 py-2.5">Notițe</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
              <?php foreach ($g['members'] as $m): ?>
                <tr>
                  <td class="px-5 py-2.5 font-medium text-slate-800 whitespace-nowrap"><?= e($m['account_name'] ?? '—') ?></td>
                  <td class="px-3 py-2.5 text-slate-600 max-w-[260px]"><div class="truncate" title="<?= e($m['product_name']) ?>"><?= e($m['product_name']) ?></div></td>
                  <td class="px-3 py-2.5 font-mono <?= _ca_empty($m['cod_oblio']) ? 'text-slate-300' : 'text-slate-700' ?>"><?= _ca_empty($m['cod_oblio']) ? '—' : e($m['cod_oblio']) ?></td>
                  <td class="px-3 py-2.5 text-right tabular-nums <?= _ca_empty($m['units_per_box']) ? 'text-slate-300' : 'text-slate-700' ?>"><?= _ca_empty($m['units_per_box']) ? '—' : (int)$m['units_per_box'] ?></td>
                  <td class="px-3 py-2.5 <?= _ca_empty($m['phone_label']) ? 'text-slate-300' : 'text-slate-700' ?>"><?= _ca_empty($m['phone_label']) ? '—' : e($m['phone_label']) ?></td>
                  <td class="px-3 py-2.5 text-center"><?= $m['vol_complete'] ? '<span class="text-emerald-600">✓</span>' : '<span class="text-slate-300">—</span>' ?></td>
                  <td class="px-3 py-2.5 <?= _ca_empty($m['notes']) ? 'text-slate-300' : 'text-slate-600' ?> max-w-[180px]"><div class="truncate" title="<?= e($m['notes'] ?? '') ?>"><?= _ca_empty($m['notes']) ? '—' : e($m['notes']) ?></div></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <!-- Completări propuse -->
        <?php if ($fillCount > 0): ?>
          <div class="px-5 py-3 border-t border-slate-100">
            <div class="text-[11px] uppercase tracking-wide text-slate-400 font-semibold mb-2">Se va completa</div>
            <div class="flex flex-wrap gap-2">
              <?php foreach ($g['fills'] as $f): ?>
                <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-sky-50 text-sky-800 text-xs">
                  <span class="font-medium"><?= e($f['account_name'] ?? '—') ?></span>
                  <span class="text-sky-400">·</span>
                  <span class="text-sky-600"><?= e($f['label']) ?>:</span>
                  <span class="font-medium"><?= e(mb_strimwidth((string)$f['to_value'], 0, 48, '…')) ?></span>
                </span>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>

        <!-- Conflicte -->
        <?php if ($hasConflict): ?>
          <div class="px-5 py-3 border-t border-amber-100 bg-amber-50/50">
            <div class="text-[11px] uppercase tracking-wide text-amber-600 font-semibold mb-2 flex items-center gap-1.5">
              <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>
              Conflicte (necesită decizie manuală — nu se ating)
            </div>
            <div class="space-y-1">
              <?php foreach ($g['conflicts'] as $c): ?>
                <div class="text-xs text-amber-900">
                  <span class="font-medium"><?= e($c['field']) ?>:</span>
                  <?php $vals = array_map(fn($v) => mb_strimwidth((string)$v, 0, 40, '…'), $c['values']); ?>
                  <span class="font-mono"><?= e(implode('  ≠  ', $vals)) ?></span>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>
  </div>

  <?php endif; ?>

</div>

<script>
function crossAccountPage() {
  return {
    busy: false,
    csrf: '<?= e(csrf_token()) ?>',

    async propagate(ean, ev) {
      if (this.busy) return;
      const label = ean ? `pentru EAN ${ean}` : 'pentru toate EAN-urile';
      if (!confirm(`Propag completările ${label}?\nSe completează doar câmpurile goale; nimic existent nu se suprascrie.`)) return;
      this.busy = true;
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        if (ean) fd.append('ean', ean);
        const r = await fetch('<?= url('api/cross-account-propagate.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error || 'Eroare');
        // Reîncarcă pentru a reflecta noile valori și a recalcula planul.
        window.location.reload();
      } catch (e) {
        alert('Eroare la propagare: ' + e.message);
        this.busy = false;
      }
    }
  };
}
</script>

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