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

$pageTitle  = 'Sync eMAG';
$breadcrumb = [['label' => 'Sync eMAG']];

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

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

<div x-data="syncPage(<?= htmlspecialchars(json_encode($accounts), ENT_QUOTES, 'UTF-8') ?>, <?= active_account_id() ?>)" class="max-w-4xl">

  <div class="mb-6">
    <h1 class="text-2xl font-bold text-slate-900">Sincronizare cu eMAG</h1>
    <p class="text-sm text-slate-500 mt-0.5">Importă sau actualizează produsele dintr-un cont eMAG. Match după <code>emag_id</code>, fallback EAN / PNK.</p>
  </div>

  <!-- Empty state -->
  <template x-if="accounts.length === 0">
    <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-amber-50 flex items-center justify-center mb-4">
        <svg class="w-7 h-7 text-amber-600" fill="none" stroke="currentColor" stroke-width="1.5" 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>
      </div>
      <h2 class="font-semibold text-slate-900 mb-1">Niciun cont activ</h2>
      <p class="text-sm text-slate-500 mb-4">Adaugă și activează un cont eMAG pentru a începe sincronizarea.</p>
      <a href="<?= url('settings.php') ?>" 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 transition">
        Mergi la Setări
      </a>
    </div>
  </template>

  <template x-if="accounts.length > 0">
  <div class="space-y-4">

    <!-- Configurare sync -->
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-5">
      <label class="block text-xs font-medium text-slate-700 mb-2">Selectează contul</label>
      <div class="grid grid-cols-1 md:grid-cols-3 gap-2">
        <template x-for="acc in accounts" :key="acc.id">
          <label class="relative cursor-pointer">
            <input type="radio" name="account" :value="acc.id" x-model.number="selectedAccount" class="peer sr-only" :disabled="running">
            <div class="border-2 rounded-lg p-3 transition peer-checked:border-brand-500 peer-checked:bg-brand-50 border-slate-200 hover:border-slate-300">
              <div class="font-medium text-sm text-slate-900 truncate" x-text="acc.account_name"></div>
              <div class="text-xs text-slate-500 font-mono truncate mt-0.5" x-text="acc.username"></div>
              <div class="text-[11px] text-slate-400 mt-1.5" x-text="acc.last_sync_at ? 'Ultim sync: ' + formatDate(acc.last_sync_at) : 'Niciodată sincronizat'"></div>
            </div>
          </label>
        </template>
      </div>

      <div class="mt-5 flex items-center justify-between gap-3">
        <div class="text-xs text-slate-500">
          Sincronizarea citește produsele paginat (<?= EMAG_PAGE_SIZE ?> per pagină) și face upsert după <code>emag_id → EAN → PNK</code>.
        </div>
        <button @click="start()" :disabled="!selectedAccount || running"
          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">
          <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="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
          <span x-show="running" class="spinner"></span>
          <span x-text="running ? 'Sincronizez…' : 'Pornește sync'"></span>
        </button>
      </div>
    </div>

    <!-- Progress -->
    <template x-if="running || done">
      <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-5">

        <!-- Bar -->
        <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="done && !error" class="text-emerald-700">✓ Sincronizare finalizată</span>
            <span x-show="error" class="text-rose-700">✗ Sincronizare eșuată</span>
          </div>
          <div class="text-xs text-slate-500">
            Pagina <span x-text="currentPage"></span><span x-show="totalKnown !== null"> · <span x-text="estimatedPages()"></span> estimate</span>
          </div>
        </div>

        <div class="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
          <div class="h-full bg-gradient-to-r from-brand-500 to-brand-600 transition-all duration-300"
               :style="`width: ${progressPercent()}%`"></div>
        </div>

        <!-- Live stats -->
        <div class="mt-5 grid grid-cols-2 sm:grid-cols-5 gap-3">
          <div class="bg-emerald-50 rounded-lg p-3">
            <div class="text-[11px] uppercase tracking-wide text-emerald-700 font-medium">Noi</div>
            <div class="text-xl font-bold text-emerald-900 mt-0.5" x-text="totals.new"></div>
          </div>
          <div class="bg-sky-50 rounded-lg p-3">
            <div class="text-[11px] uppercase tracking-wide text-sky-700 font-medium">Actualizate</div>
            <div class="text-xl font-bold text-sky-900 mt-0.5" x-text="totals.updated"></div>
          </div>
          <div class="bg-amber-50 rounded-lg p-3">
            <div class="text-[11px] uppercase tracking-wide text-amber-700 font-medium">Excluse</div>
            <div class="text-xl font-bold text-amber-900 mt-0.5" x-text="totals.excluded"></div>
          </div>
          <div class="bg-rose-50 rounded-lg p-3">
            <div class="text-[11px] uppercase tracking-wide text-rose-700 font-medium">Erori</div>
            <div class="text-xl font-bold text-rose-900 mt-0.5" x-text="totals.errors"></div>
          </div>
          <div class="bg-slate-50 rounded-lg p-3">
            <div class="text-[11px] uppercase tracking-wide text-slate-600 font-medium">Procesate</div>
            <div class="text-xl font-bold text-slate-900 mt-0.5" x-text="totals.processed"></div>
          </div>
        </div>

        <!-- Log live -->
        <div class="mt-5">
          <div class="text-xs font-medium text-slate-700 mb-1.5">Log</div>
          <div class="bg-slate-900 text-slate-300 font-mono text-[12px] rounded-lg p-3 max-h-64 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>
            <template x-if="logLines.length === 0">
              <div class="text-slate-600 italic">Așteptare…</div>
            </template>
          </div>
        </div>

        <template x-if="done && !error">
          <div class="mt-4 flex items-center justify-between">
            <a href="<?= url('products.php') ?>" class="text-sm text-brand-600 hover:text-brand-700 font-medium">→ Vezi produsele</a>
            <button @click="reset()" class="text-sm text-slate-500 hover:text-slate-700">Rulează un alt sync</button>
          </div>
        </template>
      </div>
    </template>

  </div>
  </template>

</div>

<script>
function syncPage(accounts, activeId) {
  // Preselectează contul activ (din header) dacă e printre conturile active;
  // altfel, dacă există un singur cont, îl alege pe acela.
  const preselected = (activeId && accounts.some(a => a.id == activeId))
    ? Number(activeId)
    : (accounts.length === 1 ? accounts[0].id : null);
  return {
    accounts,
    selectedAccount: preselected,
    running: false,
    done: false,
    error: false,
    currentPage: 0,
    totalKnown: null,
    totals: { new: 0, updated: 0, errors: 0, excluded: 0, processed: 0 },
    logLines: [],
    csrf: '<?= e(csrf_token()) ?>',

    formatDate(s) {
      if (!s) return '—';
      const d = new Date(s.replace(' ', 'T'));
      return d.toLocaleDateString('ro-RO') + ' ' + d.toLocaleTimeString('ro-RO', {hour:'2-digit', minute:'2-digit'});
    },

    progressPercent() {
      if (this.done) return 100;
      if (this.totalKnown !== null && this.totalKnown > 0) {
        return Math.min(99, Math.round((this.totals.processed / this.totalKnown) * 100));
      }
      // fără total cunoscut: progres "stilizat" în funcție de pagini
      return Math.min(95, this.currentPage * 8);
    },

    estimatedPages() {
      if (!this.totalKnown) return '?';
      return Math.ceil(this.totalKnown / <?= EMAG_PAGE_SIZE ?>);
    },

    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; });
    },

    reset() {
      this.running = false; this.done = false; this.error = false;
      this.currentPage = 0; this.totalKnown = null;
      this.totals = { new: 0, updated: 0, errors: 0, excluded: 0, processed: 0 };
      this.logLines = [];
    },

    async start() {
      if (!this.selectedAccount) return;
      this.reset();
      this.running = true;
      const acc = this.accounts.find(a => a.id == this.selectedAccount);
      this.log(`Start sync pentru „${acc.account_name}”`, 'info');

      let page = 1;
      let safety = 200; // max ~20.000 produse

      try {
        while (safety-- > 0) {
          this.currentPage = page;
          this.log(`→ Pagina ${page}…`);

          const fd = new FormData();
          fd.append('csrf_token', this.csrf);
          fd.append('action', 'page');
          fd.append('account_id', this.selectedAccount);
          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ă');

          this.totals.new       += data.stats.new;
          this.totals.updated   += data.stats.updated;
          this.totals.errors    += data.stats.errors;
          this.totals.excluded  += (data.stats.excluded || 0) + (data.stats.excluded_category || 0);
          this.totals.processed += data.processed;
          if (data.total_known != null) this.totalKnown = data.total_known;

          const exParts = [];
          if (data.stats.excluded > 0)          exParts.push(`${data.stats.excluded} EAN`);
          if (data.stats.excluded_category > 0) exParts.push(`${data.stats.excluded_category} categorie`);
          const exMsg = exParts.length ? ` · ${exParts.join(' + ')} excluse` : '';
          const nfMsg = (data.stats.name_fixed > 0) ? ` · ${data.stats.name_fixed} nume FBE corectate` : '';
          this.log(`  ✓ ${data.processed} produse | +${data.stats.new} noi · ~${data.stats.updated} update · ${data.stats.errors} erori${exMsg}${nfMsg}`, '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 = this.totals.errors === 0 ? 'success' : (this.totals.new + this.totals.updated > 0 ? 'partial' : 'failed');
        const fd2 = new FormData();
        fd2.append('csrf_token', this.csrf);
        fd2.append('action', 'finalize');
        fd2.append('account_id', this.selectedAccount);
        fd2.append('new', this.totals.new);
        fd2.append('updated', this.totals.updated);
        fd2.append('errors', this.totals.errors);
        fd2.append('status', status);
        await fetch('<?= url('api/emag-sync.php') ?>', { method: 'POST', body: fd2 });

        this.log(`✓ FINALIZAT: ${this.totals.new} noi, ${this.totals.updated} actualizate, ${this.totals.excluded} excluse, ${this.totals.errors} erori`, 'success');
        this.done = true;
      } catch (e) {
        this.log(`✗ EROARE: ${e.message}`, 'error');
        this.error = true;
        this.done = true;
      } finally {
        this.running = false;
      }
    }
  };
}
</script>

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