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

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

$dbError = null;
$search  = trim((string)($_GET['q'] ?? ''));
$fStatus = (string)($_GET['status'] ?? '');
$orders  = [];
$stats   = ['count' => 0, 'value' => 0.0];
// Totalurile din bara lipită de jos (calculate pe comenzile filtrate).
$sumFoot = ['lines' => 0, 'qty' => 0.0, 'cancelled' => 0, 'cur' => []];

// „Comandă nouă" — creează o ciornă și trimite direct în editor.
if (($_GET['new'] ?? '') === '1') {
    try {
        $id = db_exec(
            "INSERT INTO orders (order_no, order_date, status, currency, vat_rate) VALUES (?, ?, 'draft', 'RON', ?)",
            [order_next_no(), date('Y-m-d'), vat_rate()]
        );
        header('Location: ' . url('order.php?id=' . $id));
        exit;
    } catch (Throwable $ex) {
        flash_set('error', 'Nu am putut crea comanda: ' . $ex->getMessage());
    }
}

try {
    $where  = [];
    $params = [];
    if ($search !== '') {
        $where[] = '(o.order_no LIKE ? OR o.supplier LIKE ? OR o.notes LIKE ?)';
        $q = '%' . $search . '%';
        array_push($params, $q, $q, $q);
    }
    if (array_key_exists($fStatus, order_statuses())) {
        $where[] = 'o.status = ?';
        $params[] = $fStatus;
    }
    $whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    $orders = db_select(
        "SELECT o.*,
                (SELECT COUNT(*) FROM order_items i WHERE i.order_id = o.id) AS lines_count,
                (SELECT COALESCE(SUM(i.qty), 0) FROM order_items i WHERE i.order_id = o.id) AS qty_total,
                (SELECT COALESCE(SUM(i.qty * i.unit_price), 0) FROM order_items i WHERE i.order_id = o.id) AS subtotal
         FROM orders o
         $whereSql
         ORDER BY o.order_date DESC, o.id DESC",
        $params
    );

    // Valoarea se cumulează pe monedă — comenzile pot fi în RON, USD, EUR etc.
    // În aceeași trecere strângem și totalurile pentru bara de jos (linii, bucăți,
    // subtotal/TVA/total pe monedă). Comenzile anulate nu intră în sume.
    $byCurrency = [];
    foreach ($orders as &$o) {
        $o['total'] = round((float)$o['subtotal'] * (1 + (float)$o['vat_rate'] / 100), 2);
        if ($o['status'] === 'cancelled') {
            $sumFoot['cancelled']++;
            continue;
        }
        $cur = $o['currency'] ?: 'RON';
        $byCurrency[$cur] = ($byCurrency[$cur] ?? 0) + $o['total'];

        $sub = (float)$o['subtotal'];
        $sumFoot['lines'] += (int)$o['lines_count'];
        $sumFoot['qty']   += (float)$o['qty_total'];
        $sumFoot['cur'][$cur]['subtotal'] = ($sumFoot['cur'][$cur]['subtotal'] ?? 0) + $sub;
        $sumFoot['cur'][$cur]['vat']      = ($sumFoot['cur'][$cur]['vat']      ?? 0) + ($o['total'] - $sub);
        $sumFoot['cur'][$cur]['total']    = ($sumFoot['cur'][$cur]['total']    ?? 0) + $o['total'];
    }
    unset($o);
    $stats['count']    = count($orders);
    $stats['currency'] = $byCurrency;
} catch (Throwable $ex) {
    $dbError = $ex->getMessage();
}

$statuses = order_statuses();
$company  = order_company();
// Fără denumire de firmă antetul documentului rămâne gol — deschidem panoul.
$companyMissing = ($company['name'] === '');
$badge = [
    'draft'     => 'bg-slate-100 text-slate-600',
    'sent'      => 'bg-sky-50 text-sky-700',
    'confirmed' => 'bg-indigo-50 text-indigo-700',
    'received'  => 'bg-emerald-50 text-emerald-700',
    'cancelled' => 'bg-rose-50 text-rose-700',
];

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 class="flex items-center gap-3 flex-wrap mb-4">
  <h1 class="text-2xl font-bold text-slate-900">Orders</h1>
  <?php
    $valueParts = [];
    foreach (($stats['currency'] ?? []) as $cur => $sum) { $valueParts[] = money($sum) . ' ' . $cur; }
    $countLabel = (int)$stats['count'] === 1 ? '1 comandă' : (int)$stats['count'] . ' comenzi';
  ?>
  <span class="text-sm text-slate-400"><?= e($countLabel) ?><?= $valueParts ? ' · ' . e(implode(' · ', $valueParts)) : '' ?></span>
  <div class="flex-1"></div>
  <a href="<?= e(url('orders.php?new=1')) ?>"
     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">
    <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>
    Comandă nouă
  </a>
</div>

<?= order_tabs('orders') ?>

<?php if ($companyMissing): ?>
  <div class="mb-4 flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-xl px-4 py-2.5 text-sm text-amber-900">
    <svg class="w-4 h-4 flex-shrink-0" 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>
    Datele firmei nu sunt completate — antetul comenzilor va apărea gol.
    <a href="<?= e(url('firma.php')) ?>" class="font-medium underline hover:no-underline">Completează acum →</a>
  </div>
<?php endif; ?>

<!-- Filtre -->
<form method="get" data-ajax-filters class="flex flex-wrap items-center gap-2 mb-4">
  <input type="text" name="q" value="<?= e($search) ?>" placeholder="Caută număr, furnizor sau notă…"
    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="status" onchange="this.form.requestSubmit()"
    class="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">
    <option value="">Status: toate</option>
    <?php foreach ($statuses as $k => $lbl): ?>
      <option value="<?= e($k) ?>" <?= $fStatus === $k ? 'selected' : '' ?>><?= e($lbl) ?></option>
    <?php endforeach; ?>
  </select>
  <?php if ($search !== '' || $fStatus !== ''): ?>
    <a href="<?= e(url('orders.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>

<!-- Tabel comenzi -->
<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">
          <th class="px-3 py-2.5 w-36">Număr</th>
          <th class="px-3 py-2.5 w-28">Dată</th>
          <th class="px-3 py-2.5">Furnizor</th>
          <th class="px-3 py-2.5 w-28 text-right">Articole</th>
          <th class="px-3 py-2.5 w-32 text-right">Total</th>
          <th class="px-3 py-2.5 w-28">Status</th>
          <th class="px-3 py-2.5 w-28 text-center">Acțiune</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-slate-50">
        <?php foreach ($orders as $o): ?>
          <tr class="hover:bg-slate-50/50">
            <td class="px-3 py-2.5">
              <a href="<?= e(url('order.php?id=' . (int)$o['id'])) ?>" class="font-mono font-medium text-brand-600 hover:text-brand-700"><?= e($o['order_no']) ?></a>
              <?php if (($o['lang'] ?? 'ro') !== 'ro'): ?>
                <span class="ml-1 px-1 py-0.5 rounded bg-slate-100 text-slate-500 text-[9px] font-semibold uppercase"><?= e($o['lang']) ?></span>
              <?php endif; ?>
            </td>
            <td class="px-3 py-2.5 text-slate-500 tabular-nums"><?= e(date('d.m.Y', strtotime($o['order_date']))) ?></td>
            <td class="px-3 py-2.5 truncate"><?= $o['supplier'] ? e($o['supplier']) : '<span class="text-slate-300">—</span>' ?></td>
            <td class="px-3 py-2.5 text-right text-slate-500 tabular-nums">
              <?= (int)$o['lines_count'] ?> <span class="text-slate-300">·</span> <?= e(qty_fmt((float)$o['qty_total'])) ?> buc
            </td>
            <td class="px-3 py-2.5 text-right font-semibold tabular-nums"><?= money((float)$o['total']) ?> <span class="text-[11px] font-normal text-slate-400"><?= e($o['currency']) ?></span></td>
            <td class="px-3 py-2.5">
              <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wide <?= $badge[$o['status']] ?? 'bg-slate-100 text-slate-600' ?>">
                <?= e($statuses[$o['status']] ?? $o['status']) ?>
              </span>
            </td>
            <td class="px-3 py-2.5">
              <div class="flex items-center justify-center gap-1">
                <a href="<?= e(url('order.php?id=' . (int)$o['id'])) ?>" title="Deschide comanda"
                   class="inline-flex items-center justify-center w-8 h-8 text-brand-600 hover:text-brand-700 hover:bg-brand-50 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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                </a>
                <a href="<?= e(url('order-print.php?id=' . (int)$o['id'])) ?>" target="_blank" title="Printează / PDF"
                   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="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
                </a>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$orders): ?>
          <tr><td colspan="7" class="px-4 py-12 text-center text-sm text-slate-400">
            Nicio comandă. Începe cu <a href="<?= e(url('marfa.php')) ?>" class="text-brand-600 hover:underline">catalogul de marfă</a>,
            apoi creează o <a href="<?= e(url('orders.php?new=1')) ?>" class="text-brand-600 hover:underline">comandă nouă</a>.
          </td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Total comenzi — bară lipită de marginea de jos a ecranului -->
<?php if ($orders): ?>
  <div class="sticky bottom-0 z-30 -mx-6 mt-4 px-6 py-2.5 bg-white/95 backdrop-blur border-t border-slate-200 shadow-[0_-2px_12px_rgba(15,23,42,0.07)]">
    <div class="flex items-end gap-x-7 gap-y-2 flex-wrap">

      <div>
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Comenzi</div>
        <div class="text-base font-semibold text-slate-900 tabular-nums"><?= (int)$stats['count'] ?></div>
      </div>
      <div>
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Linii</div>
        <div class="text-base font-semibold text-slate-900 tabular-nums"><?= (int)$sumFoot['lines'] ?></div>
      </div>
      <div>
        <div class="text-[10px] uppercase tracking-wide text-slate-400">Produse</div>
        <div class="text-base font-semibold text-slate-900 tabular-nums"><?= e(qty_fmt($sumFoot['qty'])) ?> <span class="text-xs font-normal text-slate-400">buc</span></div>
      </div>

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

      <?php if (!$sumFoot['cur']): ?>
        <div class="text-sm text-slate-400">Fără valoare de calculat</div>
      <?php else: ?>
        <?php foreach ($sumFoot['cur'] as $cur => $v): ?>
          <div class="flex items-end gap-5">
            <div class="text-right">
              <div class="text-[10px] uppercase tracking-wide text-slate-400">Subtotal</div>
              <div class="text-sm font-medium text-slate-600 tabular-nums"><?= money($v['subtotal']) ?></div>
            </div>
            <div class="text-right">
              <div class="text-[10px] uppercase tracking-wide text-slate-400">TVA</div>
              <div class="text-sm font-medium text-slate-600 tabular-nums"><?= money($v['vat']) ?></div>
            </div>
            <div class="text-right">
              <div class="text-[10px] uppercase tracking-wide text-slate-400">Total <?= e($cur) ?></div>
              <div class="text-lg font-bold text-slate-900 tabular-nums leading-6"><?= money($v['total']) ?> <span class="text-xs font-normal text-slate-400"><?= e($cur) ?></span></div>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <?php if ($sumFoot['cancelled'] > 0 || $search !== '' || $fStatus !== ''): ?>
      <div class="text-[11px] text-slate-400 mt-1">
        <?php
          $notes = [];
          if ($search !== '' || $fStatus !== '') $notes[] = 'doar comenzile filtrate';
          if ($sumFoot['cancelled'] > 0) {
              $notes[] = $sumFoot['cancelled'] . ($sumFoot['cancelled'] === 1 ? ' comandă anulată, neinclusă' : ' comenzi anulate, neincluse');
          }
        ?>
        <?= e(ucfirst(implode(' · ', $notes))) ?>
      </div>
    <?php endif; ?>
  </div>
<?php endif; ?>

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