<?php
global $db, $config;

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

function money_usd($n): string { return 'USD ' . number_format((float)$n, 2); }

function safe_count(PDO $db, string $sql, array $params=[]): int {
  try { $st=$db->prepare($sql); $st->execute($params); return (int)$st->fetch()['c']; }
  catch(Throwable $e){ return 0; }
}

function safe_amount(PDO $db, string $sql, array $params=[]): float {
  try { $st=$db->prepare($sql); $st->execute($params); return (float)($st->fetch()['a'] ?? 0); }
  catch(Throwable $e){ return 0.0; }
}

/** MBL breakdown */
$mbl = ['RECEIVED'=>0,'IN_PROGRESS'=>0,'RELEASED'=>0];
try {
  $rows = $db->query("SELECT status, COUNT(*) c FROM master_bls GROUP BY status")->fetchAll();
  foreach ($rows as $r) {
    $s = strtoupper((string)$r['status']);
    if (!isset($mbl[$s])) $mbl[$s]=0;
    $mbl[$s]=(int)$r['c'];
  }
} catch(Throwable $e){}

/** HBL pipeline KPIs */
$hblAwaitInvoice = safe_count($db, "SELECT COUNT(*) c FROM house_bls WHERE status='AWAITING_INVOICE'");
$hblAwaitPay     = safe_count($db, "SELECT COUNT(*) c FROM house_bls WHERE status='AWAITING_PAYMENT'");
$hblReadyDO      = safe_count($db, "SELECT COUNT(*) c FROM house_bls WHERE status='READY_FOR_DO'");
$hblDoIssued     = safe_count($db, "SELECT COUNT(*) c FROM house_bls WHERE status='DO_ISSUED'");
$hblReleased     = safe_count($db, "SELECT COUNT(*) c FROM house_bls WHERE status='RELEASED'");

/** Uninvoiced HBLs */
$uninvoiced = safe_count($db, "
  SELECT COUNT(*) c
  FROM house_bls h
  LEFT JOIN invoices i ON i.house_bl_id=h.id
  WHERE i.id IS NULL
");

/** Outstanding invoices */
$outCount  = safe_count($db, "SELECT COUNT(*) c FROM invoices WHERE status IN ('ISSUED','PART_PAID')");
$outAmount = safe_amount($db, "SELECT COALESCE(SUM(total),0) a FROM invoices WHERE status IN ('ISSUED','PART_PAID')");

/** DO pending (if table exists) */
$dosPending = 0;
try { $dosPending = (int)$db->query("SELECT COUNT(*) c FROM delivery_orders WHERE status='PENDING'")->fetch()['c']; }
catch(Throwable $e){ $dosPending = 0; }

/** Recently released */
$recentReleasedHbl = safe_count($db, "
  SELECT COUNT(*) c FROM house_bls
  WHERE status='RELEASED' AND updated_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
");

$recentReleasedMbl = safe_count($db, "
  SELECT COUNT(*) c FROM master_bls
  WHERE status='RELEASED' AND updated_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
");

/** Recent activity */
$recent = [];
try {
  $recent = $db->query("
    SELECT h.id, h.hbl_no, h.status, h.updated_at, m.mbl_no
    FROM house_bls h
    JOIN master_bls m ON m.id=h.master_bl_id
    ORDER BY h.updated_at DESC
    LIMIT 8
  ")->fetchAll();
} catch(Throwable $e){}

function status_pill_class(string $status): string {
  $s = strtoupper(trim($status));
  return match ($s) {
    'RELEASED' => 'pill pill-green',
    'READY_FOR_DO', 'DO_ISSUED' => 'pill pill-orange',
    'AWAITING_PAYMENT', 'AWAITING_INVOICE' => 'pill pill-amber',
    default => 'pill pill-slate',
  };
}
?>

<style>
 
  .glass-card{
    background:linear-gradient(180deg, rgba(255,255,255,.98), rgba(255,255,255,.95));
    border:1px solid rgba(15,23,42,.07);
    box-shadow:
      0 16px 38px rgba(15,23,42,.07),
      inset 0 1px 0 rgba(255,255,255,.75);
  }

  .section-head{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:1rem;
  }

  .section-kicker{
    font-size:.72rem;
    font-weight:800;
    letter-spacing:.12em;
    text-transform:uppercase;
    color:#f97316;
  }

  .section-title{
    font-size:1.08rem;
    font-weight:800;
    color:#111827;
  }

  .soft-action{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:.5rem;
    padding:.65rem 1rem;
    border-radius:16px;
    font-size:.84rem;
    font-weight:700;
    color:#9a3412;
    background:linear-gradient(180deg, #fff7ed, #ffedd5);
    border:1px solid rgba(249,115,22,.18);
    box-shadow:0 8px 18px rgba(249,115,22,.08);
    transition:all .18s ease;
  }

  .soft-action:hover{
    transform:translateY(-1px);
    background:linear-gradient(180deg, #fff1e7, #fed7aa);
    box-shadow:0 12px 24px rgba(249,115,22,.14);
  }

  .metric-card{
    position:relative;
    overflow:hidden;
    border-radius:24px;
    padding:1rem;
    background:linear-gradient(180deg, rgba(255,255,255,.98), rgba(255,255,255,.94));
    border:1px solid rgba(15,23,42,.07);
    box-shadow:
      0 14px 34px rgba(15,23,42,.06),
      inset 0 1px 0 rgba(255,255,255,.75);
    transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease;
  }

  .metric-card:hover{
    transform:translateY(-3px);
    box-shadow:
      0 18px 42px rgba(15,23,42,.09),
      0 8px 22px rgba(249,115,22,.10);
    border-color:rgba(249,115,22,.16);
  }

  .metric-card::before{
    content:"";
    position:absolute;
    inset:0 auto 0 0;
    width:5px;
    border-radius:24px 0 0 24px;
    background:linear-gradient(180deg, #fb923c, #ea580c);
  }

  .metric-top{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:.75rem;
  }

  .metric-label{
    font-size:.76rem;
    line-height:1.2;
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:.10em;
    color:#64748b;
  }

  .metric-value{
    font-size:2rem;
    line-height:1;
    font-weight:900;
    color:#111827;
    margin-top:.45rem;
  }

  .metric-sub{
    margin-top:.65rem;
    font-size:.77rem;
    color:#64748b;
  }

  .metric-icon{
    height:42px;
    width:42px;
    border-radius:14px;
    display:grid;
    place-items:center;
    font-weight:900;
    font-size:1rem;
    color:#c2410c;
    background:linear-gradient(180deg, #fff7ed, #ffedd5);
    border:1px solid rgba(249,115,22,.14);
    box-shadow:0 10px 22px rgba(249,115,22,.08);
    flex:0 0 auto;
  }

  .metric-link{
    display:inline-flex;
    align-items:center;
    gap:.35rem;
    margin-top:.7rem;
    font-size:.78rem;
    font-weight:800;
    color:#c2410c;
  }

  .metric-link:hover{
    color:#9a3412;
    text-decoration:underline;
  }

  .pipeline-card{
    border-radius:24px;
    padding:1rem;
    background:linear-gradient(180deg, rgba(255,255,255,.98), rgba(255,255,255,.94));
    border:1px solid rgba(15,23,42,.07);
    box-shadow:
      0 14px 34px rgba(15,23,42,.06),
      inset 0 1px 0 rgba(255,255,255,.75);
    transition:all .18s ease;
  }

  .pipeline-card:hover{
    transform:translateY(-2px);
    border-color:rgba(249,115,22,.16);
    box-shadow:
      0 18px 42px rgba(15,23,42,.09),
      0 8px 22px rgba(249,115,22,.10);
  }

  .pipeline-label{
    font-size:.74rem;
    font-weight:800;
    letter-spacing:.10em;
    text-transform:uppercase;
    color:#64748b;
  }

  .pipeline-value{
    font-size:1.9rem;
    line-height:1;
    font-weight:900;
    color:#111827;
    margin-top:.55rem;
  }

  .pipeline-glow-orange{ box-shadow:0 16px 40px rgba(249,115,22,.11), inset 0 1px 0 rgba(255,255,255,.75); }
  .pipeline-glow-amber{ box-shadow:0 16px 40px rgba(245,158,11,.10), inset 0 1px 0 rgba(255,255,255,.75); }

  .money-panel{
    position:relative;
    overflow:hidden;
    border-radius:24px;
    background:
      radial-gradient(circle at top right, rgba(255,247,237,.95), transparent 30%),
      linear-gradient(135deg, #111827 0%, #1f2937 58%, #9a3412 100%);
    border:1px solid rgba(255,255,255,.08);
    box-shadow:0 22px 52px rgba(15,23,42,.16);
  }

  .money-panel::before{
    content:"";
    position:absolute;
    inset:auto -30px -30px auto;
    width:180px;
    height:180px;
    border-radius:999px;
    background:radial-gradient(circle, rgba(255,255,255,.12), transparent 68%);
    pointer-events:none;
  }

  .money-kicker{
    font-size:.72rem;
    font-weight:800;
    letter-spacing:.12em;
    text-transform:uppercase;
    color:#fdba74;
  }

  .money-value{
    color:#fff;
    font-size:2.15rem;
    line-height:1;
    font-weight:900;
    margin-top:.5rem;
  }

  .money-sub{
    color:rgba(255,255,255,.72);
    font-size:.82rem;
    margin-top:.6rem;
  }

  .activity-wrap{
    overflow:hidden;
    border-radius:24px;
    border:1px solid rgba(15,23,42,.08);
    box-shadow:inset 0 1px 0 rgba(255,255,255,.75);
  }

  .activity-table{
    width:100%;
    border-collapse:separate;
    border-spacing:0;
  }

  .activity-table thead th{
    background:linear-gradient(180deg, #fff7ed, #ffedd5);
    color:#7c2d12;
    font-size:.78rem;
    font-weight:800;
    letter-spacing:.06em;
    text-transform:uppercase;
    padding:1rem;
    border-bottom:1px solid rgba(249,115,22,.14);
  }

  .activity-table tbody td{
    padding:1rem;
    color:#1f2937;
    border-top:1px solid rgba(15,23,42,.06);
  }

  .activity-table tbody tr{
    background:#fff;
    transition:background .16s ease, transform .16s ease;
  }

  .activity-table tbody tr:hover{
    background:#fffaf5;
  }

  .pill{
    display:inline-flex;
    align-items:center;
    padding:.34rem .72rem;
    border-radius:999px;
    font-size:.72rem;
    font-weight:800;
    border:1px solid transparent;
  }

  .pill-green{
    background:#ecfdf5;
    color:#047857;
    border-color:#a7f3d0;
  }

  .pill-orange{
    background:#fff7ed;
    color:#c2410c;
    border-color:#fed7aa;
  }

  .pill-amber{
    background:#fffbeb;
    color:#b45309;
    border-color:#fde68a;
  }

  .pill-slate{
    background:#f8fafc;
    color:#475569;
    border-color:#cbd5e1;
  }

  .micro-stat{
    border-radius:20px;
    background:linear-gradient(180deg, #ffffff, #fffaf5);
    border:1px solid rgba(249,115,22,.10);
    box-shadow:0 10px 26px rgba(15,23,42,.05);
  }

  .micro-label{
    font-size:.72rem;
    font-weight:800;
    text-transform:uppercase;
    letter-spacing:.08em;
    color:#64748b;
  }

  .micro-value{
    margin-top:.35rem;
    font-size:1.35rem;
    font-weight:900;
    color:#111827;
  }
</style>

  <div class="space-y-5">

    <!-- TOP GRID -->
    <div class="grid lg:grid-cols-12 gap-5">

      <!-- OPERATIONS OVERVIEW -->
      <div class="glass-card rounded-[28px] p-5 lg:col-span-7">
        <div class="section-head">
          <div>
            <div class="section-kicker">Operations overview</div>
            <div class="section-title mt-1">Shipment and execution pulse</div>
          </div>
          <div class="flex gap-2 flex-wrap">
            <a class="soft-action" href="<?= h($basePath) ?>/shipments" data-nav>Shipments</a>
            <a class="soft-action" href="<?= h($basePath) ?>/hbl" data-nav>HBLs</a>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4 mt-5">
          <div class="metric-card">
            <div class="metric-top">
              <div>
                <div class="metric-label">MBLs received</div>
                <div class="metric-value"><?= (int)$mbl['RECEIVED'] ?></div>
              </div>
              <div class="metric-icon">↘</div>
            </div>
            <div class="metric-sub">Fresh incoming parent shipments ready for operational intake.</div>
            <a class="metric-link" href="<?= h($basePath) ?>/shipments" data-nav>Open register →</a>
          </div>

          <div class="metric-card">
            <div class="metric-top">
              <div>
                <div class="metric-label">MBLs in progress</div>
                <div class="metric-value"><?= (int)$mbl['IN_PROGRESS'] ?></div>
              </div>
              <div class="metric-icon">◔</div>
            </div>
            <div class="metric-sub">Recently released in 7 days: <span class="font-bold text-ink-800"><?= (int)$recentReleasedMbl ?></span></div>
          </div>

          <div class="metric-card">
            <div class="metric-top">
              <div>
                <div class="metric-label">MBLs released</div>
                <div class="metric-value"><?= (int)$mbl['RELEASED'] ?></div>
              </div>
              <div class="metric-icon">✓</div>
            </div>
            <div class="metric-sub">Completed shipment parents that have crossed the release gate.</div>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4 mt-4">
          <div class="metric-card">
            <div class="metric-top">
              <div>
                <div class="metric-label">Uninvoiced HBLs</div>
                <div class="metric-value"><?= (int)$uninvoiced ?></div>
              </div>
              <div class="metric-icon">$
              </div>
            </div>
            <div class="metric-sub">Revenue leakage watchlist requiring billing action.</div>
            <a class="metric-link" href="<?= h($basePath) ?>/hbl?uninvoiced=1" data-nav>Drill down →</a>
          </div>

          <div class="metric-card">
            <div class="metric-top">
              <div>
                <div class="metric-label">DOs pending issuance</div>
                <div class="metric-value"><?= (int)$dosPending ?></div>
              </div>
              <div class="metric-icon">⇢</div>
            </div>
            <div class="metric-sub">Client release blockers still awaiting delivery order issuance.</div>
          </div>

          <div class="metric-card">
            <div class="metric-top">
              <div>
                <div class="metric-label">HBL released · 7 days</div>
                <div class="metric-value"><?= (int)$recentReleasedHbl ?></div>
              </div>
              <div class="metric-icon">★</div>
            </div>
            <div class="metric-sub">A simple signal of recent fulfillment throughput and client wins.</div>
          </div>
        </div>
      </div>

      <!-- CLIENT PIPELINE -->
      <div class="glass-card rounded-[28px] p-5 lg:col-span-5">
        <div class="section-head">
          <div>
            <div class="section-kicker">Client pipeline</div>
            <div class="section-title mt-1">Commercial movement and release readiness</div>
          </div>
        </div>

        <div class="grid grid-cols-2 gap-4 mt-5">
          <a class="pipeline-card pipeline-glow-amber"
             href="<?= h($basePath) ?>/hbl?status=AWAITING_INVOICE" data-nav>
            <div class="pipeline-label">Awaiting invoice</div>
            <div class="pipeline-value"><?= (int)$hblAwaitInvoice ?></div>
          </a>

          <a class="pipeline-card pipeline-glow-amber"
             href="<?= h($basePath) ?>/hbl?status=AWAITING_PAYMENT" data-nav>
            <div class="pipeline-label">Awaiting payment</div>
            <div class="pipeline-value"><?= (int)$hblAwaitPay ?></div>
          </a>

          <a class="pipeline-card pipeline-glow-orange"
             href="<?= h($basePath) ?>/hbl?status=READY_FOR_DO" data-nav>
            <div class="pipeline-label">Ready for DO</div>
            <div class="pipeline-value"><?= (int)$hblReadyDO ?></div>
          </a>

          <a class="pipeline-card pipeline-glow-orange"
             href="<?= h($basePath) ?>/hbl?status=DO_ISSUED" data-nav>
            <div class="pipeline-label">DO issued</div>
            <div class="pipeline-value"><?= (int)$hblDoIssued ?></div>
          </a>
        </div>

        <div class="money-panel mt-5 p-5">
          <div class="grid grid-cols-2 gap-4 items-end">
            <div>
              <div class="money-kicker">Outstanding invoices</div>
              <div class="money-value"><?= (int)$outCount ?></div>
              <div class="money-sub">ISSUED / PART_PAID records still open in the billing cycle.</div>
            </div>

            <div class="text-right">
              <div class="money-kicker">Open amount</div>
              <div class="money-value text-[1.75rem]"><?= h(money_usd($outAmount)) ?></div>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-2 gap-3 mt-4">
          <div class="micro-stat rounded-2xl p-4">
            <div class="micro-label">Released HBLs</div>
            <div class="micro-value"><?= (int)$hblReleased ?></div>
          </div>
          <div class="micro-stat rounded-2xl p-4">
            <div class="micro-label">DO ready queue</div>
            <div class="micro-value"><?= (int)$hblReadyDO ?></div>
          </div>
        </div>
      </div>

      <!-- RECENT ACTIVITY -->
      <div class="glass-card rounded-[28px] p-5 lg:col-span-12">
        <div class="section-head">
          <div>
            <div class="section-kicker">Recent activity</div>
            <div class="section-title mt-1">Latest House BL operational movement</div>
          </div>
          <a class="soft-action" href="<?= h($basePath) ?>/hbl" data-nav>Open HBLs</a>
        </div>

        <div class="activity-wrap mt-5">
          <table class="activity-table">
            <thead>
              <tr>
                <th>HBL</th>
                <th>MBL</th>
                <th>Status</th>
                <th>Updated</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($recent as $r): ?>
                <tr>
                  <td class="font-bold"><?= h($r['hbl_no']) ?></td>
                  <td><?= h($r['mbl_no']) ?></td>
                  <td>
                    <span class="<?= h(status_pill_class((string)$r['status'])) ?>">
                      <?= h($r['status']) ?>
                    </span>
                  </td>
                  <td class="text-ink-500"><?= h($r['updated_at']) ?></td>
                </tr>
              <?php endforeach; ?>

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

  </div>
</div>