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

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

/**
 * Helpers.
 */
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('money2')) {
  function money2($v): string {
    return number_format((float)$v, 2);
  }
}

/**
 * Number to words
 */
if (!function_exists('numberToWords')) {
  function numberToWords(int $num): string {
    if ($num === 0) return 'Zero';
    if ($num < 0) return 'Minus ' . numberToWords(abs($num));

    $ones = [
      '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
      'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'
    ];
    $tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];

    $out = [];

    $scales = [
      1000000000 => 'Billion',
      1000000    => 'Million',
      1000       => 'Thousand',
    ];

    foreach ($scales as $div => $label) {
      if ($num >= $div) {
        $q = (int) floor($num / $div);
        $num = $num % $div;
        $out[] = trim(numberToWords($q)) . ' ' . $label;
      }
    }

    if ($num >= 100) {
      $h = (int) floor($num / 100);
      $num = $num % 100;
      $out[] = $ones[$h] . ' Hundred';
    }

    if ($num >= 20) {
      $t = (int) floor($num / 10);
      $u = $num % 10;
      $out[] = $tens[$t] . ($u ? (' ' . $ones[$u]) : '');
    } elseif ($num > 0) {
      $out[] = $ones[$num];
    }

    return preg_replace('/\s+/', ' ', trim(implode(' ', array_filter($out))));
  }
}

if (!function_exists('amountToWordsByCurrency')) {
  function amountToWordsByCurrency(float $amount, string $currency): string {
    $amount = round($amount, 2);
    $whole  = (int) floor($amount);
    $cents  = (int) round(($amount - $whole) * 100);

    $words = trim(numberToWords($whole));
    if ($words === '') $words = 'Zero';

    $currency = strtoupper(trim((string)$currency));

    if ($currency === 'KES') {
      $prefix = 'Kenya Shillings ';
      $suffix = ' Only';
      if ($cents > 0) {
        $suffix = ' and ' . numberToWords($cents) . ' Cents Only';
      }
      return $prefix . $words . $suffix;
    }

    $prefix = 'US Dollars ';
    $suffix = ' Only';
    if ($cents > 0) {
      $suffix = ' and ' . numberToWords($cents) . ' Cents Only';
    }
    return $prefix . $words . $suffix;
  }
}

/**
 * Fetch payment + invoice + parties + shipment details
 */
if ($paymentId > 0) {
  $stmt = $db->prepare("
    SELECT
      h.id AS house_id,
      h.hbl_no,

      m.mbl_no,
      m.vessel_name,
      m.voyage_no,

      c1.name AS consignee_name,
      c2.name AS billing_name,

      i.id AS invoice_id,
      i.invoice_no,

      p.id AS payment_id,
      p.receipt_no,
      p.pay_date,
      p.method,
      p.currency,
      p.fx_rate,
      p.ref_no,
      p.amount_ccy,
      p.amount_usd

    FROM payments p
    JOIN invoices i    ON i.id = p.invoice_id
    JOIN house_bls h   ON h.id = i.house_bl_id
    JOIN master_bls m  ON m.id = h.master_bl_id
    JOIN customers c1  ON c1.id = h.consignee_customer_id
    JOIN customers c2  ON c2.id = h.billing_party_customer_id
    WHERE p.id = ?
    LIMIT 1
  ");
  $stmt->execute([$paymentId]);
  $row = $stmt->fetch();
} else {
  $stmt = $db->prepare("
    SELECT
      h.id AS house_id,
      h.hbl_no,

      m.mbl_no,
      m.vessel_name,
      m.voyage_no,

      c1.name AS consignee_name,
      c2.name AS billing_name,

      i.id AS invoice_id,
      i.invoice_no,

      p.id AS payment_id,
      p.receipt_no,
      p.pay_date,
      p.method,
      p.currency,
      p.fx_rate,
      p.ref_no,
      p.amount_ccy,
      p.amount_usd

    FROM house_bls h
    JOIN master_bls m ON m.id = h.master_bl_id
    JOIN customers c1 ON c1.id = h.consignee_customer_id
    JOIN customers c2 ON c2.id = h.billing_party_customer_id
    JOIN invoices i   ON i.house_bl_id = h.id
    JOIN payments p   ON p.invoice_id = i.id
    WHERE h.id = ?
    ORDER BY p.id DESC
    LIMIT 1
  ");
  $stmt->execute([$houseId]);
  $row = $stmt->fetch();
}

if (!$row || empty($row['payment_id'])) {
  echo "<div class='doc-wrap'><div class='doc-sheet'>Payment not found for this HBL.</div></div>";
  return;
}

$receiptNo     = trim((string)($row['receipt_no'] ?? ''));
if ($receiptNo === '') $receiptNo = '—';

$receiptDate   = dmy($row['pay_date'] ?? null);
$consignee     = trim((string)($row['consignee_name'] ?? ''));
$billing       = trim((string)($row['billing_name'] ?? ''));
$hblNo         = trim((string)($row['hbl_no'] ?? ''));
$mblNo         = trim((string)($row['mbl_no'] ?? ''));
$vesselName    = trim((string)($row['vessel_name'] ?? ''));
$voyageNo      = trim((string)($row['voyage_no'] ?? ''));
$method        = trim((string)($row['method'] ?? ''));
$currency      = strtoupper(trim((string)($row['currency'] ?? 'USD')));
$refNo         = trim((string)($row['ref_no'] ?? ''));
$amountCcy     = (float)($row['amount_ccy'] ?? 0);
$amountUsd     = (float)($row['amount_usd'] ?? 0);
$fxRate        = (float)($row['fx_rate'] ?? 0);
$invNo         = trim((string)($row['invoice_no'] ?? ''));
$invId         = (int)($row['invoice_id'] ?? 0);
$being         = $invNo !== '' ? ('Invoice ' . $invNo) : ($invId ? ('Invoice #' . $invId) : '—');
$amtWords      = amountToWordsByCurrency($amountCcy, $currency);
$showFxBlock   = ($currency === 'KES' && $fxRate > 0);
$currencyLabel = $currency === 'KES' ? 'KES' : 'USD';

/**
 * Served-by source:
 * 1. Auth class current user()
 * 2. direct fallback via session uid -> users.full_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);
$pdfUrl = $basePath . '/receipt/download?payment_id=' . (int)$row['payment_id'];
?>

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

body > .relative.min-h-screen > .relative.z-10.min-h-screen > .desktop-shell,
body > .relative.min-h-screen > .page-pad > .app-shell {
  display: block !important;
}

body > .relative.min-h-screen > .relative.z-10.min-h-screen > .desktop-shell > aside,
body > .relative.min-h-screen > .page-pad > .app-shell > aside {
  display: none !important;
}

body > .relative.min-h-screen > .relative.z-10.min-h-screen > .desktop-shell > div > header,
body > .relative.min-h-screen > .page-pad > .app-shell > div > header {
  display: none !important;
}

body > .relative.min-h-screen > .relative.z-10.min-h-screen > .desktop-shell > div > .mb-4,
body > .relative.min-h-screen > .page-pad > .app-shell > div > .mb-4 {
  display: none !important;
}

body > .relative.min-h-screen > .relative.z-10.min-h-screen > .desktop-shell > div,
body > .relative.min-h-screen > .page-pad > .app-shell > div {
  width: 100% !important;
  max-width: none !important;
  overflow: visible !important;
}

body > .relative.min-h-screen > .relative.z-10.min-h-screen > .desktop-shell > div > main,
body > .relative.min-h-screen > .page-pad > .app-shell > div > main {
  overflow: visible !important;
  min-width: 0 !important;
}

body > .relative.min-h-screen > .relative.z-10.min-h-screen,
body > .relative.min-h-screen > .page-pad {
  padding: 0 !important;
}

body > .relative.min-h-screen .bg-grid,
body > .relative.min-h-screen .orb {
  display: none !important;
}

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

.doc-sheet {
  max-width: 900px;
  width: calc(100% - 48px);
  margin: 0 auto;
  background: #fff;
  border: 3px solid #f97316;
  padding: 18px;
  box-sizing: border-box;
  min-height: 297mm;
  position: relative;
  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;
}

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

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

.meta {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  font-size: 14px;
  margin: 0 0 10px 0;
}

.meta .b {
  font-weight: 800;
  text-transform: uppercase;
}

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

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

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

.amount-box {
  margin-top: 18px;
  font-size: 14px;
  line-height: 1.5;
}

.amount-box .line {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.amount-box .label {
  width: 230px;
  font-weight: 800;
  text-transform: uppercase;
}

.amount-box .val {
  flex: 1;
}

.fx-box {
  margin-top: 14px;
  font-size: 13px;
}

.fx-box .line {
  display: flex;
  gap: 10px;
  align-items: flex-start;
  margin-top: 6px;
}

.fx-box .label {
  width: 230px;
  font-weight: 800;
  text-transform: uppercase;
}

.fx-box .val {
  flex: 1;
}

.sig {
  margin-top: 26px;
  display: flex;
  justify-content: space-between;
  gap: 20px;
  font-size: 14px;
}

.sig .block {
  width: 48%;
}

.sig .rule {
  border-bottom: 1px solid #111;
  height: 18px;
  margin-bottom: 6px;
}

.served-by {
  margin-top: 28px;
  padding-top: 8px;
  border-top: 1px dashed #d1d5db; /* lighter grey */
  font-size: 11px;
  color: #6b7280;                /* muted grey */
  text-align: right;
}

.served-by .label {
  font-weight: 400;
}

.served-by .name {
  font-weight: 500;              /* slight emphasis, not bold */
  letter-spacing: .3px;
}

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

  .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 {
    padding: 0 !important;
    background: #fff !important;
  }

  .doc-sheet {
    width: auto !important;
    max-width: none !important;
    margin: 0 !important;
    padding: 12px 12px 0 12px;
    min-height: 255mm;
    box-shadow: none !important;
  }

  .doc-divider {
    margin-left: -12px;
    margin-right: -12px;
  }

  .banner {
    max-height: 60px;
    object-fit: contain;
  }
}
</style>

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

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

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

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

    <div class="doc-title">PAYMENT RECEIPT</div>

    <div class="meta">
      <div><span class="b">Receipt No:</span> <?= h((string)$receiptNo) ?></div>
      <div><span class="b">Date:</span> <?= h((string)$receiptDate) ?></div>
    </div>

    <table class="tbl">
      <tr><td class="k">RECEIVED FROM</td><td><?= h((string)($consignee !== '' ? $consignee : '—')) ?></td></tr>
      <tr><td class="k">A/C</td><td><?= h((string)($billing !== '' ? $billing : '—')) ?></td></tr>
      <tr><td class="k">HBL NO.</td><td><?= h((string)($hblNo !== '' ? $hblNo : '—')) ?></td></tr>
      <tr><td class="k">PAYMENT MODE</td><td><?= h((string)($method !== '' ? $method : '—')) ?></td></tr>
      <tr><td class="k">CURRENCY</td><td><?= h((string)$currencyLabel) ?></td></tr>
      <tr><td class="k">REFERENCE</td><td><?= h((string)($refNo !== '' ? $refNo : '—')) ?></td></tr>
      <tr><td class="k">BEING PAYMENT FOR</td><td><?= h((string)$being) ?></td></tr>
    </table>

    <div class="amount-box">
      <div class="line">
        <div class="label">AMOUNT IN WORDS</div>
        <div class="val"><?= h((string)$amtWords) ?></div>
      </div>

      <div class="line" style="margin-top:8px;">
        <div class="label">AMOUNT</div>
        <div class="val"><strong><?= h((string)$currencyLabel) ?> <?= h((string)money2($amountCcy)) ?></strong></div>
      </div>
    </div>

    <?php if ($showFxBlock): ?>
      <div class="fx-box">
        <div class="line">
          <div class="label">USD EQUIVALENT</div>
          <div class="val">USD <?= h((string)money2($amountUsd)) ?></div>
        </div>

        <div class="line">
          <div class="label">FX RATE</div>
          <div class="val">1 USD = KES <?= h((string)number_format($fxRate, 6)) ?></div>
        </div>
      </div>
    <?php endif; ?>

    <div class="sig">
      <div class="block">
        <div class="rule"></div>
        <div><strong>Prepared By</strong></div>
      </div>

      <div class="block" style="text-align:right;">
        <div class="rule"></div>
        <div><strong>For and on behalf of WSC LOGISTICS KENYA LIMITED</strong></div>
      </div>
    </div>

    <div class="served-by">
      <span class="label">You were served by:</span>
      <span class="name"><?= h((string)($servedBy !== '' ? $servedBy : '—')) ?></span>
    </div>

  </div>
</div>