<?php
global $db, $config, $auth;
$basePath = rtrim(($config['app']['base_path'] ?? ''), '/');

$id = (int)($_GET['id'] ?? 0);

$stmt = $db->prepare("
  SELECT
    i.*,

    h.hbl_no,
    h.goods_description,
    h.packages,
    h.gross_weight_kg,
    h.cbm,

    h.manifest_no,
    h.hs_code,
    h.icms_bl_no,
    h.cfs,

    m.mbl_no,
    m.vessel_name,
    m.voyage_no,
    m.eta_date,
    m.container_no,

    pol.name AS pol_name,
    pod.name AS pod_name,

    c1.name AS consignee_name, c1.address AS consignee_address,
    c2.name AS billing_name,   c2.address AS billing_address

  FROM invoices i
  JOIN house_bls h ON h.id = i.house_bl_id
  JOIN master_bls m ON m.id = h.master_bl_id
  LEFT JOIN ports pol ON pol.id = m.pol_port_id
  LEFT JOIN ports pod ON pod.id = m.pod_port_id
  JOIN customers c1 ON c1.id = i.consignee_customer_id
  JOIN customers c2 ON c2.id = i.billing_party_customer_id
  WHERE i.id = ?
");
$stmt->execute([$id]);
$inv = $stmt->fetch();
if (!$inv) { echo "<div>Invoice not found.</div>"; return; }

$db->prepare("
    INSERT INTO invoice_events (
        invoice_id,
        event_type,
        user_id,
        ip_address,
        user_agent
    ) VALUES (
        ?, 'VIEWED', ?, ?, ?
    )
")->execute([
    $id,
    $_SESSION['uid'] ?? $_SESSION['user_id'] ?? null,
    $_SERVER['REMOTE_ADDR'] ?? null,
    $_SERVER['HTTP_USER_AGENT'] ?? null
]);

$items = $db->prepare("
  SELECT
    ii.*,
    ct.name AS charge_name
  FROM invoice_items ii
  JOIN charge_types ct ON ct.id = ii.charge_type_id
  WHERE ii.invoice_id = ?
  ORDER BY ii.id
");
$items->execute([$id]);
$rows = $items->fetchAll();

if (!function_exists('n2')) { function n2($v){ return number_format((float)$v, 2); } }
if (!function_exists('n3')) { function n3($v){ return number_format((float)$v, 3); } }

$subtotal = (float)($inv['subtotal'] ?? 0);
$total    = (float)($inv['total'] ?? 0);
$discount = 0.00;
$net      = $subtotal;
$vatRate  = 16.0;

$flatBase = 0.0;
foreach ($rows as $it) {
  $basis = strtoupper(trim((string)($it['basis'] ?? '')));
  if ($basis === 'FLAT') {
    $flatBase += (float)($it['amount'] ?? 0);
  }
}
$vatAmount = round($flatBase * 0.16, 2);

// Keep invoice totals consistent even for old data / safety
$expectedTotal = round($net + $vatAmount, 2);
if (abs($total - $expectedTotal) > 0.009) {
  $total = $expectedTotal;
}

$issueDate = $inv['issue_date'] ?: date('Y-m-d');
$invoiceNo = $inv['invoice_no'] ?: ('INV-' . $id);

$wm = '';
$st = strtoupper((string)($inv['status'] ?? ''));

/*
if ($st === 'PAID')        $wm = 'PAID';
elseif ($st === 'ISSUED')  $wm = 'ISSUED';
elseif ($st === 'DRAFT')   $wm = 'DRAFT';
elseif ($st === 'CANCELLED') $wm = 'CANCELLED';
elseif ($st === 'PART_PAID') $wm = 'PART PAID';
*/

// Shipment fields
$vessel   = (string)($inv['vessel_name'] ?? '');
$voyage   = (string)($inv['voyage_no'] ?? '');
$polName  = (string)($inv['pol_name'] ?? '');
$podName  = (string)($inv['pod_name'] ?? '');
$mblNo    = (string)($inv['mbl_no'] ?? '');
$hblNo    = (string)($inv['hbl_no'] ?? '');
$weightKg = (float)($inv['gross_weight_kg'] ?? 0);
$cbm      = (float)($inv['cbm'] ?? 0);
$pkgs     = (string)($inv['packages'] ?? '');
$desc     = (string)($inv['goods_description'] ?? '');

$containerNo = (string)($inv['container_no'] ?? '');
$manifestNo  = (string)($inv['manifest_no'] ?? '');
$hsCode      = (string)($inv['hs_code'] ?? '');
$icmsBlNo    = (string)($inv['icms_bl_no'] ?? '');
$cfs         = (string)($inv['cfs'] ?? '');

function itemLabel(array $it): string {
  $desc = trim((string)($it['description'] ?? ''));
  $name = strtoupper(trim((string)($it['charge_name'] ?? '')));
  return $desc !== '' ? strtoupper($desc) : $name;
}

$servedBy = '';
if (isset($auth) && $auth instanceof Auth) {
  $authUser = $auth->user();
  if (is_array($authUser) && !empty($authUser['full_name'])) {
    $servedBy = trim((string)$authUser['full_name']);
  }
}
if ($servedBy === '' && !empty($_SESSION['uid'])) {
  try {
    $uStmt = $db->prepare("SELECT full_name FROM users WHERE id = ? LIMIT 1");
    $uStmt->execute([(int)$_SESSION['uid']]);
    $uRow = $uStmt->fetch();
    if ($uRow && !empty($uRow['full_name'])) {
      $servedBy = trim((string)$uRow['full_name']);
    }
  } catch (Throwable $e) {
    $servedBy = '';
  }
}
$servedBy = strtoupper($servedBy);
?>
<style>
  header,
  nav,
  .app-header,
  .app-navbar,
  .topbar,
  .user-menu {
    display: none !important;
  }

  body {
    margin-top: 0 !important;
  }

  .inv-wrap{
    background:#fff;
    color:#000;
    font-family:Arial, Helvetica, sans-serif;
    padding:0;
    box-sizing:border-box;
  }

  .inv-sheet{
    max-width:900px;
    width:900px;
    margin-left:1cm;
    border:3px solid #f97316;
    padding:18px;
    box-sizing:border-box;
    min-height:297mm;
    position: relative;
  }

  .inv-divider{
    height:0;
    border-top:3px solid #f97316;
    margin:8px -18px 12px;
  }

  .banner{
    width:auto;
    max-width:520px;
    height:auto;
    display:block;
    margin:0;
  }

  .inv-title{font-weight:700;text-align:center;letter-spacing:.5px;margin:0 0 10px 0;}
  .topgrid{
    display:grid;
    grid-template-columns:1fr 1fr 1fr;
    gap:18px;
    margin-bottom:10px;
    font-size:12px;
    line-height:1.25;
  }

  .meta-align{
    margin-left:85px;
    text-align:left;
  }
  .meta-align .lbl,
  .meta-align .val{
    margin:0;
    text-align:left;
  }

  .lbl{font-weight:700;text-transform:uppercase;}
  .val{margin-top:2px;white-space:pre-line;}
  .box{margin-top:6px;}
  .midgrid{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin:10px 0 8px;font-size:12px;}
  .midrow{display:grid;grid-template-columns:190px 1fr;gap:10px;margin:3px 0;}
  .midrow .k{font-weight:700;text-transform:uppercase;}
  .items{width:100%;border-collapse:collapse;margin-top:10px;font-size:12px;}
  .items th{border-bottom:1px solid #000;padding:6px 4px;text-align:left;font-weight:700;text-transform:uppercase;}
  .items td{padding:6px 4px;border-bottom:1px solid #ddd;}
  .r{text-align:right;}
  .totals{margin-top:10px;display:grid;grid-template-columns:1fr 280px;gap:10px;font-size:12px;align-items:start;}
  .tot{width:100%;border-collapse:collapse;}
  .tot td{padding:4px 0;}
  .tot .k{font-weight:700;text-transform:uppercase;}
  .remit{margin-top:0;font-size:12px;white-space:pre-line;line-height:1.15;}
  .remit .hdr{font-weight:700;text-transform:uppercase;margin:0 0 4px 0;}
  .print-actions{display:flex;justify-content:flex-end;gap:8px;margin-bottom:8px;}
  .btn{padding:8px 10px;border:1px solid #000;background:#fff;color:#000;border-radius:6px;cursor:pointer;font-size:12px;text-decoration:none;display:inline-block;}
  .inv-banner{
    display:flex;
    justify-content:flex-start;
    margin-bottom:8px;
  }

  .banner{
    display:block;
    max-width:100%;
    height:auto;
  }

  .inv-watermark{
    position:absolute;
    inset:0;
    display:flex;
    align-items:center;
    justify-content:center;
    pointer-events:none;
    z-index:0;
  }

  .inv-watermark span{
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:6px;
    font-size:72px;
    line-height:1;
    opacity:0.10;
    transform:rotate(-28deg);
    color:#111;
    white-space:nowrap;
  }

  .inv-sheet > *:not(.inv-watermark){
    position:relative;
    z-index:1;
  }

  .items th.r{
    text-align:right;
  }

  .tot .label{
    font-weight:700;
    text-transform:uppercase;
    font-size:12px;
    letter-spacing:0.3px;
    white-space:nowrap;
  }

  .audit-footer{
    margin-top: 28px;
    padding-top: 8px;
    border-top: 1px dashed #d1d5db;
    font-size: 11px;
    color: #6b7280;
    text-align: right;
  }

  @media print{
    .print-actions{display:none;}
    .inv-sheet{
      margin-left:1cm;
      width:auto;
      max-width:none;
      padding:12px 12px 0 12px;
      border:3px solid #f97316;
      box-sizing:border-box;
      min-height:255mm;
    }

    .banner{
      max-height:60px;
      object-fit:contain;
    }

    .inv-divider{
      margin-left:-12px;
      margin-right:-12px;
      border-top:3px solid #f97316;
    }

    .inv-watermark span{
      opacity:0.12;
      -webkit-print-color-adjust:exact;
      print-color-adjust:exact;
    }
  }
</style>

<div class="inv-wrap">
  <div class="inv-sheet">

  <?php if ($wm !== ''): ?>
    <div class="inv-watermark"><span><?= h($wm) ?></span></div>
  <?php endif; ?>

 <div class="print-actions">
  <a class="btn" href="<?= h($basePath) ?>/invoice/download?id=<?= (int)$id ?>">Download PDF</a>
  <button class="btn" onclick="window.print()">Print</button>
</div>

  <div class="inv-banner">
    <img
      class="banner"
      src="<?= h($basePath) ?>/assets/wcs-banner.png"
      alt="WSC Banner"
    />
  </div>

  <div class="inv-divider"></div>

  <h2 class="inv-title" style="color:#f97316; font-weight:700;">
    INVOICE
  </h2>

  <div class="topgrid">
    <div>
      <div class="lbl">TO</div>
      <div class="val box"><?= strtoupper(h($inv['consignee_name'])) . "\n" . h($inv['consignee_address']) ?></div>
    </div>

    <div>
      <div class="lbl">BILL TO</div>
      <div class="val box"><?= strtoupper(h($inv['billing_name'])) . "\n" . h($inv['billing_address']) ?></div>
    </div>

    <div class="meta-align">
      <div class="lbl">DATE</div>
      <div class="val"><?= h($issueDate) ?></div>

      <div class="lbl" style="margin-top:8px;">INVOICE NO.</div>
      <div class="val"><?= h($invoiceNo) ?></div>
    </div>

  </div>

  <div class="midgrid">
    <div>
      <div class="midrow"><div class="k">VESSEL</div><div><?= h($vessel) ?></div></div>
      <div class="midrow"><div class="k">PORT OF LOADING</div><div><?= h($polName) ?></div></div>
      <div class="midrow"><div class="k">PORT OF DISCHARGE</div><div><?= h($podName) ?></div></div>
      <div class="midrow"><div class="k">CONTAINER NUMBER</div><div><?= h($containerNo) ?></div></div>
      <div class="midrow"><div class="k">MBL</div><div><?= h($mblNo) ?></div></div>
      <div class="midrow"><div class="k">HBL</div><div><?= h($hblNo) ?></div></div>
      <div class="midrow"><div class="k">WEIGHT</div><div><?= n2($weightKg) ?> KGS</div></div>
      <div class="midrow"><div class="k">VOLUME</div><div><?= n3($cbm) ?> CBM</div></div>
    </div>

    <div>
      <div class="midrow"><div class="k">VOYAGE</div><div><?= h($voyage) ?></div></div>
      <div class="midrow"><div class="k">DESCRIPTION</div><div><?= h($desc) ?></div></div>
      <div class="midrow"><div class="k">PACKAGES</div><div><?= h($pkgs) ?></div></div>
      <div class="midrow"><div class="k">HSCODE</div><div><?= h($hsCode) ?></div></div>
      <div class="midrow"><div class="k">MANIFEST NO.</div><div><?= h($manifestNo) ?></div></div>
      <div class="midrow"><div class="k">CFS</div><div><?= h($cfs) ?></div></div>
      <div class="midrow"><div class="k">ICMS BL NO</div><div><?= h($icmsBlNo) ?></div></div>
    </div>
  </div>

  <table class="items">
    <thead>
      <tr>
        <th>ITEM</th>
        <th class="r">PRICE</th>
        <th class="r">QTY</th>
        <th class="r">TOTAL</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($rows as $it): ?>
        <tr>
          <td><?= h(itemLabel($it)) ?></td>
          <td class="r"><?= n2($it['unit_price'] ?? 0) ?></td>
          <td class="r"><?= n3($it['qty'] ?? 0) ?></td>
          <td class="r"><?= n2($it['amount'] ?? 0) ?></td>
        </tr>
      <?php endforeach; ?>
      <?php if (!$rows): ?>
        <tr><td colspan="4" style="padding:10px 4px;">&nbsp;</td></tr>
      <?php endif; ?>
    </tbody>
  </table>

  <div class="totals">
    <div class="remit">
      <div class="hdr">Remarks / Payment Instructions:</div>
DIRECT REMITTANCE TO ACCOUNT
WSC LOGISTICS KENYA LTD
KENYA COMMERCIAL BANK
MVITA BRANCH - MOMBASA
ACCOUNT NUMBER 132 - 1815 - 573
BRANCH CODE 136
SWIFT CODE KCBLKENX
P O BOX 81194 – 80100 MOMBASA KENYA
    </div>

    <table class="tot">
        <tr>
          <td class="label">Subtotal</td>
          <td class="r"><?= n2($subtotal) ?></td>
        </tr>
        <tr>
          <td class="label">Discount</td>
          <td class="r"><?= n2($discount) ?></td>
        </tr>
        <tr>
          <td class="label">Subtotal Less Discount</td>
          <td class="r"><?= n2($net) ?></td>
        </tr>
        <tr>
          <td class="label">Vat Rate <?= rtrim(rtrim(number_format($vatRate, 2), '0'), '.') ?>%</td>
          <td class="r"><?= n2($vatAmount) ?></td>
        </tr>
        <tr>
          <td class="label">Total</td>
          <td class="r" style="font-weight:700;"><?= n2($total) ?></td>
        </tr>
        <tr>
          <td class="label">Balance Due &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(USD)</td>
          <td class="r" style="font-weight:700;"><?= n2($total) ?></td>
        </tr>
    </table>
  </div>

  <div class="audit-footer">
    Served by: <?= h((string)($servedBy !== '' ? $servedBy : '—')) ?>
  </div>

  <script>
    (function(){
      const BASE = <?= json_encode($basePath, JSON_UNESCAPED_SLASHES) ?>;
      const invoiceId = <?= (int)$id ?>;

      function withBase(url){
        if (!BASE) return url;
        if (!url.startsWith('/')) url = '/' + url;
        if (url === BASE || url.startsWith(BASE + '/')) return url;
        return BASE + url;
      }

      function markIssued(){
        const url = withBase('/api/invoice/mark-issued');
        const currentStatus = <?= json_encode((string)$inv['status']) ?>;
        if (currentStatus === 'ISSUED') return;

        const fd = new FormData();
        fd.append('invoice_id', String(invoiceId));

        if (navigator.sendBeacon) {
          navigator.sendBeacon(url, fd);
          return;
        }

        fetch(url, {
          method: 'POST',
          body: fd,
          headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).catch(()=>{});
      }

      window.addEventListener('beforeprint', markIssued);
      window.addEventListener('afterprint', markIssued);
    })();
  </script>
  </div>
</div>