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

$pageTitle  = 'Stocuri';
$breadcrumb = [['label' => 'Stocuri']];

$dbError = null;

// Contul de lucru e cel global (selectat din header). 0 = toate conturile.
$activeId = active_account_id();

// ---- Filtre locale ----
$search       = trim((string)($_GET['q'] ?? ''));
$filterStock  = $_GET['stock'] ?? ''; // '', 'set', 'unset', 'changed'
$filterUnits  = $_GET['units'] ?? ''; // '', 'null', 'any', sau număr exact
$filterBrand  = isset($_GET['brand']) ? (int)$_GET['brand'] : 0; // brand telefon (phone_brands.id)
$filterStatus = $_GET['status'] ?? ''; // '', 'draft', 'active', 'synced'
$filterOffer  = $_GET['offer']  ?? ''; // '', '1' (activ), '0' (inactiv), '2' (EOL), 'null' (necunoscut)
$pageNum      = max(1, (int)($_GET['page'] ?? 1));
$allowedPer   = [50, 100, 200];
$perPage      = (int)($_GET['per_page'] ?? 50);
if (!in_array($perPage, $allowedPer, true)) $perPage = 50;

$products        = [];
$total           = 0;
$totalPages      = 1;
$eligibleCount   = 0;   // produse care POT fi împinse la eMAG pentru contul activ
$selectedAccount = null;
$isFbe           = false;
$unitsValues     = [];
$brandsList      = [];

// JOIN-uri pentru brand-ul telefonului (expune pb.id / pb.name), comune la COUNT și SELECT.
$phoneJoin = "
    LEFT JOIN phone_series ps ON ps.id = p.phone_series_id
    LEFT JOIN phone_models pm ON pm.id = ps.model_id
    LEFT JOIN phone_brands pb ON pb.id = pm.brand_id
";

try {
    if ($activeId > 0) {
        $rows = db_select("SELECT id, account_name, username, is_fbe FROM emag_accounts WHERE id = ? AND is_active = 1", [$activeId]);
        $selectedAccount = $rows[0] ?? null;
        $isFbe = $selectedAccount ? ((int)$selectedAccount['is_fbe'] === 1) : false;
    }

    // Valori distincte de units_per_box pentru dropdown (în scopul contului activ)
    if ($activeId > 0) {
        $unitsValues = array_map('intval', array_column(
            db_select("SELECT DISTINCT units_per_box FROM products WHERE units_per_box IS NOT NULL AND emag_account_id = ? ORDER BY units_per_box ASC", [$activeId]),
            'units_per_box'
        ));
    } else {
        $unitsValues = array_map('intval', array_column(
            db_select("SELECT DISTINCT units_per_box FROM products WHERE units_per_box IS NOT NULL ORDER BY units_per_box ASC"),
            'units_per_box'
        ));
    }

    // Branduri telefon care au cel puțin un produs (în scopul contului activ).
    $brandScope = $activeId > 0 ? "AND p2.emag_account_id = " . (int)$activeId : "";
    $brandsList = db_select(
        "SELECT b.id, b.name
         FROM phone_brands b
         WHERE EXISTS (
             SELECT 1 FROM products p2
             JOIN phone_series ps2 ON ps2.id = p2.phone_series_id
             JOIN phone_models pm2 ON pm2.id = ps2.model_id
             WHERE pm2.brand_id = b.id $brandScope
         )
         ORDER BY b.name COLLATE NOCASE"
    );

    // WHERE comun: exclude produsele excluse (EAN sau categorie)
    $where  = [
        "(c.is_excluded IS NULL OR c.is_excluded = 0)",
        "(p.ean IS NULL OR p.ean NOT IN (SELECT ean FROM excluded_eans))",
    ];
    $params = [];

    if ($activeId > 0) {
        $where[] = 'p.emag_account_id = ?';
        $params[] = $activeId;
    }
    if ($search !== '') {
        $where[] = '(p.ean LIKE ? OR p.product_name LIKE ? OR p.pnk LIKE ? OR p.emag_id LIKE ?)';
        $q = '%' . $search . '%';
        array_push($params, $q, $q, $q, $q);
    }
    if ($filterStock === 'set') {
        $where[] = 'p.stock IS NOT NULL';
    } elseif ($filterStock === 'unset') {
        $where[] = 'p.stock IS NULL';
    } elseif ($filterStock === 'changed') {
        $where[] = '(p.stock IS NOT NULL AND (p.current_stock IS NULL OR p.stock != p.current_stock))';
    }
    if ($filterUnits === 'null') {
        $where[] = 'p.units_per_box IS NULL';
    } elseif ($filterUnits === 'any') {
        $where[] = 'p.units_per_box IS NOT NULL';
    } elseif ($filterUnits !== '' && ctype_digit((string)$filterUnits)) {
        $where[] = 'p.units_per_box = ?';
        $params[] = (int)$filterUnits;
    }
    if ($filterBrand > 0) {
        $where[] = 'pb.id = ?';
        $params[] = $filterBrand;
    }
    if (in_array($filterStatus, ['draft', 'active', 'synced'], true)) {
        $where[] = 'p.status = ?';
        $params[] = $filterStatus;
    }
    // Starea ofertei pe eMAG: 1 = activ, 0 = inactiv, 2 = end of life, NULL = fără sync
    if ($filterOffer === 'null') {
        $where[] = 'p.emag_offer_status IS NULL';
    } elseif (in_array($filterOffer, ['0', '1', '2'], true)) {
        $where[] = 'p.emag_offer_status = ?';
        $params[] = (int)$filterOffer;
    }
    $whereSql = implode(' AND ', $where);

    $total = (int)db_scalar(
        "SELECT COUNT(*) FROM products p
         LEFT JOIN categories c ON c.id = p.category_id
         $phoneJoin
         WHERE $whereSql",
        $params
    );
    $totalPages = max(1, (int)ceil($total / $perPage));
    if ($pageNum > $totalPages) $pageNum = $totalPages;
    $offset = ($pageNum - 1) * $perPage;

    $products = db_select(
        "SELECT p.id, p.product_name, p.ean, p.pnk, p.emag_id, p.emag_account_id,
                p.stock, p.current_stock, p.stock_synced_at, p.status, p.units_per_box,
                p.emag_offer_status,
                a.account_name, pb.name AS phone_brand_name
         FROM products p
         LEFT JOIN categories c ON c.id = p.category_id
         LEFT JOIN emag_accounts a ON a.id = p.emag_account_id
         $phoneJoin
         WHERE $whereSql
         ORDER BY p.stock_synced_at IS NOT NULL, p.product_name COLLATE NOCASE
         LIMIT ? OFFSET ?",
        array_merge($params, [$perPage, $offset])
    );

    // Câte produse pot fi efectiv împinse la eMAG pentru contul activ (non-FBE)
    if ($activeId > 0 && !$isFbe) {
        $eligibleCount = (int)db_scalar(
            "SELECT COUNT(*) FROM products p
             LEFT JOIN categories c ON c.id = p.category_id
             WHERE p.emag_account_id = ?
               AND p.emag_id IS NOT NULL AND p.emag_id != ''
               AND p.stock IS NOT NULL
               AND (c.is_excluded IS NULL OR c.is_excluded = 0)
               AND (p.ean IS NULL OR p.ean NOT IN (SELECT ean FROM excluded_eans))",
            [$activeId]
        );
    }
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

function stock_url(array $overrides = []): string {
    $current = [
        'q'        => $_GET['q']        ?? null,
        'stock'    => $_GET['stock']    ?? null,
        'units'    => $_GET['units']    ?? null,
        'brand'    => $_GET['brand']    ?? null,
        'status'   => $_GET['status']   ?? null,
        'offer'    => $_GET['offer']    ?? null,
        'page'     => $_GET['page']     ?? null,
        'per_page' => $_GET['per_page'] ?? null,
    ];
    $merged = array_filter(array_merge($current, $overrides), fn($v) => $v !== null && $v !== '');
    return '?' . http_build_query($merged);
}

$startRow = $total > 0 ? (($pageNum - 1) * $perPage) + 1 : 0;
$endRow   = min($pageNum * $perPage, $total);

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="stockPage({
       rows: <?= htmlspecialchars(json_encode($products), ENT_QUOTES, 'UTF-8') ?>,
       csrf: '<?= e(csrf_token()) ?>',
       accountId: <?= $activeId ?>,
       eligible: <?= $eligibleCount ?>,
       startIndex: <?= $startRow ?: 1 ?>,
       isFbe: <?= $isFbe ? 'true' : 'false' ?>
     })">

  <!-- Header + cont activ -->
  <div class="flex items-center gap-3 flex-wrap mb-4">
    <h1 class="text-2xl font-bold text-slate-900">Stocuri</h1>
    <?php if ($selectedAccount): ?>
      <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-brand-50 text-brand-700 text-sm font-medium">
        <span class="w-1.5 h-1.5 rounded-full bg-brand-500"></span><?= e($selectedAccount['account_name']) ?>
        <?php if ($isFbe): ?><span class="ml-1 text-[10px] font-semibold uppercase tracking-wider text-violet-700">FBE</span><?php endif; ?>
      </span>
    <?php else: ?>
      <span class="inline-flex items-center px-2.5 py-1 rounded-lg bg-slate-100 text-slate-600 text-sm font-medium">Toate conturile</span>
    <?php endif; ?>
    <span class="text-sm text-slate-400"><?= number_format($total, 0, ',', '.') ?> produse</span>
  </div>

  <?php if ($isFbe): ?>
    <!-- Avertisment FBE -->
    <div class="mb-4 bg-violet-50 border border-violet-200 rounded-xl p-4 text-sm text-violet-900 flex items-start gap-3">
      <svg class="w-5 h-5 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
      <div>
        <div class="font-semibold">Cont Fulfillment by eMAG (FBE)</div>
        <div class="mt-0.5">Marfa stă în depozitul eMAG, iar stocul e gestionat automat de eMAG la recepție. Stocul <strong>nu poate fi trimis</strong> de seller pentru acest cont — mai jos vezi doar stocul curent (read-only).</div>
      </div>
    </div>
  <?php endif; ?>

  <!-- Filtre -->
  <?php $hasFilters = ($search !== '' || $filterStock !== '' || $filterUnits !== '' || $filterBrand > 0 || $filterStatus !== '' || $filterOffer !== ''); ?>
  <form method="get" data-ajax-filters class="flex flex-wrap items-center gap-2 mb-4">
    <?php $sel = 'px-2.5 py-1.5 text-sm text-slate-600 border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500'; ?>
    <input type="text" name="q" value="<?= e($search) ?>" placeholder="Caută nume, EAN, PNK…"
      class="flex-1 min-w-[220px] px-3 py-1.5 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">

    <select name="offer" onchange="this.form.requestSubmit()" class="<?= $sel ?>">
      <option value="">Stare eMAG: toate</option>
      <option value="1"    <?= $filterOffer === '1'    ? 'selected' : '' ?>>Active</option>
      <option value="0"    <?= $filterOffer === '0'    ? 'selected' : '' ?>>Inactive</option>
      <option value="2"    <?= $filterOffer === '2'    ? 'selected' : '' ?>>End of life</option>
      <option value="null" <?= $filterOffer === 'null' ? 'selected' : '' ?>>Fără sync</option>
    </select>

    <select name="stock" onchange="this.form.requestSubmit()" class="<?= $sel ?>">
      <option value="">Stoc nou: toate</option>
      <option value="set"     <?= $filterStock === 'set'     ? 'selected' : '' ?>>Setat</option>
      <option value="unset"   <?= $filterStock === 'unset'   ? 'selected' : '' ?>>Nesetat</option>
      <option value="changed" <?= $filterStock === 'changed' ? 'selected' : '' ?>>Modificat</option>
    </select>

    <select name="brand" onchange="this.form.requestSubmit()" class="<?= $sel ?>">
      <option value="0">Brand: toate</option>
      <?php foreach ($brandsList as $b): ?>
        <option value="<?= (int)$b['id'] ?>" <?= $filterBrand === (int)$b['id'] ? 'selected' : '' ?>><?= e($b['name']) ?></option>
      <?php endforeach; ?>
    </select>

    <select name="units" onchange="this.form.requestSubmit()" class="<?= $sel ?>">
      <option value="">Nr. buc: toate</option>
      <option value="null" <?= $filterUnits === 'null' ? 'selected' : '' ?>>Fără valoare</option>
      <option value="any"  <?= $filterUnits === 'any'  ? 'selected' : '' ?>>Cu valoare</option>
      <?php foreach ($unitsValues as $val): ?>
        <option value="<?= (int)$val ?>" <?= (string)$filterUnits === (string)$val ? 'selected' : '' ?>><?= (int)$val ?> buc</option>
      <?php endforeach; ?>
    </select>

    <select name="status" onchange="this.form.requestSubmit()" class="<?= $sel ?>">
      <option value="">Status: toate</option>
      <option value="draft"  <?= $filterStatus === 'draft'  ? 'selected' : '' ?>>Draft</option>
      <option value="active" <?= $filterStatus === 'active' ? 'selected' : '' ?>>Activ</option>
      <option value="synced" <?= $filterStatus === 'synced' ? 'selected' : '' ?>>Sincronizat</option>
    </select>

    <select name="per_page" onchange="this.form.requestSubmit()" class="<?= $sel ?>">
      <?php foreach ($allowedPer as $pp): ?>
        <option value="<?= $pp ?>" <?= $perPage === $pp ? 'selected' : '' ?>><?= $pp ?>/pag</option>
      <?php endforeach; ?>
    </select>

    <?php if ($hasFilters): ?>
      <a href="<?= e(url('stocuri.php')) ?>" title="Resetează filtrele"
         class="inline-flex items-center justify-center w-8 h-8 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg 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="M6 18L18 6M6 6l12 12"/></svg>
      </a>
    <?php endif; ?>
  </form>

  <?php if (!$isFbe): ?>
  <!-- Panou Sync la eMAG -->
  <div class="bg-white border border-slate-100 rounded-xl shadow-soft px-4 py-3 mb-4">
    <div class="flex items-center justify-between gap-4 flex-wrap">
      <div class="text-sm text-slate-500">
        <?php if ($selectedAccount): ?>
          <strong class="text-slate-800" x-text="eligible"></strong> produse gata de trimis la eMAG
        <?php else: ?>
          Selectează un cont din header pentru a trimite stocurile la eMAG
        <?php endif; ?>
      </div>
      <button @click="startSync()"
        :disabled="running || !accountId || eligible === 0"
        class="inline-flex items-center gap-2 px-3.5 py-1.5 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg 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="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 ? 'Trimit…' : 'Sync stocuri'"></span>
      </button>
    </div>

    <!-- Progress -->
    <template x-if="running || done">
      <div class="mt-4">
        <div class="flex items-center justify-between text-sm mb-2">
          <div class="font-medium text-slate-700">
            <span x-show="running">Trimitere în progres…</span>
            <span x-show="done && !error" class="text-emerald-700">✓ Trimitere finalizată</span>
            <span x-show="error" class="text-rose-700">✗ Trimitere eșuată</span>
          </div>
          <div class="text-xs text-slate-500"><span x-text="totals.processed"></span> / <span x-text="totals.total"></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>
        <div class="mt-3 flex items-center gap-4 text-xs">
          <span class="text-emerald-700"><strong x-text="totals.sent"></strong> trimise</span>
          <span class="text-rose-700"><strong x-text="totals.failed"></strong> erori</span>
        </div>
        <div class="mt-3">
          <div class="bg-slate-900 text-slate-300 font-mono text-[12px] rounded-lg p-3 max-h-40 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">
          <div class="mt-3 text-sm">
            <a href="" @click.prevent="window.location.reload()" class="text-brand-600 hover:text-brand-700 font-medium">↻ Reîncarcă lista</a>
          </div>
        </template>
      </div>
    </template>
  </div>

  <!-- Bara setare în masă (apare când ai selecții) -->
  <div x-show="selectedIds.length > 0" x-cloak
       class="bg-brand-50 border border-brand-200 rounded-xl px-4 py-2.5 mb-4 flex items-center gap-3 flex-wrap">
    <span class="text-sm font-medium text-brand-900 whitespace-nowrap">
      <span x-text="selectedIds.length"></span> selectate
    </span>
    <input type="number" min="0" max="999999" step="1" x-model="bulkStock" placeholder="Stoc nou"
      class="w-28 px-2 py-1.5 text-sm text-right tabular-nums border border-slate-200 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-500">
    <button @click="applyBulk()" :disabled="bulkSaving"
      class="inline-flex items-center gap-2 px-3.5 py-1.5 text-sm font-medium text-white bg-brand-600 hover:bg-brand-700 rounded-lg transition disabled:opacity-50 whitespace-nowrap">
      <span x-show="bulkSaving" class="spinner"></span>
      <span x-text="bulkSaving ? 'Aplic…' : 'Aplică'"></span>
    </button>
    <button @click="clearSelection()" title="Deselectează"
      class="inline-flex items-center justify-center w-8 h-8 text-slate-400 hover:text-slate-700 hover:bg-white/70 rounded-lg 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="M6 18L18 6M6 6l12 12"/></svg>
    </button>
  </div>
  <?php endif; ?>

  <!-- 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 table-fixed">
        <thead>
          <tr class="border-b border-slate-100 bg-slate-50/60 text-left text-xs font-medium text-slate-500 uppercase tracking-wide">
            <?php if (!$isFbe): ?>
            <th class="px-3 py-3 w-10">
              <input type="checkbox" @change="toggleAll($event.target.checked)" :checked="allSelected()"
                class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer">
            </th>
            <?php endif; ?>
            <th class="px-2 py-2.5 w-10 text-right">#</th>
            <th class="px-3 py-2.5">Produs</th>
            <th class="px-3 py-2.5 w-28 text-right whitespace-nowrap">Stoc eMAG</th>
            <?php if (!$isFbe): ?>
            <th class="px-3 py-2.5 w-28 text-right whitespace-nowrap">Stoc nou</th>
            <th class="px-3 py-2.5 w-28 whitespace-nowrap">Stare</th>
            <th class="px-3 py-2.5 w-20 text-center whitespace-nowrap">Acțiune</th>
            <?php endif; ?>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-50">
          <template x-for="(p, idx) in rows" :key="p.id">
            <tr class="hover:bg-slate-50/50" :class="isSelected(p.id) ? 'bg-brand-50/40' : ''">
              <?php if (!$isFbe): ?>
              <td class="px-3 py-2.5">
                <input type="checkbox" :value="p.id" :checked="isSelected(p.id)" @change="toggleOne(p.id, $event.target.checked)"
                  class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 cursor-pointer">
              </td>
              <?php endif; ?>
              <td class="px-2 py-2 text-right text-xs text-slate-300 tabular-nums" x-text="startIndex + idx"></td>
              <td class="px-3 py-2 overflow-hidden">
                <div class="flex items-center gap-2 min-w-0">
                  <span class="w-1.5 h-1.5 rounded-full flex-shrink-0" :class="offerDot(p.emag_offer_status)"
                        :title="'Stare eMAG: ' + offerLabel(p.emag_offer_status)"></span>
                  <span class="font-medium text-slate-800 truncate" :title="p.product_name" x-text="p.product_name"></span>
                </div>
                <div class="text-[11px] text-slate-400 mt-0.5 truncate">
                  <span x-show="p.ean" x-text="p.ean"></span>
                  <span x-show="p.phone_brand_name"> · <span x-text="p.phone_brand_name"></span></span>
                  <span x-show="p.units_per_box != null && p.units_per_box !== ''"> · <span x-text="p.units_per_box"></span> buc</span>
                  <span x-show="!p.emag_id" class="text-amber-600"> · fără emag_id</span>
                </div>
              </td>
              <td class="px-3 py-2 text-right tabular-nums">
                <template x-if="p.current_stock !== null && p.current_stock !== ''">
                  <span class="inline-flex items-center justify-center min-w-[2.25rem] px-2 py-0.5 rounded-md font-semibold"
                        :class="stockClass(p.current_stock)" x-text="p.current_stock"></span>
                </template>
                <template x-if="p.current_stock === null || p.current_stock === ''">
                  <span class="text-slate-300">—</span>
                </template>
              </td>
              <?php if (!$isFbe): ?>
              <td class="px-3 py-2 text-right">
                <input type="number" min="0" max="999999" step="1"
                  x-model="p.stock"
                  @focus="snapshot(p)"
                  @change="saveRow(p)"
                  @keydown.enter.prevent="$event.target.blur()"
                  placeholder="—"
                  class="w-20 px-2 py-1 text-sm text-right tabular-nums font-semibold border rounded-md focus:outline-none focus:ring-2 focus:ring-brand-500"
                  :class="(stockChanged(p) ? 'border-amber-400 ' : 'border-slate-200 ') + stockTextClass(p.stock)">
              </td>
              <td class="px-3 py-2">
                <template x-if="hasStock(p) && p.stock_synced_at && !stockChanged(p)">
                  <span class="inline-flex items-center gap-1.5 text-xs text-emerald-700 whitespace-nowrap">
                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span> trimis
                  </span>
                </template>
                <template x-if="hasStock(p) && (!p.stock_synced_at || stockChanged(p))">
                  <span class="inline-flex items-center gap-1.5 text-xs text-sky-700 whitespace-nowrap">
                    <span class="w-1.5 h-1.5 rounded-full bg-sky-500"></span> de trimis
                  </span>
                </template>
                <template x-if="!hasStock(p)">
                  <span class="inline-flex items-center gap-1.5 text-xs text-slate-400 whitespace-nowrap">
                    <span class="w-1.5 h-1.5 rounded-full bg-slate-300"></span> fără stoc
                  </span>
                </template>
              </td>
              <td class="px-3 py-2 text-center">
                <template x-if="hasStock(p) && p.emag_id">
                  <button @click="sendOne(p)" :disabled="isSending(p.id)"
                    class="inline-flex items-center justify-center w-8 h-8 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
                    :class="(p.stock_synced_at && !stockChanged(p))
                              ? 'text-slate-400 hover:text-slate-700 hover:bg-slate-100'
                              : 'text-brand-600 hover:text-brand-700 hover:bg-brand-50'"
                    :title="(p.stock_synced_at && !stockChanged(p)) ? 'Stoc deja trimis — retrimite' : 'Trimite stocul la eMAG'">
                    <span x-show="isSending(p.id)" class="spinner"></span>
                    <svg x-show="!isSending(p.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="M5 12h14M12 5l7 7-7 7"/></svg>
                  </button>
                </template>
                <template x-if="!(hasStock(p) && p.emag_id)">
                  <span class="text-slate-200">—</span>
                </template>
              </td>
              <?php endif; ?>
            </tr>
          </template>
          <template x-if="rows.length === 0">
            <tr><td colspan="<?= $isFbe ? 3 : 7 ?>" class="px-4 py-12 text-center text-sm text-slate-400">Niciun produs.</td></tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Paginare -->
  <?php if ($totalPages > 1): ?>
    <div class="mt-4 flex items-center justify-between text-sm">
      <div class="text-slate-500">Afișez <strong><?= $startRow ?>–<?= $endRow ?></strong> din <strong><?= number_format($total, 0, ',', '.') ?></strong></div>
      <div class="flex items-center gap-1">
        <?php if ($pageNum > 1): ?>
          <a href="<?= e(stock_url(['page' => $pageNum - 1])) ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50">‹ Anterior</a>
        <?php endif; ?>
        <span class="px-3 py-1.5 text-slate-500">Pagina <?= $pageNum ?> / <?= $totalPages ?></span>
        <?php if ($pageNum < $totalPages): ?>
          <a href="<?= e(stock_url(['page' => $pageNum + 1])) ?>" class="px-3 py-1.5 border border-slate-200 rounded-lg hover:bg-slate-50">Următor ›</a>
        <?php endif; ?>
      </div>
    </div>
  <?php endif; ?>

</div>

<script>
function stockPage(cfg) {
  return {
    rows: cfg.rows,
    csrf: cfg.csrf,
    accountId: cfg.accountId,
    eligible: cfg.eligible,
    startIndex: cfg.startIndex,
    isFbe: cfg.isFbe,
    _snap: {},

    // --- Selecție multiplă ---
    selectedIds: [],
    bulkStock: '',
    bulkSaving: false,

    isSelected(id) { return this.selectedIds.includes(id); },
    toggleOne(id, on) {
      if (on) { if (!this.isSelected(id)) this.selectedIds.push(id); }
      else    { this.selectedIds = this.selectedIds.filter(x => x !== id); }
    },
    allSelected() { return this.rows.length > 0 && this.selectedIds.length === this.rows.length; },
    toggleAll(on) { this.selectedIds = on ? this.rows.map(p => p.id) : []; },
    clearSelection() { this.selectedIds = []; this.bulkStock = ''; },

    // --- Culori pe praguri de stoc: 0 = roșu, 1–9 = galben, 10+ = verde ---
    stockLevel(v) {
      if (v === null || v === undefined || v === '') return null;
      const n = parseInt(v, 10);
      if (isNaN(n)) return null;
      if (n <= 0)  return 'zero';
      if (n < 10)  return 'low';
      return 'ok';
    },
    stockClass(v) {
      const lvl = this.stockLevel(v);
      if (lvl === 'zero') return 'bg-rose-50 text-rose-700';
      if (lvl === 'low')  return 'bg-amber-50 text-amber-700';
      if (lvl === 'ok')   return 'bg-emerald-50 text-emerald-700';
      return 'text-slate-300';
    },
    stockTextClass(v) {
      const lvl = this.stockLevel(v);
      if (lvl === 'zero') return 'bg-rose-50 text-rose-700';
      if (lvl === 'low')  return 'bg-amber-50 text-amber-700';
      if (lvl === 'ok')   return 'bg-emerald-50 text-emerald-700';
      return 'text-slate-500';
    },

    // --- Stare ofertă eMAG (1 activ, 0 inactiv, 2 EOL, null = fără sync) ---
    offerLabel(v) {
      if (v === null || v === undefined || v === '') return '—';
      if (v == 1) return 'Activ';
      if (v == 0) return 'Inactiv';
      if (v == 2) return 'EOL';
      return String(v);
    },
    offerDot(v) {
      if (v == 1) return 'bg-emerald-500';
      if (v == 0) return 'bg-rose-500';
      if (v == 2) return 'bg-amber-500';
      return 'bg-slate-200';
    },

    // --- Helpers stoc ---
    hasStock(p) {
      return p.stock !== null && p.stock !== '' && p.stock !== undefined;
    },
    stockChanged(p) {
      if (!this.hasStock(p)) return false;
      const cur = (p.current_stock === null || p.current_stock === '' || p.current_stock === undefined)
        ? null : parseInt(p.current_stock);
      return cur === null || parseInt(p.stock) !== cur;
    },

    // --- Trimitere individuală la eMAG ---
    sendingIds: [],
    isSending(id) { return this.sendingIds.includes(id); },
    async sendOne(p) {
      if (this.isSending(p.id)) return;
      this.sendingIds.push(p.id);
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', p.id);
        const r = await fetch('<?= url('api/stock-send-one.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error || 'Eroare');
        if (data.product) Object.assign(p, data.product);
      } catch (e) {
        alert('Eroare trimitere „' + (p.product_name || '').slice(0, 60) + '": ' + e.message);
      } finally {
        this.sendingIds = this.sendingIds.filter(x => x !== p.id);
      }
    },

    async applyBulk() {
      if (this.selectedIds.length === 0 || this.bulkSaving) return;
      if (String(this.bulkStock).trim() === '') { alert('Completează stocul nou.'); return; }
      const val = parseInt(String(this.bulkStock).trim(), 10);
      if (isNaN(val) || val < 0) { alert('Stoc invalid.'); return; }
      this.bulkSaving = true;
      try {
        for (const id of this.selectedIds) {
          const fd = new FormData();
          fd.append('csrf_token', this.csrf);
          fd.append('id', id);
          fd.append('stock', val);
          const r = await fetch('<?= url('api/save-stock.php') ?>', { method: 'POST', body: fd });
          const data = await r.json();
          if (data.ok && data.product) {
            const row = this.rows.find(x => x.id == id);
            if (row) Object.assign(row, data.product);
          }
        }
        this.bulkStock = '';
      } catch (e) {
        alert('Eroare salvare în masă: ' + e.message);
      } finally {
        this.bulkSaving = false;
      }
    },

    running: false,
    done: false,
    error: false,
    totals: { sent: 0, failed: 0, processed: 0, total: 0 },
    logLines: [],

    snapshot(p) { this._snap[p.id] = { stock: p.stock }; },

    async saveRow(p) {
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('id', p.id);
        fd.append('stock', p.stock ?? '');
        const r = await fetch('<?= url('api/save-stock.php') ?>', { method: 'POST', body: fd });
        const data = await r.json();
        if (!data.ok) throw new Error(data.error || 'Eroare');
        Object.assign(p, data.product); // include stock_synced_at = null
      } catch (e) {
        const s = this._snap[p.id];
        if (s) Object.assign(p, s);
        alert('Eroare salvare: ' + e.message);
      }
    },

    progressPercent() {
      if (this.done) return 100;
      if (this.totals.total > 0) return Math.min(99, Math.round((this.totals.processed / this.totals.total) * 100));
      return 5;
    },

    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 startSync() {
      if (!this.accountId || this.eligible === 0 || this.running) return;
      this.running = true; this.done = false; this.error = false;
      this.totals = { sent: 0, failed: 0, processed: 0, total: this.eligible };
      this.logLines = [];
      this.log(`Start trimitere stocuri (${this.eligible} produse)`, 'info');

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

          this.totals.total      = data.total;
          this.totals.sent      += data.stats.sent;
          this.totals.failed    += data.stats.failed;
          this.totals.processed += data.processed;
          this.log(`  ✓ lot: ${data.processed} procesate · ${data.stats.sent} trimise · ${data.stats.failed} erori`, 'success');
          (data.errors_log || []).forEach(m => this.log(`  ⚠ ${m}`, 'error'));

          if (!data.has_more || data.processed === 0) break;
          offset = data.next_offset;
        }
        this.log(`✓ FINALIZAT: ${this.totals.sent} trimise, ${this.totals.failed} 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'; ?>
