<?php
global $db, $config;

$id = (int)($_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 text-sm">Missing HBL id.</div>';
  return;
}

$basePath = rtrim(($config['app']['base_path'] ?? ''), '/');

$st = $db->prepare("
  SELECT
    h.*,

    m.id AS master_bl_id,
    m.mbl_no,
    m.vessel_name,
    m.voyage_no,
    m.container_no,
    m.container_type,
    m.seal_no,
    m.eta_date,

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

    i.id AS invoice_id,
    i.invoice_no,
    i.status AS invoice_status,
    i.currency AS invoice_currency,
    i.total AS invoice_total

  FROM house_bls h
  LEFT JOIN master_bls m ON m.id = h.master_bl_id
  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 customers c3 ON c3.id = h.notify_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.id = ?
  LIMIT 1
");
$st->execute([$id]);
$r = $st->fetch();

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

$isReleased = strtoupper((string)($r['status'] ?? '')) === 'RELEASED';

$invoiceCleanUrl = !empty($r['invoice_id'])
  ? $basePath . '/invoice/view?id=' . (int)$r['invoice_id']
  : '';

$payment = null;
try {
  $p = $db->prepare("
    SELECT id, amount, currency, pay_date, method, ref_no
    FROM payments
    WHERE house_bl_id = ?
    ORDER BY id DESC
    LIMIT 1
  ");
  $p->execute([$id]);
  $payment = $p->fetch() ?: null;
} catch (Throwable $e) {
  $payment = null;
}

function drawer_value($v, $fallback = '—') {
  $v = is_string($v) ? trim($v) : $v;
  return ($v === null || $v === '') ? $fallback : $v;
}
?>

<div data-hbl-drawer-title="<?= h((string)$r['hbl_no']) ?>"></div>

<div class="space-y-4" data-hbl-drawer-root="<?= (int)$r['id'] ?>">

  <div
    id="releaseFeedback-<?= (int)$r['id'] ?>"
    class="hidden rounded-2xl border px-4 py-3 text-sm font-semibold"
    role="status"
    aria-live="polite">
  </div>

  <!-- HERO -->
  <div class="drawer-card p-4">
    <div class="flex items-start justify-between gap-3">
      <div>
        <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">House BL</div>
        <div class="mt-1 text-2xl font-extrabold text-ink-900"><?= h((string)$r['hbl_no']) ?></div>

        <div class="mt-3 flex flex-wrap gap-2">
          <span class="drawer-chip" data-hbl-status-chip><?= h((string)drawer_value($r['status'])) ?></span>
          <span class="drawer-chip">MBL: <?= h((string)drawer_value($r['mbl_no'])) ?></span>

          <?php if (!empty($r['invoice_no'])): ?>
            <span class="drawer-chip">Invoice: <?= h((string)$r['invoice_no']) ?></span>
          <?php else: ?>
            <span class="drawer-chip">No invoice</span>
          <?php endif; ?>
        </div>
      </div>

      <div class="text-right">
        <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">Manifest</div>
        <div class="mt-1 font-bold text-ink-900"><?= h((string)drawer_value($r['manifest_no'])) ?></div>
      </div>
    </div>
  </div>

  <!-- SUMMARY -->
  <div class="drawer-card p-4">
    <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">Summary</div>

    <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Consignee</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['consignee_name'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Billing Party</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['billing_name'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Packages</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['packages'], '0')) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Weight / CBM</div>
        <div class="mt-1 font-semibold text-ink-900">
          <?= h((string)drawer_value($r['gross_weight_kg'], '0')) ?> kg / <?= h((string)drawer_value($r['cbm'], '0')) ?>
        </div>
      </div>
    </div>

    <div class="mt-4">
      <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Goods Description</div>
      <div class="mt-1 text-sm leading-6 text-ink-900">
        <?= nl2br(h((string)drawer_value($r['goods_description']))) ?>
      </div>
    </div>
  </div>

  <!-- INVOICE / FINANCIAL SNAPSHOT -->
  <div class="drawer-card p-4">
    <div class="flex items-center justify-between gap-3">
      <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">Invoice Snapshot</div>

      <?php if (!empty($r['invoice_status'])): ?>
        <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((string)$r['invoice_status']) ?>
        </span>
      <?php endif; ?>
    </div>

    <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Invoice No</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['invoice_no'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Invoice Total</div>
        <div class="mt-1 font-semibold text-ink-900">
          <?php if (!empty($r['invoice_id'])): ?>
            <?= h((string)drawer_value($r['invoice_currency'], 'USD')) ?> <?= number_format((float)($r['invoice_total'] ?? 0), 2) ?>
          <?php else: ?>
            —
          <?php endif; ?>
        </div>
      </div>
    </div>

    <?php if ($payment): ?>
      <div class="mt-4 pt-4 border-t border-ink-100">
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Latest Payment</div>
        <div class="mt-2 text-sm text-ink-900">
          <span class="font-semibold"><?= h((string)drawer_value($payment['currency'], 'USD')) ?> <?= number_format((float)($payment['amount'] ?? 0), 2) ?></span>
          · <?= h((string)drawer_value($payment['method'])) ?>
          · <?= h((string)drawer_value($payment['pay_date'])) ?>
          <?php if (!empty($payment['ref_no'])): ?>
            · Ref: <?= h((string)$payment['ref_no']) ?>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <!-- SHIPMENT / PARENT -->
  <div class="drawer-card p-4">
    <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">Parent Shipment</div>

    <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Master BL</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['mbl_no'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Vessel / Voyage</div>
        <div class="mt-1 font-semibold text-ink-900">
          <?= h((string)drawer_value($r['vessel_name'])) ?> / <?= h((string)drawer_value($r['voyage_no'])) ?>
        </div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Container</div>
        <div class="mt-1 font-semibold text-ink-900">
          <?= h((string)drawer_value($r['container_no'])) ?>
          <?php if (!empty($r['container_type'])): ?>
            · <?= h((string)$r['container_type']) ?>
          <?php endif; ?>
        </div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Seal / ETA</div>
        <div class="mt-1 font-semibold text-ink-900">
          <?= h((string)drawer_value($r['seal_no'])) ?> / <?= h((string)drawer_value($r['eta_date'])) ?>
        </div>
      </div>
    </div>

    <div class="mt-4">
      <button
        type="button"
        class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold"
        data-action="shipment-open"
        data-id="<?= (int)$r['master_bl_id'] ?>">
        Open Parent Shipment
      </button>
    </div>
  </div>

  <!-- EXTRA DETAILS -->
  <div class="drawer-card p-4">
    <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">Additional Details</div>

    <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">Notify Party</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['notify_name'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">HS Code</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['hs_code'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">ICMS BL No</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['icms_bl_no'])) ?></div>
      </div>

      <div>
        <div class="text-xs uppercase tracking-[0.14em] text-ink-500 font-bold">CFS</div>
        <div class="mt-1 font-semibold text-ink-900"><?= h((string)drawer_value($r['cfs'])) ?></div>
      </div>
    </div>
  </div>

  <!-- ACTIONS -->
  <div class="drawer-card p-4">
    <div class="text-xs uppercase tracking-[0.16em] text-ink-500 font-bold">Actions</div>

    <div class="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-3">

      <?php if (!$isReleased): ?>
        <button
          type="button"
          class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold"
          data-action="edit-hbl"
          data-id="<?= (int)$r['id'] ?>">
          Edit HBL
        </button>
      <?php else: ?>
        <button
          type="button"
          class="px-4 py-3 rounded-2xl border border-slate-200 bg-slate-50 text-slate-400 font-semibold cursor-not-allowed"
          disabled
          title="Released HBLs cannot be edited.">
          Edit Locked
        </button>
      <?php endif; ?>

      <?php if (!empty($r['invoice_id'])): ?>
        <button
          type="button"
          class="px-4 py-3 rounded-2xl border border-orange-200 bg-orange-50 hover:bg-orange-100 text-orange-800 font-semibold text-center"
          onclick="window.open('<?= h($invoiceCleanUrl) ?>', '_blank', 'noopener,noreferrer'); return false;">
          View Invoice
        </button>
      <?php else: ?>
        <button
          type="button"
          class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold"
          data-action="gen-invoice"
          data-id="<?= (int)$r['id'] ?>">
          Generate Invoice
        </button>
      <?php endif; ?>

      <?php if (!empty($r['invoice_id'])): ?>
        <button
          type="button"
          class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold"
          data-action="receipt"
          data-id="<?= (int)$r['id'] ?>"
          data-invoice-id="<?= (int)$r['invoice_id'] ?>">
          Receipt
        </button>
      <?php else: ?>
        <button
          type="button"
          class="px-4 py-3 rounded-2xl border border-ink-200 bg-ink-50 text-ink-400 font-semibold cursor-not-allowed"
          disabled>
          Receipt
        </button>
      <?php endif; ?>

      <button
        type="button"
        class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold"
        data-action="arrival"
        data-id="<?= (int)$r['id'] ?>">
        Arrival Notice
      </button>

      <button
        type="button"
        class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold"
        data-action="do"
        data-id="<?= (int)$r['id'] ?>">
        Delivery Order
      </button>

<?php if (!$isReleased): ?>
  <button
    type="button"
    class="px-4 py-3 rounded-2xl border border-emerald-300 bg-emerald-50 hover:bg-emerald-100 text-emerald-800 font-semibold"
    data-id="<?= (int)$r['id'] ?>"
    data-hbl-no="<?= h((string)$r['hbl_no']) ?>"
    data-has-invoice="<?= !empty($r['invoice_id']) ? '1' : '0' ?>"
    data-invoice-status="<?= h(strtoupper((string)($r['invoice_status'] ?? ''))) ?>"
    onclick="
      (async function(btn){
        const root = btn.closest('[data-hbl-drawer-root]');
        const box = root ? root.querySelector('[id^=releaseFeedback-]') : null;

        function msg(type, text){
          if (!box) { alert(text); return; }

          if (type === 'error') {
            box.className = 'rounded-2xl border border-red-200 bg-red-50 text-red-700 px-4 py-3 text-sm font-semibold';
          } else if (type === 'success') {
            box.className = 'rounded-2xl border border-emerald-200 bg-emerald-50 text-emerald-700 px-4 py-3 text-sm font-semibold';
          } else if (type === 'warning') {
            box.className = 'rounded-2xl border border-orange-200 bg-orange-50 text-orange-700 px-4 py-3 text-sm font-semibold';
          } else {
            box.className = 'rounded-2xl border border-blue-200 bg-blue-50 text-blue-700 px-4 py-3 text-sm font-semibold';
          }

          box.textContent = text;
          box.scrollIntoView({behavior:'smooth', block:'nearest'});
        }

if (btn.dataset.hasInvoice !== '1') {
  const m = 'Release aborted.\n\nGenerate the invoice first before releasing this HBL.';
  alert(m);
  msg('error', m.replace(/\n/g,' '));
  return false;
}

        const invoiceStatus = (btn.dataset.invoiceStatus || '').toUpperCase();
if (invoiceStatus !== 'PAID') {
  const m = 'Release aborted.\n\nInvoice exists but is not paid.\nCurrent status: ' + (invoiceStatus || 'UNKNOWN') + '.';
  alert(m);
  msg('error', m.replace(/\n/g,' '));
  return false;
}

        if (!confirm('Sure To Release?')) {
          msg('warning', 'Release cancelled. No change was made.');
          return false;
        }

        btn.disabled = true;
        btn.textContent = 'Releasing...';
        btn.classList.add('opacity-70', 'cursor-wait');
        msg('info', 'Releasing...');

        try {
          const fd = new FormData();
          fd.append('id', btn.dataset.id);
          fd.append('hbl_id', btn.dataset.id);
          fd.append('house_bl_id', btn.dataset.id);
          fd.append('status', 'RELEASED');

          const res = await fetch('<?= h($basePath) ?>/api/hbl/status', {
            method: 'POST',
            body: fd,
            headers: {'X-Requested-With':'XMLHttpRequest'},
            credentials: 'same-origin'
          });

          let payload = null;
          try { payload = await res.json(); } catch(e) {}

          if (!res.ok || (payload && payload.ok === false)) {
            throw new Error((payload && payload.msg) ? payload.msg : 'Release failed.');
          }

          btn.className = 'px-4 py-3 rounded-2xl border border-emerald-200 bg-emerald-50 text-emerald-700 font-semibold cursor-default';
          btn.textContent = 'Already Released';

          const chip = root ? root.querySelector('[data-hbl-status-chip]') : null;
          if (chip) chip.textContent = 'RELEASED';

          const editBtn = root ? root.querySelector('[data-action=edit-hbl]') : null;
          if (editBtn) {
            const locked = document.createElement('button');
            locked.type = 'button';
            locked.disabled = true;
            locked.title = 'Released HBLs cannot be edited.';
            locked.className = 'px-4 py-3 rounded-2xl border border-slate-200 bg-slate-50 text-slate-400 font-semibold cursor-not-allowed';
            locked.textContent = 'Edit Locked';
            editBtn.replaceWith(locked);
          }

          msg('success', 'Release Successful');

        } catch(e) {
          btn.disabled = false;
          btn.className = 'px-4 py-3 rounded-2xl border border-emerald-300 bg-emerald-50 hover:bg-emerald-100 text-emerald-800 font-semibold';
          btn.textContent = 'Mark Released';
          msg('error', e && e.message ? e.message : 'Release failed. Please try again.');
        }

        return false;
      })(this);
      return false;
    ">
    Mark Released
  </button>
<?php else: ?>
  <button
    type="button"
    class="px-4 py-3 rounded-2xl border border-emerald-200 bg-emerald-50 text-emerald-700 font-semibold cursor-default"
    disabled>
    Already Released
  </button>
<?php endif; ?>

    </div>
  </div>
</div>

