<?php
/**
 * Comanda formatată pentru print / salvare ca PDF (A4).
 * Pagină de sine stătătoare — fără sidebar/header de aplicație.
 */
require_once __DIR__ . '/includes/orders.php';

$id    = (int)($_GET['id'] ?? 0);
$order = $id > 0 ? order_load($id) : null;

if (!$order) {
    http_response_code(404);
    echo 'Comanda nu există.';
    exit;
}

$items    = $order['items'];
$totals   = order_totals($items, (float)$order['vat_rate']);
$company  = order_company();
// Limba documentului: cea salvată pe comandă, cu override temporar prin ?lang=
$lang     = order_lang($_GET['lang'] ?? ($order['lang'] ?? 'ro'));
$t        = order_labels($lang);
$statuses = order_statuses($lang);
$langs    = order_langs();
$cur      = $order['currency'];
$priceDec = order_price_decimals($order['price_decimals'] ?? 2);
$dateFmt  = $lang === 'en' ? 'd M Y' : 'd.m.Y';
?>
<!DOCTYPE html>
<html lang="<?= e($lang) ?>">
<head>
<meta charset="UTF-8">
<title><?= e($order['order_no']) ?></title>
<style>
  @page { size: A4; margin: 14mm 12mm; }
  * { box-sizing: border-box; }
  body {
    font-family: "Segoe UI", Inter, Arial, sans-serif;
    color: #0f172a; font-size: 12px; line-height: 1.45;
    margin: 0; padding: 24px; background: #f1f5f9;
  }
  .sheet {
    max-width: 210mm; margin: 0 auto; background: #fff; padding: 16mm 14mm;
    box-shadow: 0 4px 24px rgba(15,23,42,.10);
  }
  .toolbar { max-width: 210mm; margin: 0 auto 12px; display: flex; gap: 8px; justify-content: flex-end; }
  .btn {
    font: inherit; font-weight: 600; font-size: 12px; padding: 8px 14px; border-radius: 8px;
    border: 1px solid #cbd5e1; background: #fff; color: #334155; cursor: pointer; text-decoration: none;
  }
  .btn-primary { background: #4f46e5; border-color: #4f46e5; color: #fff; }

  header.doc { display: flex; justify-content: space-between; gap: 24px; align-items: flex-start; }
  .company-name { font-size: 16px; font-weight: 700; }
  .muted { color: #64748b; }
  .doc-title { font-size: 22px; font-weight: 700; letter-spacing: -.02em; text-align: right; }
  .doc-no { font-family: ui-monospace, Consolas, monospace; font-size: 15px; color: #4f46e5; font-weight: 700; text-align: right; }
  .status {
    display: inline-block; margin-top: 6px; padding: 2px 8px; border-radius: 999px;
    font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em;
    background: #eef2ff; color: #4338ca;
  }

  .rule { height: 2px; background: #0f172a; margin: 14px 0 16px; }

  .meta { display: flex; gap: 32px; margin-bottom: 18px; }
  .meta .block { flex: 1; }
  .label { font-size: 9px; text-transform: uppercase; letter-spacing: .06em; color: #94a3b8; font-weight: 700; margin-bottom: 3px; }
  .value { font-weight: 600; }

  table { width: 100%; border-collapse: collapse; }
  thead th {
    text-align: left; font-size: 9px; text-transform: uppercase; letter-spacing: .05em;
    color: #475569; border-bottom: 1.5px solid #0f172a; padding: 7px 6px; font-weight: 700;
  }
  tbody td { padding: 7px 6px; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
  tbody tr:nth-child(even) td { background: #f8fafc; }
  .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
  .mono { font-family: ui-monospace, Consolas, monospace; font-size: 11px; color: #475569; }
  .idx { color: #94a3b8; width: 26px; text-align: right; }

  .totals { margin-top: 14px; display: flex; justify-content: flex-end; }
  .totals table { width: 260px; }
  .totals td { padding: 5px 6px; border: none; }
  .totals .grand td { border-top: 1.5px solid #0f172a; font-size: 14px; font-weight: 700; padding-top: 8px; }

  .notes { margin-top: 18px; padding: 10px 12px; background: #f8fafc; border-left: 3px solid #cbd5e1; }
  .sign { margin-top: 32px; display: flex; gap: 40px; }
  .sign .box { flex: 1; }
  .sign .line { margin-top: 34px; border-top: 1px solid #94a3b8; padding-top: 4px; font-size: 10px; color: #64748b; }
  footer.doc { margin-top: 22px; font-size: 9px; color: #94a3b8; text-align: center; }

  @media print {
    body { background: #fff; padding: 0; }
    .sheet { box-shadow: none; padding: 0; max-width: none; }
    .toolbar { display: none !important; }
    thead { display: table-header-group; }
    tr { page-break-inside: avoid; }
  }
</style>
</head>
<body>

<div class="toolbar">
  <a class="btn" href="<?= e(url('order.php?id=' . (int)$order['id'])) ?>">← <?= $lang === 'en' ? 'Back to order' : 'Înapoi la comandă' ?></a>
  <?php foreach ($langs as $code => $lbl): if ($code === $lang) continue; ?>
    <a class="btn" href="?id=<?= (int)$order['id'] ?>&lang=<?= e($code) ?>"><?= e($lbl) ?></a>
  <?php endforeach; ?>
  <button class="btn btn-primary" onclick="window.print()"><?= $lang === 'en' ? 'Print / Save as PDF' : 'Printează / Salvează PDF' ?></button>
</div>

<div class="sheet">
  <header class="doc">
    <div>
      <?php if ($company['name']): ?>
        <div class="company-name"><?= e($company['name']) ?></div>
      <?php else: ?>
        <div class="company-name muted"><?= e($t['company_ph']) ?></div>
        <div class="muted" style="font-size:10px"><?= e($t['company_hint']) ?></div>
      <?php endif; ?>
      <?php
        $idLine = implode(' · ', array_filter([
            $company['cui'] ? $t['vat_id'] . ': ' . $company['cui'] : '',
            $company['reg'] ? $t['reg'] . ': ' . $company['reg'] : '',
        ]));
        $addrLine    = implode(', ', array_filter([$company['address'], $company['city'], $company['country']]));
        $contactLine = implode(' · ', array_filter([
            $company['phone'] ? $t['phone'] . ': ' . $company['phone'] : '',
            $company['email'] ?: '',
            $company['web']   ?: '',
        ]));
        $bankLine = implode(' · ', array_filter([
            $company['bank'] ?: '',
            $company['iban'] ? $t['iban'] . ': ' . $company['iban'] : '',
        ]));
      ?>
      <?php if ($idLine):      ?><div class="muted"><?= e($idLine) ?></div><?php endif; ?>
      <?php if ($addrLine):    ?><div class="muted"><?= e($addrLine) ?></div><?php endif; ?>
      <?php if ($contactLine): ?><div class="muted"><?= e($contactLine) ?></div><?php endif; ?>
      <?php if ($bankLine):    ?><div class="muted"><?= e($bankLine) ?></div><?php endif; ?>
    </div>
    <div>
      <div class="doc-title"><?= e($t['doc_title']) ?></div>
      <div class="doc-no"><?= e($order['order_no']) ?></div>
      <div style="text-align:right"><span class="status"><?= e($statuses[$order['status']] ?? $order['status']) ?></span></div>
    </div>
  </header>

  <div class="rule"></div>

  <div class="meta">
    <div class="block">
      <div class="label"><?= e($t['supplier']) ?></div>
      <div class="value"><?= $order['supplier'] ? e($order['supplier']) : '—' ?></div>
    </div>
    <div class="block">
      <div class="label"><?= e($t['order_date']) ?></div>
      <div class="value"><?= e(date($dateFmt, strtotime($order['order_date']))) ?></div>
    </div>
    <div class="block">
      <div class="label"><?= e($t['delivery']) ?></div>
      <div class="value"><?= $order['delivery_date'] ? e(date($dateFmt, strtotime($order['delivery_date']))) : '—' ?></div>
    </div>
    <div class="block">
      <div class="label"><?= e($t['currency']) ?></div>
      <div class="value"><?= e($cur) ?></div>
    </div>
  </div>

  <table>
    <thead>
      <tr>
        <th class="idx"><?= e($t['idx']) ?></th>
        <th style="width:90px"><?= e($t['code']) ?></th>
        <th><?= e($t['name']) ?></th>
        <th style="width:44px"><?= e($t['unit']) ?></th>
        <th class="num" style="width:70px"><?= e($t['qty_short']) ?></th>
        <th class="num" style="width:90px"><?= e($t['unit_price']) ?></th>
        <th class="num" style="width:100px"><?= e($t['amount']) ?></th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($items as $i => $it): $lineTotal = (float)$it['qty'] * (float)$it['unit_price']; ?>
        <tr>
          <td class="idx"><?= $i + 1 ?></td>
          <td class="mono"><?= e($it['sku'] ?? '') ?></td>
          <td><?= e($it['name']) ?></td>
          <td><?= e(order_unit_label($it['unit'], $lang)) ?></td>
          <td class="num"><?= e(qty_fmt((float)$it['qty'], $lang)) ?></td>
          <td class="num"><?= money((float)$it['unit_price'], $lang, $priceDec) ?></td>
          <td class="num"><strong><?= money($lineTotal, $lang) ?></strong></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$items): ?>
        <tr><td colspan="7" style="text-align:center;color:#94a3b8;padding:24px 0"><?= e($t['empty']) ?></td></tr>
      <?php endif; ?>
    </tbody>
  </table>

  <div class="totals">
    <table>
      <tr>
        <td class="muted"><?= e($t['items']) ?></td>
        <td class="num"><?= (int)$totals['lines'] ?> <?= e($t['lines']) ?> · <?= e(qty_fmt($totals['qty'], $lang)) ?> <?= e($t['pcs']) ?></td>
      </tr>
      <tr>
        <td class="muted"><?= e($t['subtotal']) ?></td>
        <td class="num"><?= money($totals['subtotal'], $lang) ?> <?= e($cur) ?></td>
      </tr>
      <?php if ((float)$order['vat_rate'] > 0): ?>
        <tr>
          <td class="muted"><?= e($t['vat']) ?> <?= e(rtrim(rtrim(number_format((float)$order['vat_rate'], 2, '.', ''), '0'), '.')) ?>%</td>
          <td class="num"><?= money($totals['vat'], $lang) ?> <?= e($cur) ?></td>
        </tr>
      <?php endif; ?>
      <tr class="grand">
        <td><?= e($t['total']) ?></td>
        <td class="num"><?= money($totals['total'], $lang) ?> <?= e($cur) ?></td>
      </tr>
    </table>
  </div>

  <?php if ($order['notes']): ?>
    <div class="notes">
      <div class="label"><?= e($t['notes']) ?></div>
      <div><?= nl2br(e($order['notes'])) ?></div>
    </div>
  <?php endif; ?>

  <div class="sign">
    <div class="box"><div class="line"><?= e($t['sign_buyer']) ?></div></div>
    <div class="box"><div class="line"><?= e($t['sign_supplier']) ?></div></div>
  </div>

  <footer class="doc">
    <?= e($t['generated']) ?> <?= e(date($dateFmt . ' H:i')) ?> · <?= e(APP_NAME) ?>
  </footer>
</div>

<?php if (($_GET['print'] ?? '') === '1'): ?>
<script>window.addEventListener('load', () => setTimeout(() => window.print(), 250));</script>
<?php endif; ?>

</body>
</html>
