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

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

// --- Statistici (cu fallback dacă DB nu există încă) ---
$stats = [
    'total_products'   => 0,
    'synced_products'  => 0,
    'draft_products'   => 0,
    'active_accounts'  => 0,
    'excluded_eans'    => 0,
    'last_sync'        => null,
];
$recentProducts = [];
$recentLogs     = [];
$dbError        = null;

try {
    $stats['total_products']  = (int) db_scalar("SELECT COUNT(*) FROM products");
    $stats['synced_products'] = (int) db_scalar("SELECT COUNT(*) FROM products WHERE status='synced'");
    $stats['draft_products']  = (int) db_scalar("SELECT COUNT(*) FROM products WHERE status='draft'");
    $stats['active_accounts'] = (int) db_scalar("SELECT COUNT(*) FROM emag_accounts WHERE is_active=1");
    $stats['excluded_eans']   = (int) db_scalar("SELECT COUNT(*) FROM excluded_eans");
    $stats['last_sync']       = db_scalar("SELECT MAX(last_sync_at) FROM emag_accounts");

    $recentProducts = db_select(
        "SELECT p.id, p.ean, p.product_name, p.pnk, p.status, p.updated_at, a.account_name
         FROM products p
         LEFT JOIN emag_accounts a ON a.id = p.emag_account_id
         ORDER BY p.updated_at DESC
         LIMIT 6"
    );

    $recentLogs = db_select(
        "SELECT s.*, a.account_name
         FROM sync_logs s
         LEFT JOIN emag_accounts a ON a.id = s.emag_account_id
         ORDER BY s.created_at DESC
         LIMIT 5"
    );
} 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">
    <div class="font-semibold mb-1">⚠️ Baza de date nu este disponibilă</div>
    <div>Verifică permisiunile de scriere pe folderul <code class="px-1.5 py-0.5 bg-amber-100 rounded">data/</code>. Migrațiile rulează automat la prima conexiune.</div>
    <details class="mt-2"><summary class="cursor-pointer">Detalii</summary><pre class="mt-2 text-xs"><?= e($dbError) ?></pre></details>
  </div>
<?php endif; ?>

<!-- Welcome -->
<div class="mb-6">
  <h1 class="text-2xl font-bold text-slate-900">Bine ai venit 👋</h1>
  <p class="text-sm text-slate-500 mt-1">Privire de ansamblu asupra produselor și conturilor eMAG.</p>
</div>

<!-- Stat cards -->
<div class="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-8">
  <?php
  $cards = [
    ['label' => 'Total produse',      'value' => $stats['total_products'],  'color' => 'from-indigo-500 to-indigo-600',   'icon' => 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4'],
    ['label' => 'Sincronizate',       'value' => $stats['synced_products'], 'color' => 'from-emerald-500 to-emerald-600', 'icon' => 'M5 13l4 4L19 7'],
    ['label' => 'Draft',              'value' => $stats['draft_products'],  'color' => 'from-amber-500 to-amber-600',     'icon' => 'M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z'],
    ['label' => 'EAN excluse',        'value' => $stats['excluded_eans'],   'color' => 'from-rose-500 to-rose-600',       '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'],
    ['label' => 'Conturi active',     'value' => $stats['active_accounts'], 'color' => 'from-sky-500 to-sky-600',         'icon' => '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'],
  ];
  foreach ($cards as $c): ?>
    <div class="card-hover bg-white rounded-xl p-5 shadow-soft border border-slate-100">
      <div class="flex items-start justify-between">
        <div>
          <div class="text-xs uppercase tracking-wide text-slate-500 font-medium"><?= e($c['label']) ?></div>
          <div class="mt-2 text-3xl font-bold text-slate-900"><?= number_format((int)$c['value'], 0, ',', '.') ?></div>
        </div>
        <div class="w-11 h-11 rounded-xl bg-gradient-to-br <?= e($c['color']) ?> 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="<?= e($c['icon']) ?>"/>
          </svg>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

  <!-- Produse recente -->
  <div class="lg:col-span-2 bg-white rounded-xl shadow-soft border border-slate-100">
    <div class="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
      <h2 class="font-semibold text-slate-900">Produse recente</h2>
      <a href="<?= url('products.php') ?>" class="text-sm text-brand-600 hover:text-brand-700 font-medium">Vezi toate →</a>
    </div>
    <?php if (!$recentProducts): ?>
      <div class="p-10 text-center text-sm text-slate-500">
        <div class="mx-auto w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center mb-3">
          <svg class="w-6 h-6 text-slate-400" fill="none" stroke="currentColor" stroke-width="1.5" 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>
        Niciun produs adăugat încă.
        <div class="mt-3">
          <a href="<?= url('add-product.php') ?>" class="inline-flex items-center gap-2 text-brand-600 hover:text-brand-700 font-medium">
            <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>
            Adaugă primul produs
          </a>
        </div>
      </div>
    <?php else: ?>
      <div class="divide-y divide-slate-100">
        <?php foreach ($recentProducts as $p):
          $badge = ['draft'=>'badge-draft','active'=>'badge-active','synced'=>'badge-synced'][$p['status']] ?? 'badge-draft';
        ?>
          <div class="px-5 py-3 flex items-center gap-4 hover:bg-slate-50 transition">
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-slate-900 truncate"><?= e($p['product_name']) ?></div>
              <div class="text-xs text-slate-500 mt-0.5 flex items-center gap-3">
                <?php if ($p['ean']): ?><span>EAN: <?= e($p['ean']) ?></span><?php endif; ?>
                <?php if ($p['pnk']): ?><span>PNK: <?= e($p['pnk']) ?></span><?php endif; ?>
                <?php if ($p['account_name']): ?><span class="text-slate-400">·</span><span><?= e($p['account_name']) ?></span><?php endif; ?>
              </div>
            </div>
            <span class="text-[11px] font-medium uppercase tracking-wide px-2 py-1 rounded-full <?= $badge ?>"><?= e($p['status']) ?></span>
            <span class="text-xs text-slate-400 hidden sm:inline"><?= date('d.m H:i', strtotime($p['updated_at'])) ?></span>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>

  <!-- Activitate sync -->
  <div class="bg-white rounded-xl shadow-soft border border-slate-100">
    <div class="px-5 py-4 border-b border-slate-100">
      <h2 class="font-semibold text-slate-900">Ultimele sincronizări</h2>
      <div class="text-xs text-slate-500 mt-0.5">
        <?php if ($stats['last_sync']): ?>
          Ultimul sync: <?= date('d.m.Y H:i', strtotime($stats['last_sync'])) ?>
        <?php else: ?>
          Niciun sync efectuat
        <?php endif; ?>
      </div>
    </div>
    <?php if (!$recentLogs): ?>
      <div class="p-8 text-center text-sm text-slate-500">
        Niciun log de sincronizare.
      </div>
    <?php else: ?>
      <ul class="divide-y divide-slate-100">
        <?php foreach ($recentLogs as $log):
          $dot = ['success'=>'bg-emerald-500','partial'=>'bg-amber-500','failed'=>'bg-rose-500'][$log['status']] ?? 'bg-slate-400';
        ?>
          <li class="px-5 py-3 text-sm">
            <div class="flex items-center gap-2">
              <span class="w-2 h-2 rounded-full <?= $dot ?>"></span>
              <span class="font-medium text-slate-800"><?= e($log['account_name'] ?? 'Cont șters') ?></span>
              <span class="ml-auto text-xs text-slate-400"><?= date('d.m H:i', strtotime($log['created_at'])) ?></span>
            </div>
            <div class="mt-1 text-xs text-slate-500 ml-4">
              <?= (int)$log['products_new'] ?> noi · <?= (int)$log['products_updated'] ?> actualizate · <?= (int)$log['products_errors'] ?> erori
            </div>
          </li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>
  </div>

</div>

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