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

$mblFilter = (int)($_GET['master_bl_id'] ?? 0);
$statusFilter = strtoupper(trim((string)($_GET['status'] ?? '')));
$uninvoicedOnly = (int)($_GET['uninvoiced'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));

/**
 * Preserve selected MBL for Select2:
 * If filtering by master_bl_id, fetch that MBL so we can render a selected option.
 */
$selectedMbl = null;
if ($mblFilter) {
  $s = $db->prepare("SELECT id, mbl_no, vessel_name, voyage_no FROM master_bls WHERE id=?");
  $s->execute([$mblFilter]);
  $selectedMbl = $s->fetch() ?: null;
}

/**
 * HBL listing
 * Pull latest invoice only so each HBL stays single-row and can show invoice number/status.
 */
$where = [];
$params = [];

if ($mblFilter) {
  $where[] = "h.master_bl_id = ?";
  $params[] = $mblFilter;
}
if ($statusFilter !== '') {
  $where[] = "UPPER(COALESCE(h.status,'')) = ?";
  $params[] = $statusFilter;
}
if ($uninvoicedOnly === 1) {
  $where[] = "i.id IS NULL";
}
if ($q !== '') {
  $where[] = "(
    h.hbl_no LIKE ?
    OR m.mbl_no LIKE ?
    OR c1.name LIKE ?
    OR c2.name LIKE ?
    OR COALESCE(h.goods_description, '') LIKE ?
    OR COALESCE(i.invoice_no, '') LIKE ?
    OR UPPER(COALESCE(h.status,'')) LIKE UPPER(?)
  )";
  $like = "%{$q}%";
  array_push($params, $like, $like, $like, $like, $like, $like, $like);
}

$sql = "
  SELECT
    h.*,
    m.mbl_no,
    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
  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
  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
  )
";
if ($where) {
  $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY h.id DESC LIMIT 300";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$activeFilters = [];
if ($q !== '') {
  $activeFilters[] = 'Search: ' . $q;
}
if ($mblFilter && $selectedMbl) {
  $activeFilters[] = 'MBL: ' . $selectedMbl['mbl_no'];
}
if ($statusFilter !== '') {
  $activeFilters[] = 'Status: ' . $statusFilter;
}
if ($uninvoicedOnly === 1) {
  $activeFilters[] = 'Uninvoiced only';
}
?>

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

<div class="space-y-5">
  <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
    <div>
      <div class="text-sm font-bold uppercase tracking-[0.2em] text-orange-600">Child Shipment Register</div>
      <h1 class="text-3xl font-extrabold text-ink-900">House Bills of Lading</h1>
      <div class="text-sm text-ink-500 mt-1">
        Clean HBL register with row-click detail drawer and reduced screen clutter.
      </div>
    </div>

    <div class="flex flex-wrap gap-2">
      <a href="<?= h(to('/hbl/new' . ($mblFilter ? ('?master_bl_id=' . $mblFilter) : ''))) ?>"
         data-nav
         class="px-4 py-3 rounded-2xl btn-primary">
        New HBL
      </a>

      <?php if ($mblFilter): ?>
        <a href="<?= h(to('/shipments/view?id=' . $mblFilter . '&tab=hbls')) ?>"
           data-nav
           class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold">
          Open Parent Shipment
        </a>
      <?php endif; ?>
    </div>
  </div>

  <form id="hbl-filter-form"
        method="get"
        action="<?= h(to('/hbl')) ?>"
        class="glass rounded-3xl p-4 md:p-5">
    <div class="grid grid-cols-1 md:grid-cols-6 gap-3">
      <div class="md:col-span-2">
        <label class="form-label">Search</label>
        <input
          type="search"
          name="q"
          value="<?= h((string)$q) ?>"
          placeholder="HBL / MBL / consignee / billing / invoice / cargo / status"
          class="mt-1 w-full px-4 py-3 rounded-2xl" />
      </div>

      <div class="md:col-span-2">
        <label class="form-label">Filter by Shipment (MBL)</label>
        <select name="master_bl_id" class="js-mbl mt-1 w-full">
          <option value=""></option>
          <?php if ($selectedMbl): ?>
            <option value="<?= (int)$selectedMbl['id'] ?>" selected>
              <?= h((string)$selectedMbl['mbl_no']) ?>
            </option>
          <?php endif; ?>
        </select>
      </div>

      <div>
        <label class="form-label">Status</label>
        <select name="status" class="mt-1 w-full px-4 py-3 rounded-2xl">
          <option value="">All statuses</option>
          <?php
          $statuses = ['PENDING','AWAITING_INVOICE','AWAITING_PAYMENT','READY_FOR_DO','DO_ISSUED','RELEASED'];
          foreach ($statuses as $s):
          ?>
            <option value="<?= h((string)$s) ?>" <?= $statusFilter === $s ? 'selected' : '' ?>>
              <?= h((string)$s) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="flex items-end">
        <label class="inline-flex items-center gap-2 px-3 py-3 rounded-2xl border border-ink-200 bg-white w-full">
          <input type="checkbox" name="uninvoiced" value="1" <?= $uninvoicedOnly ? 'checked' : '' ?> />
          <span class="text-sm font-medium text-ink-800">Uninvoiced only</span>
        </label>
      </div>
    </div>

    <div class="mt-3 flex flex-wrap gap-2">
      <button class="px-4 py-3 rounded-2xl btn-primary" type="submit">Apply</button>
      <a href="<?= h(to('/hbl')) ?>"
         data-nav
         class="px-4 py-3 rounded-2xl border border-ink-200 bg-white hover:bg-orange-50 font-semibold text-center">
        Reset
      </a>
    </div>

    <?php if ($activeFilters): ?>
      <div class="mt-4 flex flex-wrap gap-2">
        <?php foreach ($activeFilters as $f): ?>
          <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)$f) ?>
          </span>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </form>

  <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 class="text-xs text-ink-500 mt-1">Click any row to open the details drawer and actions.</div>
      </div>
      <div class="text-sm text-ink-500"><?= count($rows) ?> record(s)</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 ($rows 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((string)$r['hbl_no']) ?></div>
                <div class="text-xs text-ink-500"><?= h((string)($r['mbl_no'] ?: '—')) ?></div>
              </td>

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

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

              <td class="px-4 py-4">
                <div class="font-medium text-ink-900">Pkgs: <?= h((string)($r['packages'] ?: '0')) ?></div>
                <div class="text-xs text-ink-500">
                  Wt: <?= h((string)($r['gross_weight_kg'] ?: '0')) ?> kg ·
                  CBM: <?= h((string)($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((string)$r['invoice_no']) ?></div>
                  <div class="text-xs text-ink-500"><?= h((string)($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((string)($r['status'] ?: '—')) ?>
                </span>
              </td>
            </tr>
          <?php endforeach; ?>

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

<script>
(function () {
  const form = document.getElementById('hbl-filter-form');
  if (!form) return;
  if (form.dataset.boundFilters === '1') return;
  form.dataset.boundFilters = '1';

  function submitThroughShell() {
    const action = form.getAttribute('action') || window.location.pathname;
    const qs = new URLSearchParams(new FormData(form)).toString();
    const url = qs ? (action + '?' + qs) : action;

    if (typeof window.loadPartial === 'function') {
      window.loadPartial(url, true);
      return true;
    }

    if (typeof window.appLoad === 'function') {
      window.appLoad(url, true);
      return true;
    }

    window.location.href = url;
    return true;
  }

  form.addEventListener('submit', function (e) {
    e.preventDefault();
    submitThroughShell();
  });

  const statusEl = form.querySelector('select[name="status"]');
  const uninvoicedEl = form.querySelector('input[name="uninvoiced"]');
  const searchEl = form.querySelector('input[name="q"]');
  const mblEl = form.querySelector('select[name="master_bl_id"]');

  if (statusEl) {
    statusEl.addEventListener('change', function () {
      submitThroughShell();
    });
  }

  if (uninvoicedEl) {
    uninvoicedEl.addEventListener('change', function () {
      submitThroughShell();
    });
  }

  if (mblEl) {
    mblEl.addEventListener('change', function () {
      submitThroughShell();
    });
  }

  let searchTimer = null;
  if (searchEl) {
    searchEl.addEventListener('input', function () {
      clearTimeout(searchTimer);
      searchTimer = setTimeout(function () {
        submitThroughShell();
      }, 350);
    });
  }

  // If Select2 is used and change is triggered through jQuery/Select2, this still catches it.
  if (window.jQuery && window.jQuery.fn) {
    const $mbl = window.jQuery(form).find('select[name="master_bl_id"]');
    if ($mbl.length) {
      $mbl.off('change.hblFilterAuto').on('change.hblFilterAuto', function () {
        submitThroughShell();
      });
    }
  }
})();
</script>