<?php
require_once __DIR__ . '/config.php';

// Pe hosting, dacă instalarea nu e făcută (lipsește data/.installed), redirect la install.php.
// Local rămâne neafectat (creăm lock-ul o dată). install.php nu se auto-redirectează.
if (!is_file(DATA_PATH . '/.installed')
    && basename($_SERVER['SCRIPT_NAME'] ?? '') !== 'install.php') {
    $base = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
    header('Location: ' . $base . '/install.php');
    exit;
}

require_once __DIR__ . '/db.php';
$pageTitle = $pageTitle ?? 'Dashboard';
$breadcrumb = $breadcrumb ?? [['label' => $pageTitle]];

// Cont activ (context global selectat din header)
$activeAccounts    = active_accounts_list();
$activeAccountId   = active_account_id();
$activeAccountName = 'Toate conturile';
foreach ($activeAccounts as $a) {
    if ((int)$a['id'] === $activeAccountId) { $activeAccountName = $a['account_name']; break; }
}
?>
<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= e($pageTitle) ?> · <?= e(APP_NAME) ?></title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
  theme: {
    extend: {
      fontFamily: { sans: ['Inter','system-ui','sans-serif'] },
      colors: {
        brand: {
          50:  '#eef2ff',
          100: '#e0e7ff',
          500: '#6366f1',
          600: '#4f46e5',
          700: '#4338ca',
        }
      },
      boxShadow: {
        soft: '0 1px 2px rgba(0,0,0,0.04), 0 4px 12px rgba(0,0,0,0.05)',
      }
    }
  }
}
</script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<link rel="stylesheet" href="<?= url('assets/app.css') ?>">
</head>
<body class="bg-slate-50 text-slate-800 antialiased">

<div class="flex min-h-screen"
     x-data="{
       mobileOpen: false,
       sidebarHidden: localStorage.getItem('sidebarHidden') === '1'
     }"
     x-effect="localStorage.setItem('sidebarHidden', sidebarHidden ? '1' : '0')">

  <!-- ============== SIDEBAR ============== -->
  <aside
    class="fixed inset-y-0 left-0 z-40 w-64 bg-slate-900 text-slate-300 flex flex-col transform transition-transform duration-200"
    :class="{
      'translate-x-0': mobileOpen,
      '-translate-x-full': !mobileOpen,
      'md:translate-x-0': !sidebarHidden,
      'md:-translate-x-full': sidebarHidden
    }"
  >
    <!-- Logo -->
    <div class="h-16 flex items-center gap-3 px-6 border-b border-slate-800">
      <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shadow-soft">
        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
        </svg>
      </div>
      <div class="flex-1 min-w-0">
        <div class="text-white font-semibold leading-tight">eMAG Manager</div>
        <div class="text-[11px] text-slate-500">v<?= e(APP_VERSION) ?></div>
      </div>
      <!-- Collapse button (vizibil doar pe desktop) -->
      <button @click="sidebarHidden = true"
              class="hidden md:flex w-7 h-7 items-center justify-center text-slate-400 hover:text-white hover:bg-slate-800 rounded-md transition"
              title="Ascunde meniul">
        <svg 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="M11 19l-7-7 7-7m8 14l-7-7 7-7"/>
        </svg>
      </button>
    </div>

    <!-- Nav -->
    <nav class="flex-1 py-4 space-y-1 overflow-y-auto">
      <?php
      $navItems = [
        ['url' => url('index.php'),        'page' => 'index.php',        'label' => 'Dashboard',  'icon' => 'M3 12l9-9 9 9M5 10v10h14V10'],
        ['url' => url('products.php'),     'page' => 'products.php',     'label' => 'Produse',    'icon' => 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4'],
        ['url' => url('add-product.php'),  'page' => 'add-product.php',  'label' => 'Adaugă',     'icon' => 'M12 4v16m8-8H4'],
        ['url' => url('import-emag.php'),  'page' => 'import-emag.php',  'label' => 'Sync eMAG',  'icon' => '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'],
        ['url' => url('validare.php'),     'page' => 'validare.php',     'label' => 'Validare documentație', 'icon' => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'],
        ['url' => url('receptie.php'),     'page' => 'receptie.php',     'label' => 'Generare recepție', 'icon' => 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4'],
        ['url' => url('labels.php'),       'page' => 'labels.php',       'label' => 'Labeluri', 'icon' => 'M7 7h.01M3 5a2 2 0 012-2h5.586a1 1 0 01.707.293l8 8a2 2 0 010 2.828l-5.586 5.586a2 2 0 01-2.828 0l-8-8A1 1 0 013 10.586V5z'],
        ['url' => url('volumetrie.php'),   'page' => 'volumetrie.php',   'label' => 'Volumetrie', 'icon' => 'M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z M3.27 6.96L12 12.01l8.73-5.05 M12 22.08V12'],
        ['url' => url('prices.php'),       'page' => 'prices.php',       'label' => 'Actualizare prețuri', 'icon' => 'M7 7h.01M3 5a2 2 0 012-2h5.586a1 1 0 01.707.293l8 8a2 2 0 010 2.828l-5.586 5.586a2 2 0 01-2.828 0l-8-8A1 1 0 013 10.586V5z'],
        ['url' => url('stocuri.php'),      'page' => 'stocuri.php',      'label' => 'Stocuri', 'icon' => 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4'],
        ['url' => url('orders.php'),       'page' => 'orders.php',       'label' => 'Orders', 'pages' => ['order.php'],
          'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4',
          'children' => [
            ['url' => url('marfa.php'), 'page' => 'marfa.php', 'label' => 'Marfă'],
            ['url' => url('firma.php'), 'page' => 'firma.php', 'label' => 'Firma mea'],
          ]],
        ['url' => url('cross-account.php'),'page' => 'cross-account.php', 'label' => 'Metadate conturi', 'icon' => 'M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4'],
        ['url' => url('compare.php'),      'page' => 'compare.php',      'label' => 'Comparație conturi', 'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01',
          'children' => [
            ['url' => url('cod-produs-sync.php'), 'page' => 'cod-produs-sync.php', 'label' => 'Cod produs sync'],
          ]],
        ['url' => url('categories.php'),   'page' => 'categories.php',   'label' => 'Categorii',  'icon' => 'M7 7h10M7 12h10M7 17h6M4 4h16v16H4z'],
        ['url' => url('phone-models.php'), 'page' => 'phone-models.php', 'label' => 'Modele telefon', 'icon' => 'M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z'],
        ['url' => url('templates.php'),    'page' => 'templates.php',    'label' => 'Șabloane',       'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
        ['url' => url('title-sessions.php'),'page' => 'title-sessions.php','label' => 'Sesiuni titluri','icon' => 'M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z'],
        ['url' => url('excluded.php'),     'page' => 'excluded.php',     'label' => 'EAN excluse', 'icon' => 'M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728L5.636 5.636m12.728 12.728L18.364 5.636M5.636 18.364l12.728-12.728'],
        ['url' => url('settings.php'),     'page' => 'settings.php',     'label' => 'Setări',     'icon' => 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z'],
      ];
      foreach ($navItems as $item):
        $children   = $item['children'] ?? [];
        $childActive = false;
        foreach ($children as $c) { if (is_page($c['page'])) { $childActive = true; break; } }
        // 'pages' = pagini suplimentare care țin meniul activ (ex: editorul unei comenzi)
        $extraActive = false;
        foreach (($item['pages'] ?? []) as $p) { if (is_page($p)) { $extraActive = true; break; } }
        $active = is_page($item['page']) || $childActive || $extraActive;
      ?>
        <a href="<?= e($item['url']) ?>"
           class="flex items-center gap-3 px-6 py-2.5 text-sm font-medium hover:text-white hover:bg-slate-800/60 transition-all <?= $active ? 'nav-item-active' : '' ?>">
          <svg class="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="<?= e($item['icon']) ?>"/>
          </svg>
          <span><?= e($item['label']) ?></span>
        </a>
        <?php if ($children && $active): ?>
          <?php foreach ($children as $child): $cActive = is_page($child['page']); ?>
            <a href="<?= e($child['url']) ?>"
               class="flex items-center gap-3 pl-14 pr-6 py-2 text-[13px] font-medium hover:text-white hover:bg-slate-800/60 transition-all <?= $cActive ? 'text-white' : 'text-slate-400' ?>">
              <span class="w-1.5 h-1.5 rounded-full flex-shrink-0 <?= $cActive ? 'bg-brand-400' : 'bg-slate-600' ?>"></span>
              <span><?= e($child['label']) ?></span>
            </a>
          <?php endforeach; ?>
        <?php endif; ?>
      <?php endforeach; ?>
    </nav>

    <!-- Footer sidebar -->
    <div class="border-t border-slate-800 px-6 py-4 text-xs text-slate-500">
      <div class="flex items-center gap-2">
        <span class="w-2 h-2 rounded-full bg-emerald-400"></span>
        <span>Sistem online</span>
      </div>
    </div>
  </aside>

  <!-- Overlay mobile -->
  <div x-show="mobileOpen" @click="mobileOpen = false"
       class="fixed inset-0 bg-slate-900/50 z-30 md:hidden" x-cloak></div>

  <!-- ============== MAIN ============== -->
  <div class="flex-1 min-w-0 flex flex-col min-h-screen transition-all duration-200"
       :class="sidebarHidden ? 'md:ml-0' : 'md:ml-64'">

    <!-- Header -->
    <header class="h-16 bg-white border-b border-slate-200 sticky top-0 z-20 flex items-center px-6 gap-4">
      <!-- Mobile toggle (hamburger) -->
      <button @click="mobileOpen = !mobileOpen" class="md:hidden text-slate-600" title="Meniu">
        <svg class="w-6 h-6" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"/>
        </svg>
      </button>
      <!-- Desktop toggle: arată/ascunde sidebar -->
      <button @click="sidebarHidden = !sidebarHidden"
              class="hidden md:flex items-center justify-center w-9 h-9 text-slate-500 hover:text-brand-600 hover:bg-slate-100 rounded-lg transition"
              :title="sidebarHidden ? 'Arată meniul' : 'Ascunde meniul'">
        <svg x-show="sidebarHidden" 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="M4 6h16M4 12h16M4 18h16"/>
        </svg>
        <svg x-show="!sidebarHidden" x-cloak 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="M13 5l-7 7 7 7M19 5l-7 7 7 7"/>
        </svg>
      </button>

      <!-- Breadcrumb -->
      <nav class="flex items-center gap-2 text-sm">
        <a href="<?= url('index.php') ?>" class="text-slate-500 hover:text-brand-600 transition">Home</a>
        <?php foreach ($breadcrumb as $i => $crumb): ?>
          <svg class="w-4 h-4 text-slate-300" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
          <?php if (!empty($crumb['url'])): ?>
            <a href="<?= e($crumb['url']) ?>" class="text-slate-500 hover:text-brand-600 transition"><?= e($crumb['label']) ?></a>
          <?php else: ?>
            <span class="text-slate-900 font-medium"><?= e($crumb['label']) ?></span>
          <?php endif; ?>
        <?php endforeach; ?>
      </nav>

      <div class="flex-1"></div>

      <!-- Selector cont activ (context global) -->
      <?php if (!empty($activeAccounts)): ?>
      <div class="relative" x-data="accountSwitcher()" @keydown.escape="open = false">
        <button @click="open = !open"
                class="inline-flex items-center gap-2 px-3 py-2 text-sm font-medium text-slate-700 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-lg transition max-w-[220px]"
                :class="{ 'ring-2 ring-brand-500': open }" title="Schimbă contul activ">
          <svg class="w-4 h-4 text-slate-400 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a4 4 0 00-3-3.87M9 20H4v-2a4 4 0 013-3.87m6-5.13a4 4 0 11-8 0 4 4 0 018 0z"/>
          </svg>
          <span class="truncate"><?= e($activeAccountName) ?></span>
          <svg class="w-4 h-4 text-slate-400 flex-shrink-0 transition" :class="open ? 'rotate-180' : ''" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7"/></svg>
        </button>

        <div x-show="open" x-cloak @click.outside="open = false"
             x-transition:enter="transition ease-out duration-100"
             x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
             class="absolute right-0 mt-2 w-64 bg-white border border-slate-200 rounded-xl shadow-lg py-1.5 z-50 origin-top-right">
          <div class="px-3 py-1.5 text-[11px] uppercase tracking-wide text-slate-400 font-semibold">Cont de lucru</div>

          <button @click="select(0)"
                  class="w-full flex items-center justify-between gap-2 px-3 py-2 text-sm text-left hover:bg-slate-50 transition"
                  :class="<?= $activeAccountId === 0 ? 'true' : 'false' ?> ? 'text-brand-700 font-medium' : 'text-slate-700'">
            <span class="flex items-center gap-2">
              <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"/></svg>
              Toate conturile
            </span>
            <?php if ($activeAccountId === 0): ?>
              <svg class="w-4 h-4 text-brand-600" 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 endif; ?>
          </button>

          <div class="my-1 border-t border-slate-100"></div>

          <?php foreach ($activeAccounts as $acc): $sel = (int)$acc['id'] === $activeAccountId; ?>
            <button @click="select(<?= (int)$acc['id'] ?>)"
                    class="w-full flex items-center justify-between gap-2 px-3 py-2 text-sm text-left hover:bg-slate-50 transition <?= $sel ? 'text-brand-700 font-medium' : 'text-slate-700' ?>">
              <span class="min-w-0">
                <span class="block truncate"><?= e($acc['account_name']) ?></span>
                <span class="block text-[11px] text-slate-400 font-mono truncate"><?= e($acc['username']) ?></span>
              </span>
              <?php if ($sel): ?>
                <svg class="w-4 h-4 text-brand-600 flex-shrink-0" 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 endif; ?>
            </button>
          <?php endforeach; ?>

          <div class="my-1 border-t border-slate-100"></div>
          <a href="<?= url('settings.php') ?>" class="flex items-center gap-2 px-3 py-2 text-sm text-slate-500 hover:bg-slate-50 transition">
            <svg 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="M12 4v16m8-8H4"/></svg>
            Gestionează conturile
          </a>
        </div>
      </div>

      <script>
        function accountSwitcher() {
          return {
            open: false,
            csrf: '<?= e(csrf_token()) ?>',
            async select(id) {
              if (id === <?= $activeAccountId ?>) { this.open = false; return; }
              try {
                const fd = new FormData();
                fd.append('csrf_token', this.csrf);
                fd.append('account_id', id);
                const r = await fetch('<?= url('api/set-active-account.php') ?>', { method: 'POST', body: fd });
                const data = await r.json();
                if (!data.ok) throw new Error(data.error || 'Eroare');
                // Reîncarcă pe calea curentă fără query, ca filtrul global să se aplice.
                window.location = window.location.pathname;
              } catch (e) {
                alert('Nu am putut schimba contul: ' + e.message);
              }
            }
          };
        }
      </script>
      <?php endif; ?>

      <!-- Sync rapid — rulează sync-ul direct, fără a părăsi pagina curentă -->
      <div x-data="headerSync(
             <?= htmlspecialchars(json_encode($activeAccounts), ENT_QUOTES, 'UTF-8') ?>,
             <?= (int)$activeAccountId ?>
           )" class="hidden sm:block">
        <button @click="start()" :disabled="running"
           class="inline-flex items-center gap-2 px-3.5 py-2 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg shadow-soft transition-all disabled:opacity-60 disabled:cursor-not-allowed"
           :title="running ? 'Sincronizare în curs…' : 'Sincronizează produsele din eMAG fără a părăsi pagina'">
          <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-show="running" class="spinner"></span>
          <span x-text="running ? 'Sincronizez…' : 'Sync eMAG'"></span>
        </button>

        <!-- Panou progres flotant -->
        <div x-show="running || done" x-cloak
             x-transition:enter="transition ease-out duration-150"
             x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0"
             class="fixed bottom-5 right-5 z-[60] w-80 bg-white border border-slate-200 rounded-xl shadow-2xl overflow-hidden">
          <div class="px-4 py-3 border-b border-slate-100 flex items-center justify-between gap-2">
            <div class="font-semibold text-sm text-slate-900">
              <span x-show="running">Sincronizare eMAG…</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>
            <button x-show="done" @click="dismiss()" class="text-slate-400 hover:text-slate-600 p-1">
              <svg 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="M6 18L18 6M6 6l12 12"/></svg>
            </button>
          </div>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-500 mb-2" x-text="phase"></div>
            <div class="w-full h-1.5 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>
            <div class="mt-3 grid grid-cols-4 gap-2 text-center">
              <div class="bg-emerald-50 rounded-md py-1.5">
                <div class="text-[10px] uppercase tracking-wide text-emerald-700 font-medium">Noi</div>
                <div class="text-sm font-bold text-emerald-900" x-text="totals.new"></div>
              </div>
              <div class="bg-sky-50 rounded-md py-1.5">
                <div class="text-[10px] uppercase tracking-wide text-sky-700 font-medium">Update</div>
                <div class="text-sm font-bold text-sky-900" x-text="totals.updated"></div>
              </div>
              <div class="bg-rose-50 rounded-md py-1.5">
                <div class="text-[10px] uppercase tracking-wide text-rose-700 font-medium">Erori</div>
                <div class="text-sm font-bold text-rose-900" x-text="totals.errors"></div>
              </div>
              <div class="bg-slate-50 rounded-md py-1.5">
                <div class="text-[10px] uppercase tracking-wide text-slate-600 font-medium">Total</div>
                <div class="text-sm font-bold text-slate-900" x-text="totals.processed"></div>
              </div>
            </div>
            <template x-if="done">
              <div class="mt-3 text-xs text-slate-500">
                <span x-show="!error">Reîncarc pagina cu datele noi…</span>
                <button x-show="error" @click="dismiss()" class="text-brand-600 hover:text-brand-700 font-medium">Închide</button>
              </div>
            </template>
          </div>
        </div>
      </div>

      <script>
        function headerSync(accounts, activeId) {
          return {
            accounts: accounts || [],
            activeId: Number(activeId) || 0,
            running: false,
            done: false,
            error: false,
            phase: '',
            currentPage: 0,
            totalKnown: null,
            totals: { new: 0, updated: 0, errors: 0, processed: 0 },
            csrf: '<?= e(csrf_token()) ?>',

            // Conturile vizate: contul activ, sau toate conturile active dacă e „Toate".
            targets() {
              if (this.activeId > 0) {
                const a = this.accounts.find(x => x.id == this.activeId);
                return a ? [a] : [];
              }
              return this.accounts.slice();
            },

            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));
              }
              return Math.min(95, this.currentPage * 8);
            },

            dismiss() {
              this.done = false; this.error = false;
            },

            async start() {
              if (this.running) return;
              const targets = this.targets();
              if (targets.length === 0) {
                alert('Niciun cont eMAG activ. Adaugă/activează un cont din Setări.');
                window.location = '<?= url('settings.php') ?>';
                return;
              }

              this.running = true; this.done = false; this.error = false;
              this.currentPage = 0; this.totalKnown = null;
              this.totals = { new: 0, updated: 0, errors: 0, processed: 0 };

              try {
                for (let ti = 0; ti < targets.length; ti++) {
                  const acc = targets[ti];
                  this.phase = (targets.length > 1 ? `(${ti + 1}/${targets.length}) ` : '') + acc.account_name;

                  let page = 1, safety = 300;
                  let accStats = { new: 0, updated: 0, errors: 0 };
                  this.totalKnown = null;

                  while (safety-- > 0) {
                    this.currentPage = page;
                    const fd = new FormData();
                    fd.append('csrf_token', this.csrf);
                    fd.append('action', 'page');
                    fd.append('account_id', acc.id);
                    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.processed += data.processed;
                    accStats.new     += data.stats.new;
                    accStats.updated += data.stats.updated;
                    accStats.errors  += data.stats.errors;
                    if (data.total_known != null) this.totalKnown = data.total_known;

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

                  // Finalize pentru contul curent
                  const status = accStats.errors === 0
                    ? 'success'
                    : ((accStats.new + accStats.updated) > 0 ? 'partial' : 'failed');
                  const fd2 = new FormData();
                  fd2.append('csrf_token', this.csrf);
                  fd2.append('action', 'finalize');
                  fd2.append('account_id', acc.id);
                  fd2.append('new', accStats.new);
                  fd2.append('updated', accStats.updated);
                  fd2.append('errors', accStats.errors);
                  fd2.append('status', status);
                  await fetch('<?= url('api/emag-sync.php') ?>', { method: 'POST', body: fd2 });
                }

                this.phase = 'Gata';
                this.done = true;
                // Reîncarc pagina curentă (cu filtrele ei) ca să afișeze datele noi.
                setTimeout(() => window.location.reload(), 900);
              } catch (e) {
                this.phase = e.message;
                this.error = true;
                this.done = true;
              } finally {
                this.running = false;
              }
            }
          };
        }
      </script>
    </header>

    <!-- Flash messages -->
    <?php $flash = flash_get(); if ($flash): ?>
      <div class="px-6 pt-4 space-y-2">
        <?php foreach ($flash as $f):
          $isErr = ($f['type'] === 'error');
          $cls = $isErr ? 'bg-rose-50 text-rose-800 border-rose-200' : 'bg-emerald-50 text-emerald-800 border-emerald-200';
        ?>
          <div class="toast-enter border <?= $cls ?> px-4 py-3 rounded-lg text-sm flex items-center gap-2">
            <svg class="w-4 h-4 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
              <?php if ($isErr): ?>
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
              <?php else: ?>
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
              <?php endif; ?>
            </svg>
            <span><?= e($f['message']) ?></span>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <!-- Main content -->
    <main class="flex-1 px-6 py-6">
