<?php
global $db, $config;

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

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

$sql = "SELECT m.*, sl.name shipping_line, p1.name pol, p2.name pod
        FROM master_bls m
        JOIN shipping_lines sl ON sl.id=m.shipping_line_id
        JOIN ports p1 ON p1.id=m.pol_port_id
        JOIN ports p2 ON p2.id=m.pod_port_id";

$params = [];
if ($q !== '') {
  $sql .= " WHERE (
      m.mbl_no LIKE ?
      OR sl.name LIKE ?
      OR p1.name LIKE ?
      OR p2.name LIKE ?
      OR m.vessel_name LIKE ?
      OR m.voyage_no LIKE ?
      OR m.container_no LIKE ?
      OR m.seal_no LIKE ?
    )";
  $like = '%' . $q . '%';
  $params = [$like,$like,$like,$like,$like,$like,$like,$like];
}

$sql .= " ORDER BY m.id DESC LIMIT 200";

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

function mblStatusClass(string $status): string {
  $s = strtoupper(trim($status));
  return match ($s) {
    'RECEIVED' => 'bg-orange-50 text-orange-700 border border-orange-200',
    'BREAKDOWN_IN_PROGRESS', 'IN_PROGRESS' => 'bg-amber-50 text-amber-700 border border-amber-200',
    'BREAKDOWN_DONE', 'CLEARING' => 'bg-blue-50 text-blue-700 border border-blue-200',
    'RELEASED' => 'bg-emerald-50 text-emerald-700 border border-emerald-200',
    'CLOSED' => 'bg-slate-100 text-slate-700 border border-slate-200',
    default => 'bg-slate-50 text-slate-700 border border-slate-200',
  };
}
?>

<style>
  .mbl-head-card{
    background:linear-gradient(180deg,#fff 0%,#fffaf5 100%);
    border:1px solid rgba(249,115,22,0.14);
    box-shadow:0 10px 35px rgba(15,23,42,0.06);
  }
  .mbl-table-wrap{
    background:#fff;
    border:1px solid rgba(15,23,42,0.08);
    box-shadow:0 14px 40px rgba(15,23,42,0.06);
  }
  .mbl-thead{
    background:linear-gradient(90deg, rgba(249,115,22,0.10), rgba(255,247,237,1));
  }
  .mbl-row:hover{
    background:#fff7ed;
  }
  .mbl-kicker{
    color:#c2410c;
  }
  .btn-soft-orange{
    background:#fff7ed;
    border:1px solid #fed7aa;
    color:#9a3412;
    font-weight:600;
  }
  .btn-soft-orange:hover{
    background:#ffedd5;
  }
  .btn-outline-neutral{
    background:#fff;
    border:1px solid #e2e8f0;
    color:#334155;
    font-weight:600;
  }
  .btn-outline-neutral:hover{
    background:#f8fafc;
  }
</style>

<div class="flex items-center justify-between mb-4">
  <div>
    <h1 class="text-2xl font-semibold text-ink-900">Master Bills of Lading</h1>
    <div class="text-sm text-ink-600 mt-1">Track inbound master shipments, manifests, and operational status.</div>
  </div>

  <a class="btn-primary px-4 py-2 rounded-2xl transition"
     href="<?= h($basePath) ?>/mbl/new" data-nav>New MBL</a>
</div>

<div class="mbl-head-card rounded-3xl p-5 mb-4">
  <form class="grid md:grid-cols-6 gap-3"
        onsubmit="event.preventDefault();
                  const q=this.q.value.trim();
                  const base=<?= json_encode($basePath, JSON_UNESCAPED_SLASHES) ?>;
                  const url=(base?base:'') + '/mbl' + (q?('?q='+encodeURIComponent(q)):'');
                  window.loadPartial ? loadPartial(url,true) : (location.href=url);">
    <div class="md:col-span-5">
      <label class="form-label">Search MBLs</label>
      <input name="q"
             value="<?= h($q) ?>"
             class="mt-1 w-full px-4 py-3 rounded-2xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 outline-none focus:ring-2 focus:ring-orange-300"
             placeholder="MBL No, shipping line, POL, POD, vessel, voyage, container, seal no..." />
    </div>

    <div class="flex items-end gap-2">
      <button class="w-full px-4 py-3 rounded-2xl btn-soft-orange transition">Search</button>
    </div>
  </form>
</div>

<div class="mbl-table-wrap rounded-3xl overflow-hidden">
  <div class="overflow-x-auto">
    <table class="w-full text-sm">
      <thead class="mbl-thead">
        <tr class="text-left text-ink-800">
          <th class="p-3 font-semibold">MBL</th>
          <th class="p-3 font-semibold">Shipping Line</th>
          <th class="p-3 font-semibold">POL → POD</th>
          <th class="p-3 font-semibold">Vessel / Voyage</th>
          <th class="p-3 font-semibold">Container / Seal</th>
          <th class="p-3 font-semibold">ETA</th>
          <th class="p-3 font-semibold">Status</th>
          <th class="p-3 font-semibold">Actions</th>
        </tr>
      </thead>

      <tbody class="text-ink-900">
        <?php foreach ($rows as $r): ?>
          <tr class="border-t border-ink-200 mbl-row transition">
            <td class="p-3">
              <div class="font-semibold text-ink-900"><?= h($r['mbl_no']) ?></div>
              <div class="text-[11px] mbl-kicker mt-1">ID #<?= (int)$r['id'] ?></div>
            </td>

            <td class="p-3"><?= h($r['shipping_line']) ?></td>

            <td class="p-3">
              <div><?= h($r['pol']) ?></div>
              <div class="text-xs text-ink-500 mt-1">to <?= h($r['pod']) ?></div>
            </td>

            <td class="p-3">
              <div><?= h(trim(($r['vessel_name'] ?? '') . ' ' . ($r['voyage_no'] ?? ''))) ?: '—' ?></div>
            </td>

            <td class="p-3">
              <div><?= h($r['container_no'] ?? '—') ?></div>
              <div class="text-xs text-ink-500 mt-1">Seal: <?= h($r['seal_no'] ?? '—') ?></div>
            </td>

            <td class="p-3"><?= h($r['eta_date'] ?? '—') ?></td>

            <td class="p-3">
              <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold <?= h(mblStatusClass((string)$r['status'])) ?>">
                <?= h($r['status']) ?>
              </span>
            </td>

            <td class="p-3">
              <div class="flex flex-wrap gap-2">
                <a class="px-3 py-2 rounded-2xl btn-outline-neutral transition"
                   href="<?= h($basePath) ?>/mbl/edit?id=<?= (int)$r['id'] ?>" data-nav>Edit</a>

                <a class="px-3 py-2 rounded-2xl btn-soft-orange transition"
                   href="<?= h($basePath) ?>/doc/manifest?mbl_id=<?= (int)$r['id'] ?>"
                   target="_blank" rel="noopener">View Manifest</a>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>

        <?php if (!$rows): ?>
          <tr>
            <td class="p-4 text-ink-500" colspan="8">
              <?= $q !== '' ? 'No MBLs matched your search.' : 'No records yet.' ?>
            </td>
          </tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>