<?php
global $db, $config;

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

$q = trim((string)($_GET['q'] ?? ''));

$where = [];
$params = [];

if ($q !== '') {
  $where[] = "(
    m.mbl_no LIKE ?
    OR m.vessel_name LIKE ?
    OR m.voyage_no LIKE ?
    OR m.container_no LIKE ?
    OR UPPER(COALESCE(m.status, '')) LIKE UPPER(?)
    OR sl.name LIKE ?
    OR pol.name LIKE ?
    OR pod.name LIKE ?
  )";
  $like = "%{$q}%";
  array_push($params, $like, $like, $like, $like, $like, $like, $like, $like);
}

$sql = "
  SELECT
    m.*,
    sl.name AS shipping_line_name,
    pol.name AS pol_name,
    pod.name AS pod_name,

    COUNT(h.id) AS hbl_count,

    SUM(
      CASE
        WHEN h.id IS NOT NULL
         AND 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 h.id IS NOT NULL
         AND UPPER(COALESCE(h.status,'')) = 'READY_FOR_DO'
        THEN 1 ELSE 0
      END
    ) AS ready_do_count,

    SUM(
      CASE
        WHEN h.id IS NOT NULL
         AND UPPER(COALESCE(h.status,'')) = 'RELEASED'
        THEN 1 ELSE 0
      END
    ) AS released_count

  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
  LEFT JOIN house_bls h ON h.master_bl_id = m.id
";

if ($where) {
  $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= "
  GROUP BY
    m.id, m.mbl_no, m.shipping_line_id, m.pol_port_id, m.pod_port_id,
    m.vessel_name, m.voyage_no, m.eta_date, m.container_no, m.seal_no,
    m.container_type, m.status, m.created_at, m.updated_at,
    sl.name, pol.name, pod.name
  ORDER BY m.id DESC
  LIMIT 300
";

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

<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">Operational Workspace</div>
      <h1 class="text-3xl font-extrabold text-ink-900">Manifests</h1>
      <div class="text-sm text-ink-500 mt-1">
        Manifests register
      </div>
    </div>

    <div class="flex flex-wrap gap-2">
      <a href="<?= h(to('/mbl/new')) ?>"
         data-nav
         class="px-4 py-3 rounded-2xl btn-primary">
        New Manifest
      </a>
    </div>
  </div>

  <form id="shipment-search-form"
        method="get"
        action="<?= h(to('/shipments')) ?>"
        class="glass rounded-3xl p-4 md:p-5"
        onsubmit="event.preventDefault(); if (window.wscRunShipmentSearch) window.wscRunShipmentSearch(this.querySelector('[name=q]'), true); return false;">
    <div>
      <label class="form-label">Search</label>
      <input
        id="shipment-auto-search"
        type="search"
        name="q"
        value="<?= h((string)$q) ?>"
        placeholder="Search by manifest, vessel, voyage, container, line, port, or status..."
        autocomplete="off"
        class="mt-1 w-full px-4 py-3 rounded-2xl"
        oninput="if (window.wscRunShipmentSearch) window.wscRunShipmentSearch(this, true);" />
    </div>
  </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">Manifests Register</div>
        <div class="text-xs text-ink-500 mt-1">Open a manifest to manage HBLs and financials.</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">Manifest</th>
            <th class="px-4 py-3 font-semibold">Vessel / Voyage</th>
            <th class="px-4 py-3 font-semibold">Route</th>
            <th class="px-4 py-3 font-semibold">Container</th>
            <th class="px-4 py-3 font-semibold">HBLs</th>
            <th class="px-4 py-3 font-semibold text-right">Open</th>
          </tr>
        </thead>

        <tbody class="text-ink-900 divide-y divide-ink-100">
          <?php foreach ($rows as $r): ?>
            <tr class="hover:bg-orange-50/60 transition">
              <td class="px-4 py-4">
                <div class="font-extrabold text-ink-900"><?= h((string)$r['mbl_no']) ?></div>
                <div class="text-xs text-ink-500"><?= h((string)($r['shipping_line_name'] ?: '—')) ?></div>
              </td>

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

              <td class="px-4 py-4">
                <div class="font-medium text-ink-900">
                  <?= h((string)($r['pol_name'] ?: '—')) ?> → <?= h((string)($r['pod_name'] ?: '—')) ?>
                </div>
                <div class="text-xs text-ink-500">ETA: <?= h((string)($r['eta_date'] ?: '—')) ?></div>
              </td>

              <td class="px-4 py-4">
                <div class="font-medium text-ink-900"><?= h((string)($r['container_no'] ?: '—')) ?></div>
                <div class="text-xs text-ink-500">
                  <?= h((string)($r['container_type'] ?: '—')) ?>
                  <?php if (!empty($r['seal_no'])): ?>
                    · Seal: <?= h((string)$r['seal_no']) ?>
                  <?php endif; ?>
                </div>
              </td>

              <td class="px-4 py-4">
                <div class="font-extrabold text-ink-900"><?= (int)$r['hbl_count'] ?></div>
                <div class="text-xs text-ink-500">
                  Uninvoiced: <?= (int)$r['uninvoiced_count'] ?>
                  · Ready DO: <?= (int)$r['ready_do_count'] ?>
                  · Released: <?= (int)$r['released_count'] ?>
                </div>
              </td>

              <td class="px-4 py-4 text-right">
                <button
                  type="button"
                  class="px-4 py-2 rounded-2xl btn-primary"
                  data-action="shipment-open"
                  data-id="<?= (int)$r['id'] ?>">
                  Open
                </button>
              </td>
            </tr>
          <?php endforeach; ?>

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

<script>
(function () {
  if (window.__wscShipmentAutoSearchInstalled) return;
  window.__wscShipmentAutoSearchInstalled = true;

  window.__wscShipmentAutoSearchTimer = null;
  window.__wscShipmentAutoSearchLastUrl = '';

  window.wscRunShipmentSearch = function(input, pushState) {
    if (!input) return;

    clearTimeout(window.__wscShipmentAutoSearchTimer);

    window.__wscShipmentAutoSearchTimer = setTimeout(function () {
      const form = input.closest('form');
      if (!form) return;

      const action = form.getAttribute('action') || window.location.pathname;
      const value = (input.value || '').trim();
      const cursorPos = input.selectionStart || value.length;

      const qs = new URLSearchParams();
      if (value !== '') qs.set('q', value);

      const query = qs.toString();
      const url = query ? (action + '?' + query) : action;

      if (url === window.__wscShipmentAutoSearchLastUrl) return;
      window.__wscShipmentAutoSearchLastUrl = url;

      function restoreFocus() {
        setTimeout(function () {
          const freshInput = document.getElementById('shipment-auto-search');
          if (!freshInput) return;

          freshInput.focus();

          try {
            const pos = Math.min(cursorPos, freshInput.value.length);
            freshInput.setSelectionRange(pos, pos);
          } catch (e) {}
        }, 80);
      }

      if (typeof window.loadPartial === 'function') {
        const p = window.loadPartial(url, pushState !== false);

        if (p && typeof p.then === 'function') {
          p.then(restoreFocus);
        } else {
          restoreFocus();
        }

        return;
      }

      window.location.href = url;
    }, 650);
  };
})();
</script>