<?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);
$paymentId  = (int)($_GET['payment_id'] ?? 0);

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

if (!function_exists('h')) {
  function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
  }
}

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($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;
  }
}

if (!function_exists('normalize_spaces_receipt')) {
  function normalize_spaces_receipt(string $value): string {
    return preg_replace('/\s+/u', ' ', trim($value)) ?? '';
  }
}

if (!function_exists('first_two_names_receipt')) {
  function first_two_names_receipt(string $fullName): string {
    $fullName = normalize_spaces_receipt($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_receipt')) {
  function safe_filename_part_receipt(string $value): string {
    $value = normalize_spaces_receipt($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';
  }
}

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

if (!$row || empty($row['payment_id'])) {
  http_response_code(404);
  exit('Payment not found for this HBL.');
}

$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 (same logic as UI page)
 */
$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);

$consigneeForFile = safe_filename_part_receipt(first_two_names_receipt($consignee));
$blNumberForFile  = safe_filename_part_receipt($hblNo !== '' ? $hblNo : ($mblNo !== '' ? $mblNo : 'NA'));
$vesselVoyForFile = safe_filename_part_receipt(trim($vesselName . ' ' . $voyageNo));
$filename = 'RCPT-' . $consigneeForFile . '-' . $blNumberForFile . '-' . $vesselVoyForFile . '-RECEIPT.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);
  }
}

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

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

  .doc-sheet {
    background: #fff;
    border: 3px solid #f97316;
    padding: 12px 12px 0 12px;
    box-sizing: border-box;
    min-height: 255mm;
  }

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

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

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

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

  .meta {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
    font-size: 14px;
    margin: 0 0 10px 0;
  }

  .meta td {
    vertical-align: top;
  }

  .meta .right {
    text-align: right;
  }

  .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,
  .fx-box .line {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
  }

  .amount-box .label,
  .fx-box .label {
    display: inline-block;
    width: 230px;
    font-weight: 800;
    text-transform: uppercase;
    vertical-align: top;
  }

  .amount-box .val,
  .fx-box .val {
    display: inline-block;
    width: calc(100% - 235px);
    vertical-align: top;
  }

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

  .sig {
    margin-top: 26px;
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
    font-size: 14px;
  }

  .sig td {
    width: 48%;
    vertical-align: top;
  }

  .sig .right {
    text-align: right;
  }

  .rule {
    border-bottom: 1px solid #111;
    height: 18px;
    margin-bottom: 6px;
  }
  
  .served-by {
  margin-top: 28px;
  padding-top: 8px;
  border-top: 1px dashed #d1d5db;
  font-size: 11px;
  color: #6b7280;
  text-align: right;
}

</style>
</head>
<body>
  <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">PAYMENT RECEIPT</div>

    <table class="meta">
      <tr>
        <td><span class="b">Receipt No:</span> <?= h($receiptNo) ?></td>
        <td class="right"><span class="b">Date:</span> <?= h($receiptDate) ?></td>
      </tr>
    </table>

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

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

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

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

        <div class="line" style="margin-top:6px;">
          <span class="label">FX RATE</span>
          <span class="val">1 USD = KES <?= h(number_format($fxRate, 6)) ?></span>
        </div>
      </div>
    <?php endif; ?>

    <table class="sig">
      <tr>
        <td>
          <div class="rule"></div>
          <div><strong>Prepared By</strong></div>
        </td>
        <td class="right">
          <div class="rule"></div>
          <div><strong>For and on behalf of WSC LOGISTICS KENYA LIMITED</strong></div>
        </td>
      </tr>
    </table>

    <div class="served-by">
      Served by: <?= h((string)($servedBy !== '' ? $servedBy : '—')) ?>
    </div>
  </div>
</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;