<?php
global $db, $config, $auth;

$basePath = rtrim(($config['app']['base_path'] ?? ''), '/');
$houseId  = (int)($_GET['house_bl_id'] ?? 0);

/**
 * Helpers
 */
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 (!function_exists('dmy')) {
  function dmy(?string $ymd): string {
    if (!$ymd) return '';
    try { return (new DateTime($ymd))->format('d/m/Y'); }
    catch (Throwable $e) { return (string)$ymd; }
  }
}

/**
 * 12 unique alphanumeric (A–Z, 0–9), no repeats
 */
if (!function_exists('releasingId12')) {
  function releasingId12(): string {
    $chars = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
    shuffle($chars);
    return implode('', array_slice($chars, 0, 12));
  }
}

/**
 * Served by
 */
$servedBy = '';
if (isset($auth) && $auth instanceof Auth) {
  $authUser = $auth->user();
  if (is_array($authUser) && !empty($authUser['full_name'])) {
    $servedBy = strtoupper(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 = strtoupper(trim((string)$uRow['full_name']));
    }
  } catch (Throwable $e) {
    $servedBy = '';
  }
}

$stmt = $db->prepare("
  SELECT
    h.id,
    h.hbl_no,
    h.goods_description,
    h.packages,
    h.gross_weight_kg,
    h.cbm,
    h.hs_code,
    h.cfs,

    h.released_party_id,
    rp.name    AS released_party_name,
    rp.address AS released_party_address,

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

    sl.name AS shipper_name,

    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,
    c3.name AS notify_name,    c3.address AS notify_address

  FROM house_bls h
  JOIN master_bls m ON m.id = h.master_bl_id
  LEFT JOIN shipping_lines sl ON sl.id = m.shipping_line_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 = h.consignee_customer_id
  JOIN customers c2 ON c2.id = h.billing_party_customer_id
  LEFT JOIN customers c3 ON c3.id = h.notify_party_customer_id
  LEFT JOIN released_parties rp ON rp.id = h.released_party_id
  WHERE h.id = ?
");
$stmt->execute([$houseId]);
$h = $stmt->fetch();

if (!$h) {
  echo "<div style='padding:16px;font-family:Arial'>HBL not found.</div>";
  return;
}

/**
 * Document values (dd/mm/yyyy)
 */
$doDate      = date('d/m/Y');
$validUntil  = date('d/m/Y', strtotime('+90 days'));

$deliveryOrderNo = 'WSC-DO-' . str_pad((string)$houseId, 5, '0', STR_PAD_LEFT);
$releaseId = releasingId12();

$vesselVoy = trim((string)($h['vessel_name'] ?? ''));
$voyage    = trim((string)($h['voyage_no'] ?? ''));
if ($voyage !== '') $vesselVoy = trim($vesselVoy . ' ' . $voyage);

$containerNo = trim((string)($h['container_no'] ?? ''));
$sealNo      = trim((string)($h['seal_no'] ?? ''));
$polName     = (string)($h['pol_name'] ?? '');
$podName     = (string)($h['pod_name'] ?? '');
$mblNo       = (string)($h['mbl_no'] ?? '');
$hblNo       = (string)($h['hbl_no'] ?? '');
$eta         = dmy($h['eta_date'] ?? null);

$hsCode      = (string)($h['hs_code'] ?? '');
$cfs         = (string)($h['cfs'] ?? '');

$desc        = (string)($h['goods_description'] ?? '');
$packages    = (string)($h['packages'] ?? '');
$weightKg    = (float)($h['gross_weight_kg'] ?? 0);
$cbm         = (float)($h['cbm'] ?? 0);

$consName = (string)($h['consignee_name'] ?? '');
$consAddr = (string)($h['consignee_address'] ?? '');
$notName  = (string)($h['notify_name'] ?? '');
$notAddr  = (string)($h['notify_address'] ?? '');

$rpName = trim((string)($h['released_party_name'] ?? ''));
$rpAddr = trim((string)($h['released_party_address'] ?? ''));

$toName = ($cfs !== '' ? $cfs : $consName);
$toAddr = '';

$finalDest = $podName !== '' ? $podName : '—';

$pdfUrl = $basePath . '/doc/delivery-order/download?house_bl_id=' . (int)$houseId;

/**
 * Render sheet twice (Agent + CBL). Print button ONLY on first sheet.
 */
function renderDeliveryOrderSheet(array $ctx): void {
  extract($ctx);
  ?>
  <div class="doc-sheet">

    <?php if (!empty($showPrint)): ?>
      <div class="doc-actions">
        <a class="btn" href="<?= h($pdfUrl) ?>">Download PDF</a>
        <button class="btn" onclick="window.print()">Print</button>
      </div>
    <?php endif; ?>

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

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

    <div class="doc-title"><?= h($title) ?></div>

    <div class="topgrid">
      <div>
        <div class="kv"><span class="k">DELIVERY ORDER NO:</span> <?= h($deliveryOrderNo) ?></div>
        <div class="kv"><span class="k">DATE:</span> <?= h($doDate) ?></div>
        <div class="kv"><span class="k">VALID UNTIL:</span> <?= h($validUntil) ?></div>

        <div style="height:10px"></div>

        <div class="kv"><span class="k">RELEASED PARTY/CUSTOMS CLEARING AGENT</span></div>
        <div class="kv">
          <span class="uline"><?= h($rpName !== '' ? $rpName : '—') ?></span><br>
          <?= $rpAddr !== '' ? nl2br(h($rpAddr)) : '—' ?>
        </div>
      </div>

      <div class="box">
        <div style="font-weight:800;text-transform:uppercase;margin-bottom:6px;">TO:</div>
        <div style="font-weight:700;"><?= h($toName) ?></div>
        <?php if (trim($toAddr) !== ''): ?>
          <div><?= nl2br(h($toAddr)) ?></div>
        <?php endif; ?>
      </div>

      <div></div>

      <div>
        <div class="kv" style="margin-top:6px;">
          <span class="k">AC CONSIGNEE:</span><br>
          <span class="uline"><?= h($consName) ?></span><br>
          <?= nl2br(h($consAddr)) ?>
        </div>

        <div class="kv" style="margin-top:10px;">
          <span class="k">NOTIFY PARTY:</span><br>
          <span class="uline"><?= h($notName !== '' ? $notName : '—') ?></span><br>
          <?= $notAddr !== '' ? nl2br(h($notAddr)) : '—' ?>
        </div>
      </div>
    </div>

    <table class="tbl">
      <tr>
        <td class="k">VESSEL/VOYAGE</td><td><?= h($vesselVoy) ?></td>
        <td class="k">CONTAINER NO</td><td><?= h($containerNo !== '' ? $containerNo : '—') ?></td>
      </tr>
      <tr>
        <td class="k">PORT OF LOADING</td><td><?= h($polName) ?></td>
        <td class="k">SEAL NO</td><td><?= h($sealNo !== '' ? $sealNo : '—') ?></td>
      </tr>
      <tr>
        <td class="k">PORT OF DISCHARGE</td><td><?= h($podName) ?></td>
        <td class="k">MBL</td><td><?= h($mblNo) ?></td>
      </tr>
      <tr>
        <td class="k">ETA</td><td><?= h($eta) ?></td>
        <td class="k">HBL</td><td><?= h($hblNo) ?></td>
      </tr>
      <tr>
        <td class="k">LOCATION OF CLEARANCE</td>
        <td colspan="3"><?= h($cfs !== '' ? $cfs : '—') ?></td>
      </tr>
      <tr>
        <td class="k">MARKS &amp; NUMBERS</td>
        <td colspan="3"><?= h($desc !== '' ? $desc : '—') ?></td>
      </tr>
      <tr>
        <td class="k">DESCRIPTION OF GOODS</td>
        <td colspan="3">
          <?= h($desc !== '' ? $desc : '—') ?>
          <?php if ($hsCode !== ''): ?>
            <div style="margin-top:4px;"><strong>H.S:</strong> <?= h($hsCode) ?></div>
          <?php endif; ?>
        </td>
      </tr>
      <tr>
        <td class="k">PACKAGING</td><td colspan="3"><?= h($packages !== '' ? $packages : '—') ?></td>
      </tr>
      <tr>
        <td class="k">WEIGHT (KGS)</td><td colspan="3"><?= h(n2($weightKg)) ?> KGS</td>
      </tr>
      <tr>
        <td class="k">CBM (M3)</td><td colspan="3"><?= h(n3($cbm)) ?> CBM</td>
      </tr>
      <tr>
        <td class="k">FINAL DESTINATION</td><td colspan="3"><?= h($finalDest) ?></td>
      </tr>
    </table>

    <div class="footer">
      <div class="footer-date"><strong>DATE:</strong> <?= h($doDate) ?></div>

      <div class="footer-row2">
        <div class="left"><strong>RELEASING ID: <?= h($releaseId) ?></strong></div>
        <div class="right"><strong>AS AGENTS OF WSC LOGISTICS LTD.</strong></div>
      </div>

      <div class="footer-spacer"></div>

      <div class="footer-note">
        This Delivery Order is subject to all the conditions and expectations of the relative Bill of Lading subject to payment of landing charges prior delivery.
      </div>
    </div>

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

  </div>
  <?php
}

$common = [
  'basePath'         => $basePath,
  'pdfUrl'           => $pdfUrl,
  'deliveryOrderNo'  => $deliveryOrderNo,
  'doDate'           => $doDate,
  'validUntil'       => $validUntil,
  'rpName'           => $rpName,
  'rpAddr'           => $rpAddr,
  'toName'           => $toName,
  'toAddr'           => $toAddr,
  'consName'         => $consName,
  'consAddr'         => $consAddr,
  'notName'          => $notName,
  'notAddr'          => $notAddr,
  'vesselVoy'        => $vesselVoy,
  'containerNo'      => $containerNo,
  'sealNo'           => $sealNo,
  'polName'          => $polName,
  'podName'          => $podName,
  'mblNo'            => $mblNo,
  'hblNo'            => $hblNo,
  'eta'              => $eta,
  'cfs'              => $cfs,
  'desc'             => $desc,
  'hsCode'           => $hsCode,
  'packages'         => $packages,
  'weightKg'         => $weightKg,
  'cbm'              => $cbm,
  'finalDest'        => $finalDest,
  'releaseId'        => $releaseId,
  'servedBy'         => $servedBy,
];
?>
<style>
  body .max-w-7xl > .glass-strong > .flex.items-center.justify-between{
    display:none !important;
  }

  body .max-w-7xl{
    max-width:none !important;
    margin:0 !important;
    padding:0 !important;
  }

  body .max-w-7xl > .glass-strong{
    border:0 !important;
    box-shadow:none !important;
    border-radius:0 !important;
    background:#fff !important;
  }

  body .max-w-7xl > .glass-strong > .px-6.py-6{
    padding:0 !important;
  }

  header,
  nav,
  .app-header,
  .app-navbar,
  .topbar,
  .user-menu,
  #userMenuBtn,
  #userMenu{
    display:none !important;
  }

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

  body{
    margin-top:0 !important;
  }

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

  .doc-sheet{
    background:#fff;
    color:#000;
    font-family:Arial, Helvetica, sans-serif;
    max-width:900px;
    width:900px;
    margin:16px 0 16px 1cm;
    border:3px solid #f97316;
    padding:18px;
    box-sizing:border-box;
    min-height:297mm;
    position:relative;
    page-break-inside:avoid;
    break-inside:avoid;
    overflow:visible;
  }

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

  .doc-banner{
    display:flex;
    justify-content:flex-start;
    margin-bottom:8px;
  }

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

  .doc-divider{
    height:0;
    border-top:3px solid #f97316;
    margin:8px -18px 14px -18px;
    width:auto;
  }

  .doc-title{
    margin:0 0 12px 0;
    font-weight:800;
    letter-spacing:.5px;
    color:#f59e0b;
    font-size:24px;
    text-transform:uppercase;
  }

  .topgrid{
    display:grid;
    grid-template-columns:1.2fr 1fr;
    gap:18px;
    margin:6px 0 12px;
    font-size:13px;
  }

  .box{
    border:1px solid #e5e7eb;
    padding:10px;
    background:#fff7ed;
    font-size:13px;
    line-height:1.35;
  }

  .kv{
    margin:2px 0;
    font-size:13px;
  }

  .kv .k{
    font-weight:800;
    text-transform:uppercase;
  }

  .uline{
    text-decoration:underline;
    font-weight:700;
  }

  table.tbl{
    width:100%;
    border-collapse:collapse;
    margin:12px 0 10px;
    font-size:13px;
  }

  .tbl td{
    border:2px solid #1f2937;
    padding:6px 8px;
    vertical-align:top;
  }

  .tbl td.k{
    width:190px;
    font-weight:800;
    text-transform:uppercase;
    color:#b45309;
    background:#fff7ed;
    white-space:nowrap;
  }

  .footer{
    margin-top:22px;
    font-size:12px;
  }

  .footer-date{
    margin-bottom:8px;
  }

  .footer-row2{
    display:flex;
    justify-content:space-between;
    align-items:baseline;
    gap:14px;
  }

  .footer-row2 .left,
  .footer-row2 .right{
    font-weight:800;
    text-transform:uppercase;
  }

  .footer-spacer{
    height:28px;
  }

  .footer-note{
    font-size:11px;
    color:#374151;
  }

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

  .page-break{
    height:0;
  }

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

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

  body .max-w-7xl > .glass-strong > .flex.items-center.justify-between,
  header,
  nav,
  .app-header,
  .app-navbar,
  .topbar,
  .user-menu,
  #userMenuBtn,
  #userMenu{
    display:none !important;
  }

  body .max-w-7xl{
    max-width:none !important;
    margin:0 !important;
    padding:0 !important;
  }

  body .max-w-7xl > .glass-strong{
    border:0 !important;
    box-shadow:none !important;
    border-radius:0 !important;
    background:#fff !important;
  }

  body .max-w-7xl > .glass-strong > .px-6.py-6{
    padding:0 !important;
  }

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

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

  .doc-wrap{
    position:static !important;
    overflow:visible !important;
    background:#fff !important;
    margin:0 !important;
    padding:0 !important;
  }

  .doc-sheet{
    margin:0 !important;
    width:auto !important;
    max-width:none !important;
    padding:12px !important;
    border:3px solid #f97316 !important;
    min-height:255mm !important;
    box-sizing:border-box !important;
    page-break-inside:avoid !important;
    break-inside:avoid !important;
    background:#fff !important;
    overflow:visible !important;
  }

  .doc-divider{
    display:block !important;
    height:0 !important;
    border-top:3px solid #f97316 !important;
    margin:8px -12px 14px -12px !important;
    width:auto !important;
  }

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

  .page-break{
    display:block !important;
    page-break-before:always !important;
    break-before:page !important;
    height:0 !important;
  }
}
</style>

<div class="doc-wrap">

  <?php
    renderDeliveryOrderSheet($common + [
      'title'     => 'DELIVERY ORDER - AGENT',
      'showPrint' => true,
    ]);
  ?>

  <div class="page-break"></div>

  <?php
    renderDeliveryOrderSheet($common + [
      'title'     => 'DELIVERY ORDER - CBL',
      'showPrint' => false,
    ]);
  ?>

</div>