<?php
declare(strict_types=1);

use Dompdf\Dompdf;
use Dompdf\Options;

require_once __DIR__ . '/../../../vendor/autoload.php';

global $db, $config, $auth;

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

if (!function_exists('h')) {
  function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
  }
}
if (!function_exists('n2')) {
  function n2($v): string {
    return number_format((float)$v, 2);
  }
}
if (!function_exists('n3')) {
  function n3($v): string {
    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; }
  }
}
if (!function_exists('releasingId12')) {
  function releasingId12(): string {
    $chars = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
    shuffle($chars);
    return implode('', array_slice($chars, 0, 12));
  }
}
if (!function_exists('normalize_spaces_do')) {
  function normalize_spaces_do(string $value): string {
    return preg_replace('/\s+/u', ' ', trim($value)) ?? '';
  }
}
if (!function_exists('first_two_names_do')) {
  function first_two_names_do(string $fullName): string {
    $fullName = normalize_spaces_do($fullName);
    if ($fullName === '') return 'UNKNOWN';
    $parts = preg_split('/\s+/u', $fullName) ?: [];
    if (count($parts) > 2) $parts = array_slice($parts, 0, 2);
    return implode(' ', $parts);
  }
}
if (!function_exists('safe_filename_part_do')) {
  function safe_filename_part_do(string $value): string {
    $value = normalize_spaces_do($value);
    $value = preg_replace('/[\\\\\/:*?"<>|]+/u', '', $value) ?? '';
    $value = preg_replace('/\s+/u', ' ', $value) ?? '';
    $value = trim($value, " .-\t\n\r\0\x0B");
    return $value !== '' ? strtoupper($value) : 'NA';
  }
}

/**
 * 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(PDO::FETCH_ASSOC);
    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(PDO::FETCH_ASSOC);

if (!$h) {
  http_response_code(404);
  exit('HBL not found.');
}

$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 : '—';

$consigneeForFile = safe_filename_part_do(first_two_names_do($consName));
$blNumberForFile  = safe_filename_part_do($hblNo !== '' ? $hblNo : ($mblNo !== '' ? $mblNo : 'NA'));
$vesselVoyForFile = safe_filename_part_do(trim(((string)($h['vessel_name'] ?? '')) . ' ' . ((string)($h['voyage_no'] ?? ''))));
$filename = 'DO-' . $consigneeForFile . '-' . $blNumberForFile . '-' . $vesselVoyForFile . '-DELIVERY ORDER.pdf';

$bannerFsPath = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/\\') . $basePath . '/assets/wcs-banner.png';
$bannerDataUri = '';
if (is_file($bannerFsPath)) {
  $imgData = @file_get_contents($bannerFsPath);
  if ($imgData !== false) {
    $mime = function_exists('mime_content_type') ? mime_content_type($bannerFsPath) : 'image/png';
    $bannerDataUri = 'data:' . $mime . ';base64,' . base64_encode($imgData);
  }
}

function renderDeliveryOrderPdfSheet(array $ctx): void {
  extract($ctx);
  ?>
  <div class="doc-sheet">
    <div class="doc-banner">
      <?php if ($bannerDataUri !== ''): ?>
        <img class="banner" src="<?= $bannerDataUri ?>" alt="WSC Banner" />
      <?php endif; ?>
    </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
}

ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?= h($deliveryOrderNo) ?></title>
<style>
  @page { size:A4; margin:6mm 10mm 8mm 10mm; }

  body{
    background:#fff;
    color:#000;
    font-family:Arial, Helvetica, sans-serif;
    margin:0;
    padding:0;
  }

  .doc-sheet{
    background:#fff;
    color:#000;
    font-family:Arial, Helvetica, sans-serif;
    border:3px solid #f97316;
    padding:12px;
    box-sizing:border-box;
    min-height:255mm;
    page-break-inside:avoid;
    break-inside:avoid;
    overflow:visible;
  }

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

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

  .doc-divider{
    height:0;
    border-top:3px solid #f97316;
    margin:8px -12px 14px -12px;
    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{
    display:block;
    page-break-before:always;
    break-before:page;
    height:0;
  }
</style>
</head>
<body>

<?php
renderDeliveryOrderPdfSheet([
  'bannerDataUri'     => $bannerDataUri,
  'title'             => 'DELIVERY ORDER - AGENT',
  '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,
]);
?>

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

<?php
renderDeliveryOrderPdfSheet([
  'bannerDataUri'     => $bannerDataUri,
  'title'             => 'DELIVERY ORDER - CBL',
  '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,
]);
?>

</body>
</html>
<?php
$html = ob_get_clean();

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$options->set('defaultFont', 'Arial');

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . str_replace('"', '', $filename) . '"');
echo $dompdf->output();
exit;