<?php
global $db, $config;

$id = (int)($_GET['master_bl_id'] ?? $_GET['id'] ?? 0);
if ($id <= 0) {
  echo '<div class="rounded-2xl border border-red-200 bg-red-50 text-red-700 px-4 py-3">Missing shipment id.</div>';
  return;
}

$st = $db->prepare("
  SELECT
    m.*,
    sl.name AS shipping_line_name,
    pol.name AS pol_name,
    pod.name AS pod_name
  FROM master_bls m
  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
  WHERE m.id = ?
  LIMIT 1
");
$st->execute([$id]);
$m = $st->fetch();

if (!$m) {
  echo '<div class="rounded-2xl border border-red-200 bg-red-50 text-red-700 px-4 py-3">Shipment not found.</div>';
  return;
}

/*
 |------------------------------------------------------------
 | KPI block
 |------------------------------------------------------------
 */
$kpi = $db->prepare("
  SELECT
    COUNT(*) AS total_hbls,
    SUM(CASE WHEN NOT EXISTS (
      SELECT 1 FROM invoices i WHERE i.house_bl_id = h.id
    ) THEN 1 ELSE 0 END) AS uninvoiced_count,
    SUM(CASE WHEN EXISTS (
      SELECT 1 FROM invoices i WHERE i.house_bl_id = h.id AND i.status IN ('ISSUED','PART_PAID')
    ) THEN 1 ELSE 0 END) AS open_financial_count,
    SUM(CASE WHEN UPPER(COALESCE(h.status,'')) = 'READY_FOR_DO' THEN 1 ELSE 0 END) AS ready_do_count,
    SUM(CASE WHEN UPPER(COALESCE(h.status,'')) = 'RELEASED' THEN 1 ELSE 0 END) AS released_count
  FROM house_bls h
  WHERE h.master_bl_id = ?
");
$kpi->execute([$id]);
$k = $kpi->fetch() ?: [
  'total_hbls' => 0,
  'uninvoiced_count' => 0,
  'open_financial_count' => 0,
  'ready_do_count' => 0,
  'released_count' => 0,
];

/*
 |------------------------------------------------------------
 | Child HBL grid (latest invoice only)
 |------------------------------------------------------------
 */
$hbl = $db->prepare("
  SELECT
    h.*,
    c1.name AS consignee_name,
    c2.name AS billing_name,
    i.id AS invoice_id,
    i.invoice_no,
    i.status AS invoice_status
  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
  LEFT JOIN invoices i ON i.id = (
    SELECT ii.id
    FROM invoices ii
    WHERE ii.house_bl_id = h.id
    ORDER BY ii.id DESC
    LIMIT 1
  )
  WHERE h.master_bl_id = ?
  ORDER BY h.id DESC
");
$hbl->execute([$id]);
$children = $hbl->fetchAll();

$tab = trim((string)($_GET['tab'] ?? 'hbls'));
if (!in_array($tab, ['overview','hbls','manifest','financials'], true)) {
  $tab = 'hbls';
}
?>

<style>
  .child-row{
    cursor:pointer;
    transition:background .16s ease;
  }
  .child-row:hover{
    background:#fff7ed;
  }
</style>

<div class="space-y-6">
  <div class="flex flex-col xl:flex-row xl:items-start xl:justify-between gap-4">
    <div>
      <div class="text-sm font-bold uppercase tracking-[0.2em] text-orange-600">Manifest Workspace</div>
      <h1 class="text-3xl font-extrabold text-ink-900"><?= h($m['mbl_no']) ?></h1>
      <div class="text-sm text-ink-500 mt-1">
        <?= h($m['vessel_name'] ?: '—') ?> / <?= h($m['voyage_no'] ?: '—') ?>
        · <?= h($m['pol_name'] ?: '—') ?> → <?= h($m['pod_name'] ?: '—') ?>
      </div>
    </div>

    <div class="flex flex-wrap gap-2">
      <a href="<?= h(to('/shipments')) ?>"
         data-nav
         class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold">
        Back to Manifests
      </a>

      <a href="<?= h(to('/mbl/edit?id=' . (int)$m['id'])) ?>"
         data-nav
         class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold">
        Edit Manifest
      </a>

      <a href="<?= h(to('/hbl/new?master_bl_id=' . (int)$m['id'])) ?>"
         data-nav
         class="px-4 py-3 rounded-2xl btn-primary">
        New HBL
      </a>

      <a href="<?= h(to('/doc/manifest?master_bl_id=' . (int)$m['id'])) ?>"
         target="_blank"
         class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold">
        Print Manifest
      </a>
    </div>
  </div>

  <div class="glass rounded-3xl p-5">
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
      <div>
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Shipping Line</div>
        <div class="mt-1 font-bold text-ink-900"><?= h($m['shipping_line_name'] ?: '—') ?></div>
      </div>

      <div>
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Container</div>
        <div class="mt-1 font-bold text-ink-900"><?= h($m['container_no'] ?: '—') ?></div>
        <div class="text-xs text-ink-500"><?= h($m['container_type'] ?: '—') ?></div>
      </div>

      <div>
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Seal No</div>
        <div class="mt-1 font-bold text-ink-900"><?= h($m['seal_no'] ?: '—') ?></div>
      </div>

      <div>
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">ETA</div>
        <div class="mt-1 font-bold text-ink-900"><?= h($m['eta_date'] ?: '—') ?></div>
      </div>
    </div>

    <div class="mt-5 flex flex-wrap gap-3">
      <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
        Status: <?= h($m['status'] ?: '—') ?>
      </span>
      <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
        House BLs: <?= (int)$k['total_hbls'] ?>
      </span>
      <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
        Uninvoiced: <?= (int)$k['uninvoiced_count'] ?>
      </span>
      <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
        Open Financials: <?= (int)$k['open_financial_count'] ?>
      </span>
      <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
        Ready DO: <?= (int)$k['ready_do_count'] ?>
      </span>
      <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
        Released: <?= (int)$k['released_count'] ?>
      </span>
    </div>
  </div>

  <div class="flex flex-wrap gap-2">
    <a data-nav href="<?= h(to('/shipments/view?id=' . (int)$m['id'] . '&tab=overview')) ?>"
       class="tab-pill <?= $tab === 'overview' ? 'active' : '' ?>">
      Overview
    </a>

    <a data-nav href="<?= h(to('/shipments/view?id=' . (int)$m['id'] . '&tab=hbls')) ?>"
       class="tab-pill <?= $tab === 'hbls' ? 'active' : '' ?>">
      HBLs
    </a>

    <a data-nav href="<?= h(to('/shipments/view?id=' . (int)$m['id'] . '&tab=manifest')) ?>"
       class="tab-pill <?= $tab === 'manifest' ? 'active' : '' ?>">
      Manifest
    </a>

    <a data-nav href="<?= h(to('/shipments/view?id=' . (int)$m['id'] . '&tab=financials')) ?>"
       class="tab-pill <?= $tab === 'financials' ? 'active' : '' ?>">
      Financials
    </a>
  </div>

  <?php if ($tab === 'overview'): ?>
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-4">
      <div class="glass rounded-3xl p-5">
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Total HBLs</div>
        <div class="mt-2 text-3xl font-extrabold text-ink-900"><?= (int)$k['total_hbls'] ?></div>
      </div>

      <div class="glass rounded-3xl p-5">
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Uninvoiced</div>
        <div class="mt-2 text-3xl font-extrabold text-ink-900"><?= (int)$k['uninvoiced_count'] ?></div>
      </div>

      <div class="glass rounded-3xl p-5">
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Open Financials</div>
        <div class="mt-2 text-3xl font-extrabold text-ink-900"><?= (int)$k['open_financial_count'] ?></div>
      </div>

      <div class="glass rounded-3xl p-5">
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Ready For DO</div>
        <div class="mt-2 text-3xl font-extrabold text-ink-900"><?= (int)$k['ready_do_count'] ?></div>
      </div>

      <div class="glass rounded-3xl p-5">
        <div class="text-xs font-bold uppercase tracking-[0.16em] text-ink-500">Released</div>
        <div class="mt-2 text-3xl font-extrabold text-ink-900"><?= (int)$k['released_count'] ?></div>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($tab === 'hbls'): ?>
    <div class="glass rounded-3xl overflow-hidden">
      <div class="px-5 py-4 border-b border-ink-200 flex items-center justify-between gap-3">
        <div>
          <div class="font-extrabold text-ink-900">HBL Register</div>
        </div>

        <div class="flex gap-2">

          <a href="<?= h(to('/hbl/new?master_bl_id=' . (int)$m['id'])) ?>"
             data-nav
             class="px-4 py-3 rounded-2xl btn-primary">
            New HBL
          </a>
        </div>
      </div>

      <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-ink-100 text-ink-700">
            <tr class="text-left">
              <th class="px-4 py-3 font-semibold">HBL</th>
              <th class="px-4 py-3 font-semibold">Consignee</th>
              <th class="px-4 py-3 font-semibold">Billing Party</th>
              <th class="px-4 py-3 font-semibold">Cargo</th>
              <th class="px-4 py-3 font-semibold">Invoice</th>
              <th class="px-4 py-3 font-semibold">Status</th>
            </tr>
          </thead>

          <tbody class="text-ink-900 divide-y divide-ink-100">
            <?php foreach ($children as $r): ?>
              <tr
                class="child-row"
                data-hbl-row
                data-id="<?= (int)$r['id'] ?>"
                title="Click to open details">

                <td class="px-4 py-4">
                  <div class="font-extrabold text-ink-900"><?= h($r['hbl_no']) ?></div>
                  <div class="text-xs text-ink-500"><?= h($m['mbl_no'] ?: '—') ?></div>
                </td>

                <td class="px-4 py-4">
                  <div class="font-medium text-ink-900"><?= h($r['consignee_name'] ?: '—') ?></div>
                </td>

                <td class="px-4 py-4">
                  <div class="font-medium text-ink-900"><?= h($r['billing_name'] ?: '—') ?></div>
                </td>

                <td class="px-4 py-4">
                  <div class="font-medium text-ink-900">Pkgs: <?= h($r['packages'] ?: '0') ?></div>
                  <div class="text-xs text-ink-500">
                    Wt: <?= h($r['gross_weight_kg'] ?: '0') ?> kg ·
                    CBM: <?= h($r['cbm'] ?: '0') ?>
                  </div>
                </td>

                <td class="px-4 py-4">
                  <?php if (!empty($r['invoice_no'])): ?>
                    <div class="font-semibold text-ink-900"><?= h($r['invoice_no']) ?></div>
                    <div class="text-xs text-ink-500"><?= h($r['invoice_status'] ?: '—') ?></div>
                  <?php else: ?>
                    <span class="text-ink-400">No invoice</span>
                  <?php endif; ?>
                </td>

                <td class="px-4 py-4">
                  <span class="inline-flex px-3 py-1 rounded-full text-xs font-bold bg-orange-50 text-orange-700 border border-orange-200">
                    <?= h($r['status'] ?: '—') ?>
                  </span>
                </td>
              </tr>
            <?php endforeach; ?>

            <?php if (!$children): ?>
              <tr>
                <td class="px-4 py-10 text-ink-500 text-center" colspan="6">No HBLs under this manifest.</td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($tab === 'manifest'): ?>
    <div class="glass rounded-3xl p-5">
      <div class="flex items-center justify-between gap-3">
        <div>
          <div class="font-extrabold text-ink-900">Manifest Access</div>
          <div class="text-sm text-ink-500 mt-1">Condensed document view for this shipment.</div>
        </div>

        <a href="<?= h(to('/doc/manifest?master_bl_id=' . (int)$m['id'])) ?>"
           target="_blank"
           class="px-4 py-3 rounded-2xl btn-primary">
          Open Manifest
        </a>
      </div>

      <div class="mt-5 overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-ink-100 text-ink-700">
            <tr class="text-left">
              <th class="px-4 py-3 font-semibold">HBL</th>
              <th class="px-4 py-3 font-semibold">Consignee</th>
              <th class="px-4 py-3 font-semibold">HS Code</th>
              <th class="px-4 py-3 font-semibold">Manifest No</th>
              <th class="px-4 py-3 font-semibold">CFS</th>
            </tr>
          </thead>

          <tbody class="text-ink-900 divide-y divide-ink-100">
            <?php foreach ($children as $r): ?>
              <tr class="child-row" data-hbl-row data-id="<?= (int)$r['id'] ?>">
                <td class="px-4 py-3 font-semibold text-ink-900"><?= h($r['hbl_no']) ?></td>
                <td class="px-4 py-3"><?= h($r['consignee_name'] ?: '—') ?></td>
                <td class="px-4 py-3"><?= h($r['hs_code'] ?: '—') ?></td>
                <td class="px-4 py-3"><?= h($r['manifest_no'] ?: '—') ?></td>
                <td class="px-4 py-3"><?= h($r['cfs'] ?: '—') ?></td>
              </tr>
            <?php endforeach; ?>

            <?php if (!$children): ?>
              <tr>
                <td class="px-4 py-10 text-ink-500 text-center" colspan="5">No manifest rows available.</td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($tab === 'financials'): ?>
    <div class="glass rounded-3xl p-5">
      <div class="flex items-center justify-between gap-3">
        <div>
          <div class="font-extrabold text-ink-900">Manifest Financial Snapshot</div>
        </div>

        <a href="<?= h(to('/hbl?master_bl_id=' . (int)$m['id'] . '&uninvoiced=1')) ?>"
           data-nav
           class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold">
          View Uninvoiced
        </a>
      </div>

      <div class="mt-5 overflow-x-auto">
        <table class="w-full text-sm">
          <thead class="bg-ink-100 text-ink-700">
            <tr class="text-left">
              <th class="px-4 py-3 font-semibold">HBL</th>
              <th class="px-4 py-3 font-semibold">Billing Party</th>
              <th class="px-4 py-3 font-semibold">Invoice</th>
              <th class="px-4 py-3 font-semibold">Invoice Status</th>
              <th class="px-4 py-3 font-semibold">HBL Status</th>
            </tr>
          </thead>

          <tbody class="text-ink-900 divide-y divide-ink-100">
            <?php foreach ($children as $r): ?>
              <tr class="child-row" data-hbl-row data-id="<?= (int)$r['id'] ?>">
                <td class="px-4 py-3 font-semibold text-ink-900"><?= h($r['hbl_no']) ?></td>
                <td class="px-4 py-3"><?= h($r['billing_name'] ?: '—') ?></td>
                <td class="px-4 py-3"><?= h($r['invoice_no'] ?: '—') ?></td>
                <td class="px-4 py-3"><?= h($r['invoice_status'] ?: '—') ?></td>
                <td class="px-4 py-3"><?= h($r['status'] ?: '—') ?></td>
              </tr>
            <?php endforeach; ?>

            <?php if (!$children): ?>
              <tr>
                <td class="px-4 py-10 text-ink-500 text-center" colspan="5">No financial rows available.</td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>
</div>