<?php
global $db, $config;

$basePath = rtrim(($config['app']['base_path'] ?? ''), '/');
$mblId = (int)($_GET['master_bl_id'] ?? $_GET['mbl_id'] ?? $_GET['id'] ?? 0);

if (!function_exists('h')) {
  function h($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
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); }
}

if ($mblId <= 0) {
  echo "<div class='doc-wrap'><div class='doc-sheet'>Missing MBL reference.</div></div>";
  return;
}

$stmt = $db->prepare("
  SELECT
    m.*,
    sl.name AS shipping_line_name,
    p1.name AS pol_name,
    p2.name AS pod_name
  FROM master_bls m
  LEFT JOIN shipping_lines sl ON sl.id = m.shipping_line_id
  LEFT JOIN ports p1 ON p1.id = m.pol_port_id
  LEFT JOIN ports p2 ON p2.id = m.pod_port_id
  WHERE m.id = ?
  LIMIT 1
");
$stmt->execute([$mblId]);
$m = $stmt->fetch();

if (!$m) {
  echo "<div class='doc-wrap'><div class='doc-sheet'>MBL not found.</div></div>";
  return;
}

$hbls = $db->prepare("
  SELECT
    h.hbl_no,
    h.goods_description,
    h.packages,
    h.gross_weight_kg,
    h.cbm,
    h.marks_numbers,
    h.cfs,
    c1.name AS consignee_name,
    c1.address AS consignee_address,
    c2.name AS billing_name,
    c2.address AS billing_address
  FROM house_bls h
  LEFT JOIN customers c1 ON c1.id = h.consignee_customer_id
  LEFT JOIN customers c2 ON c2.id = h.billing_party_customer_id
  WHERE h.master_bl_id = ?
  ORDER BY h.id ASC
");
$hbls->execute([$mblId]);
$rows = $hbls->fetchAll();

$totalPackages = 0;
$totalWeight = 0.0;
$totalCbm = 0.0;

foreach ($rows as $r) {
  $totalPackages += (int)($r['packages'] ?? 0);
  $totalWeight += (float)($r['gross_weight_kg'] ?? 0);
  $totalCbm += (float)($r['cbm'] ?? 0);
}

$manifestDate = date('j \\T\\H F Y');
$cfsValue = trim((string)($rows[0]['cfs'] ?? ''));
if ($cfsValue === '') {
  $cfsValue = trim((string)($rows[0]['billing_name'] ?? $rows[0]['consignee_name'] ?? '—'));
}

$pdfUrl = $basePath . '/doc/manifest/download?master_bl_id=' . (int)$mblId . '&v=' . time();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manifest</title>

<style>
  html, body {
    background: #f3f6fb;
    margin: 0;
    padding: 0;
  }

  .doc-wrap {
    background: #f3f6fb;
    color: #000;
    font-family: Arial, Helvetica, sans-serif;
    padding: 18px 0 30px;
  }

  .doc-sheet {
    max-width: 980px;
    width: calc(100% - 48px);
    margin: 0 auto;
    border: 1px solid #666;
    padding: 24px 24px 20px;
    box-sizing: border-box;
    background: #fff;
    box-shadow: 0 10px 30px rgba(0,0,0,.10);
  }

  .doc-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;
  }

  .topbar {
    display: grid;
    grid-template-columns: 1.05fr .95fr;
    gap: 22px;
    align-items: start;
    margin-bottom: 22px;
  }

  .meta-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
  }

  .meta-table td {
    border: 1px solid #555;
    padding: 4px 8px;
    vertical-align: top;
  }

  .meta-table .k {
    width: 45%;
    font-weight: 700;
    text-transform: uppercase;
    background: #f5f5f5;
  }

  .brand-box {
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
    min-height: 140px;
  }

  .brand-half {
    width: 88%;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: flex-start;
  }

  .brand-half img {
    width: 100%;
    max-width: 430px;
    height: auto;
    display: block;
  }

  .brand-address {
    width: 100%;
    max-width: 430px;
    margin-top: 8px;
    text-align: center;
    color: #e96f00;
    font-weight: 700;
    font-size: 13px;
    line-height: 1.35;
  }

  .manifest-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
  }

  .manifest-table th,
  .manifest-table td {
    border: 1px solid #333;
    padding: 6px 6px;
    vertical-align: top;
  }

  .manifest-table th {
    text-align: left;
    font-weight: 700;
    background: #f3f4f6;
  }

  .manifest-table .num {
    text-align: right;
    white-space: nowrap;
  }

  .totals-row td {
    font-weight: 700;
    background: #fafafa;
  }

  .small {
    font-size: 11px;
    line-height: 1.35;
  }

  @media print {
    @page {
      size: A4 landscape;
      margin: 8mm;
    }

    .doc-actions {
      display: none !important;
    }

    * {
      -webkit-print-color-adjust: exact;
      print-color-adjust: exact;
    }

    html, body {
      background: #fff !important;
      margin: 0 !important;
      padding: 0 !important;
    }

    .doc-wrap {
      background: #fff !important;
      padding: 0 !important;
    }

    .doc-sheet {
      width: auto;
      max-width: none;
      margin: 0;
      border: 1px solid #666;
      padding: 16px;
      box-shadow: none !important;
    }

    .brand-address {
      color: #e96f00 !important;
      font-weight: 700 !important;
    }
  }
</style>
</head>
<body>

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

    <div class="doc-actions">
      <a class="btn" href="<?= h($pdfUrl) ?>">Download PDF</a>
      <button class="btn" onclick="window.print()">Print</button>
    </div>

    <div class="topbar">
      <div>
        <table class="meta-table">
          <tr><td class="k">DATE</td><td><?= h($manifestDate) ?></td></tr>
          <tr><td class="k">CFS</td><td><?= h($cfsValue !== '' ? $cfsValue : '—') ?></td></tr>
          <tr><td class="k">VESSEL</td><td><?= h(trim((string)($m['vessel_name'] ?? '') . ' ' . (string)($m['voyage_no'] ?? ''))) ?: '—' ?></td></tr>
          <tr>
            <td class="k">CONTAINER</td>
            <td>
              <?=
                h(
                  trim((string)($m['container_no'] ?? '')) .
                  (
                    trim((string)($m['container_type'] ?? '')) !== ''
                      ? ' : ' . trim((string)$m['container_type'])
                      : ''
                  )
                ) ?: '—'
              ?>
            </td>
          </tr>
          <tr><td class="k">ETA</td><td><?= h($m['eta_date'] ?? '—') ?></td></tr>
          <tr><td class="k">MBL</td><td><?= h($m['mbl_no'] ?? '—') ?></td></tr>
          <tr><td class="k">LOADING / DISCHARGE PORT</td><td><?= h(trim((string)($m['pol_name'] ?? '') . ' / ' . (string)($m['pod_name'] ?? ''))) ?: '—' ?></td></tr>
          <tr><td class="k">SHIPPING LINE</td><td><?= h($m['shipping_line_name'] ?? '—') ?></td></tr>
        </table>
      </div>

      <div class="brand-box">
        <div class="brand-half">
          <img src="<?= h($basePath) ?>/assets/wcs-banner2.png" alt="WSC Banner">
          <div class="brand-address">
            <div>P O BOX 81194-80100</div>
            <div>NEW CANNON TOWERS 7TH FLOOR</div>
            <div>MOI AVENUE - MOMBASA KENYA</div>
          </div>
        </div>
      </div>
    </div>

    <table class="manifest-table">
      <thead>
        <tr>
          <th style="width:14%;">HBL</th>
          <th style="width:18%;">CONSIGNEE</th>
          <th style="width:18%;">MARKS &amp; NUMBERS</th>
          <th style="width:26%;">CARGO DESCRIPTION</th>
          <th style="width:10%;">QUANTITY</th>
          <th style="width:7%;">WEIGHT<br>(KGS)</th>
          <th style="width:7%;">CBM<br>(M3)</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): ?>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td class="small"><?= nl2br(h($r['hbl_no'] ?? '—')) ?></td>
              <td class="small">
                <?= h($r['consignee_name'] ?? '') ?><br>
                <?= nl2br(h($r['consignee_address'] ?? '')) ?>
              </td>
              <td class="small">
                <?= nl2br(h(trim((string)($r['marks_numbers'] ?? '')) !== '' ? $r['marks_numbers'] : 'NO MARKS')) ?>
              </td>
              <td class="small"><?= nl2br(h($r['goods_description'] ?? '—')) ?></td>
              <td><?= h(((int)($r['packages'] ?? 0)) . ' PACKAGE' . (((int)($r['packages'] ?? 0)) !== 1 ? 'S' : '')) ?></td>
              <td class="num"><?= h(n2($r['gross_weight_kg'] ?? 0)) ?></td>
              <td class="num"><?= h(n3($r['cbm'] ?? 0)) ?></td>
            </tr>
          <?php endforeach; ?>

          <tr class="totals-row">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td><?= h($totalPackages) ?> PACKAGES</td>
            <td class="num"><?= h(n2($totalWeight)) ?> KGS</td>
            <td class="num"><?= h(n3($totalCbm)) ?> CBM</td>
          </tr>
        <?php else: ?>
          <tr>
            <td colspan="7" style="text-align:center;">No HBL rows found for this MBL.</td>
          </tr>
        <?php endif; ?>
      </tbody>
    </table>

  </div>
</div>

</body>
</html>