<?php
// ============================================================
//  MediCore — Dashboard
//  File: dashboard.php
// ============================================================
$page  = 'dashboard';
$title = 'Dashboard';
// The dashboard builds its own hero/greeting header below, so the shared
// thin title bar (includes/header.php's .page-header) would just be a
// redundant second header stacked on top of it — skip it here.
$hidePageHeader = true;
require_once 'includes/header.php';

$cfg   = $settings;
$cur   = $cfg['currency'];
$today = today();

// ── KPI queries ───────────────────────────────────────────────
$todaySales     = db_rows("SELECT * FROM sales     WHERE date = ?", [$today]);
$todayPurchases = db_rows("SELECT * FROM purchases WHERE date = ?", [$today]);

$saleTotal  = array_sum(array_column($todaySales,     'final_price'));
$saleProfit = array_sum(array_column($todaySales,     'approx_profit'));
$purchTotal = array_sum(array_column($todayPurchases, 'final_price'));

$totalCash = (float) db_val(
    "SELECT COALESCE(SUM(IF(type='in',amount,-amount)),0) FROM cash_ledger"
);

$expiredCount = (int) db_val(
    "SELECT COUNT(DISTINCT product_id) FROM purchase_items
      WHERE exp != '' AND exp < DATE_FORMAT(NOW(),'%Y-%m')"
);
$lowStockCount = (int) db_val(
    "SELECT COUNT(*) FROM products
      WHERE is_active=1 AND is_deleted=0 AND stock_pcs > 0
        AND low_stock_alert > 0 AND stock_pcs < low_stock_alert"
);
$outStockCount = (int) db_val(
    "SELECT COUNT(*) FROM products WHERE is_active=1 AND is_deleted=0 AND stock_pcs <= 0"
);
$pendingReqs   = (int) db_val(
    "SELECT COUNT(*) FROM requisitions WHERE status IN ('active','ordered')"
);
$pendingPOs    = (int) db_val(
    "SELECT COUNT(*) FROM purchases WHERE due > 0"
);
$totalProducts  = (int) db_val("SELECT COUNT(*) FROM products  WHERE is_active=1 AND is_deleted=0");
$totalCustomers = (int) db_val("SELECT COUNT(*) FROM customers WHERE id > 1");
$supplierDue    = (float) db_val("SELECT COALESCE(SUM(balance),0) FROM suppliers");
$customerDue    = (float) db_val("SELECT COALESCE(SUM(due),0)     FROM customers");
$customerAdv    = (float) db_val("SELECT COALESCE(SUM(advance),0) FROM customers WHERE id > 1");

// Stock value = sum of (stock_pcs × sale_price)
$stockValue = (float) db_val(
    "SELECT COALESCE(SUM(stock_pcs * sale_price),0) FROM products WHERE is_active=1 AND is_deleted=0"
);

// Monthly totals for comparison
// Rewritten from DATE_FORMAT(date,'%Y-%m') = ? to a plain range
// comparison — wrapping the `date` column in DATE_FORMAT() makes it
// non-sargable, so MySQL can't use idx_date and falls back to a full
// table scan of sales/purchases on every single dashboard load. A
// range on the bare column can use the index. Same fix applied to the
// 6-month chart loop below (was 12 more full-table-scan queries).
$curMonthStart = date('Y-m-01');
$nextMonthStart = date('Y-m-01', strtotime('+1 month'));
$monthSales = (float) db_val(
    "SELECT COALESCE(SUM(final_price),0) FROM sales
      WHERE date >= ? AND date < ?", [$curMonthStart, $nextMonthStart]
);
$monthPurch = (float) db_val(
    "SELECT COALESCE(SUM(final_price),0) FROM purchases
      WHERE date >= ? AND date < ?", [$curMonthStart, $nextMonthStart]
);

// ── Monthly sales chart data (last 6 months) ─────────────────
$months = [];
for ($i = 5; $i >= 0; $i--) {
    $m         = date('Y-m', strtotime("-$i months"));
    $mStart    = date('Y-m-01', strtotime("-$i months"));
    $mNextStart = date('Y-m-01', strtotime("-$i months +1 month"));
    $amt    = (float) db_val(
        "SELECT COALESCE(SUM(final_price),0) FROM sales
          WHERE date >= ? AND date < ?", [$mStart, $mNextStart]
    );
    $profit = (float) db_val(
        "SELECT COALESCE(SUM(approx_profit),0) FROM sales
          WHERE date >= ? AND date < ?", [$mStart, $mNextStart]
    );
    $months[] = [
        'label'  => date('M', strtotime("$m-01")),
        'amount' => $amt,
        'profit' => $profit,
    ];
}

// ── Greeting (purely cosmetic — server local time) ────────────
$hour     = (int) date('G');
$greeting = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
?>

<style>
  /* ── Dashboard-only visual layer — scoped to this page so the
     shared .sc/.sgrid/.al classes used elsewhere in the app (product
     list, requisitions, settings, etc.) are left completely alone. ── */
  /* With the shared .page-header title bar removed for this page
     (hidePageHeader — see includes/header.php), the hero below is the
     very first thing on screen, so it gets a bit of extra top/side
     breathing room via its own margin rather than sitting flush against
     the edge of the content area. */
  .dash-wrap{display:flex;flex-direction:column;gap:18px;padding-top:8px}

  /* Hero / greeting strip */
  .dash-hero{
    position:relative;overflow:hidden;border-radius:var(--r);
    background:linear-gradient(120deg,var(--sidebar) 0%,var(--brand) 60%,var(--brand2) 100%);
    color:#fff;padding:22px 26px;display:flex;align-items:center;
    justify-content:space-between;gap:18px;flex-wrap:wrap;
    box-shadow:0 8px 24px rgba(45,58,140,.22);
  }
  .dash-hero::before{
    content:'';position:absolute;width:280px;height:280px;border-radius:50%;
    background:rgba(255,255,255,.08);top:-140px;right:-60px;pointer-events:none;
  }
  .dash-hero-txt{position:relative;z-index:1}
  .dash-hero-txt h1{font-size:20px;font-weight:700;letter-spacing:-.3px;margin-bottom:4px}
  .dash-hero-txt p{font-size:12.5px;color:rgba(255,255,255,.78)}
  .dash-hero-actions{position:relative;z-index:1;display:flex;gap:8px;flex-wrap:wrap}
  .dash-hbtn{
    display:inline-flex;align-items:center;gap:6px;padding:9px 15px;border-radius:var(--rsm);
    font-size:13px;font-weight:700;cursor:pointer;border:1px solid rgba(255,255,255,.28);
    background:rgba(255,255,255,.14);color:#fff;transition:background .12s,transform .12s;
  }
  .dash-hbtn:hover{background:rgba(255,255,255,.24);transform:translateY(-1px)}
  .dash-hbtn.solid{background:#fff;color:var(--brand);border-color:#fff}
  .dash-hbtn.solid:hover{background:#f2f3fb}

  /* KPI cards (primary) — every card is clickable now, so cursor +
     hover-lift apply unconditionally rather than via a .clickable
     modifier class. */
  .dash-kgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px}
  .dash-kpi{
    background:var(--surface);border:1px solid var(--border);border-radius:var(--r);
    padding:16px 18px;display:flex;flex-direction:column;gap:10px;cursor:pointer;
    box-shadow:var(--sh);transition:box-shadow .15s,transform .15s;position:relative;overflow:hidden;
  }
  .dash-kpi:hover{box-shadow:var(--shmd);transform:translateY(-2px)}
  .dash-kpi-top{display:flex;align-items:flex-start;justify-content:space-between;gap:8px}
  /* min-width:0 lets this flex item shrink below its content's natural
     width — without it, a long number just grows the row instead of
     ever registering as "too wide", so the JS auto-fit below would
     never have anything to measure against. */
  .dash-kpi-top .dash-kpi-txt{flex:1;min-width:0}
  .dash-kpi-ic{
    width:38px;height:38px;border-radius:11px;display:flex;align-items:center;justify-content:center;
    font-size:17px;flex-shrink:0;
  }
  .dash-kpi-lbl{font-size:12px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.4px}
  .dash-kpi-val{
    font-size:25px;font-weight:700;letter-spacing:-.5px;line-height:1.1;
    white-space:nowrap;overflow:hidden;
  }
  .dash-kpi-sub{font-size:11.5px;color:var(--text3)}

  /* Compact stat strip (secondary metrics) — same "all clickable" rule */
  .dash-sgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px}
  .dash-stat{
    background:var(--surface);border:1px solid var(--border);border-radius:var(--rsm);
    padding:11px 13px;box-shadow:var(--sh);transition:box-shadow .15s,transform .15s;cursor:pointer;
  }
  .dash-stat:hover{box-shadow:var(--shmd);transform:translateY(-1px)}
  .dash-stat-lbl{font-size:10.5px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.4px;margin-bottom:5px}
  .dash-stat-val{font-size:17px;font-weight:700;letter-spacing:-.3px;white-space:nowrap;overflow:hidden}
  .dash-stat-sub{font-size:10.5px;color:var(--text3);margin-top:2px}

  /* Alert chips */
  .dash-agrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:10px}
  .dash-alert{
    display:flex;align-items:center;gap:10px;padding:11px 13px;border-radius:var(--rsm);
    font-size:12.5px;font-weight:600;border:1px solid transparent;transition:transform .12s,box-shadow .12s;
  }
  .dash-alert.clickable{cursor:pointer}
  .dash-alert.clickable:hover{transform:translateY(-1px);box-shadow:var(--sh)}
  .dash-alert .aic{
    width:30px;height:30px;border-radius:9px;display:flex;align-items:center;justify-content:center;
    font-size:14px;flex-shrink:0;
  }
  .dash-alert .atxt{flex:1;min-width:0}
  .dash-alert .achev{opacity:.5;font-size:13px;flex-shrink:0}
  .dash-alert.ok    { background:var(--accent-xlight); color:#064e3b; }
  .dash-alert.ok    .aic{background:rgba(26,158,110,.16)}
  .dash-alert.warn  { background:var(--warn-light); color:#78350f; }
  .dash-alert.warn  .aic{background:rgba(224,123,0,.16)}
  .dash-alert.danger{ background:var(--danger-light); color:#7f1d1d; }
  .dash-alert.danger .aic{background:rgba(211,47,47,.14)}
  .dash-alert.info   { background:var(--brand-xlight); color:var(--brand); }
  .dash-alert.info   .aic{background:rgba(61,78,179,.14)}

  /* Chart + recent sales cards */
  .dash-cardgrid{display:grid;grid-template-columns:1.2fr 1fr;gap:14px}
  @media (max-width:980px){ .dash-cardgrid{grid-template-columns:1fr} }
  .dash-card{
    background:var(--surface);border:1px solid var(--border);border-radius:var(--r);
    padding:16px;box-shadow:var(--sh);
  }
  .dash-card-hd{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
  .dash-card-hd .tt{font-size:14px;font-weight:700;display:flex;align-items:center;gap:7px}
  .dash-card-hd .lnk{
    font-size:11.5px;font-weight:700;color:var(--brand);background:var(--brand-xlight);
    padding:4px 10px;border-radius:20px;
  }
  .dash-card-hd .lnk:hover{background:var(--brand-light)}

  @media (max-width:640px){
    .dash-hero{flex-direction:column;align-items:flex-start}
  }
</style>

<div class="dash-wrap">

  <!-- ── Hero / greeting ── -->
  <div class="dash-hero">
    <div class="dash-hero-txt">
      <h1><?= htmlspecialchars($greeting) ?>, <?= htmlspecialchars(current_user_name()) ?> 👋</h1>
      <p><?= date('l, F j, Y') ?> · Here's how <?= htmlspecialchars($cfg['shop_name']) ?> is doing today.</p>
    </div>
    <div class="dash-hero-actions">
      <a class="dash-hbtn solid" href="sale/entry.php">🛒 New Sale</a>
      <a class="dash-hbtn" href="purchase/entry.php">📦 New Purchase</a>
    </div>
  </div>

  <!-- ── Row 1 — Primary KPIs ── -->
  <div class="dash-kgrid">

    <div class="dash-kpi" style="border-bottom:3px solid var(--accent)"
         onclick="location='sale/list.php'" title="View Sale Record">
      <div class="dash-kpi-top">
        <div class="dash-kpi-txt">
          <div class="dash-kpi-lbl">Today's Sales</div>
          <div class="dash-kpi-val"><?= $cur . number_format($saleTotal, 2) ?></div>
        </div>
        <div class="dash-kpi-ic" style="background:var(--accent-xlight);color:var(--accent)">💰</div>
      </div>
      <div class="dash-kpi-sub"><?= count($todaySales) ?> invoice(s) today</div>
    </div>

    <div class="dash-kpi" style="border-bottom:3px solid var(--brand)"
         onclick="location='purchase/list.php'" title="View Purchase Record">
      <div class="dash-kpi-top">
        <div class="dash-kpi-txt">
          <div class="dash-kpi-lbl">Today's Purchase</div>
          <div class="dash-kpi-val" style="color:var(--brand)"><?= $cur . number_format($purchTotal, 2) ?></div>
        </div>
        <div class="dash-kpi-ic" style="background:var(--brand-xlight);color:var(--brand)">📦</div>
      </div>
      <div class="dash-kpi-sub"><?= count($todayPurchases) ?> PO(s) today</div>
    </div>

    <?php if (can_view_profit()): ?>
    <div class="dash-kpi" style="border-bottom:3px solid <?= $saleProfit >= 0 ? 'var(--accent)' : 'var(--danger)' ?>"
         onclick="location='accounting/profit.php'" title="View Profit Report">
      <div class="dash-kpi-top">
        <div class="dash-kpi-txt">
          <div class="dash-kpi-lbl">Today's Profit</div>
          <div class="dash-kpi-val" style="color:<?= $saleProfit >= 0 ? 'var(--accent)' : 'var(--danger)' ?>">
            <?= $cur . number_format($saleProfit, 2) ?>
          </div>
        </div>
        <div class="dash-kpi-ic" style="background:<?= $saleProfit >= 0 ? 'var(--accent-xlight)' : 'var(--danger-light)' ?>;color:<?= $saleProfit >= 0 ? 'var(--accent)' : 'var(--danger)' ?>">📈</div>
      </div>
      <div class="dash-kpi-sub">Approx., based on today's sales</div>
    </div>
    <?php endif; ?>

    <div class="dash-kpi" style="border-bottom:3px solid var(--warn)"
         onclick="location='accounting/cash.php'" title="View Cash Balance">
      <div class="dash-kpi-top">
        <div class="dash-kpi-txt">
          <div class="dash-kpi-lbl">Cash Balance</div>
          <div class="dash-kpi-val" style="color:var(--warn)"><?= $cur . number_format($totalCash, 2) ?></div>
        </div>
        <div class="dash-kpi-ic" style="background:var(--warn-light);color:var(--warn)">💵</div>
      </div>
      <div class="dash-kpi-sub">All accounts combined</div>
    </div>

  </div>

  <!-- ── Row 2 — Compact stat strip ── -->
  <div class="dash-sgrid">

    <div class="dash-stat" onclick="location='product/list.php'" title="View Product List">
      <div class="dash-stat-lbl">Total Products</div>
      <div class="dash-stat-val"><?= $totalProducts ?></div>
    </div>

    <div class="dash-stat" onclick="location='customer/list.php'" title="View Customer List">
      <div class="dash-stat-lbl">Total Customers</div>
      <div class="dash-stat-val"><?= $totalCustomers ?></div>
    </div>

    <div class="dash-stat" onclick="location='customer/list.php'" title="View Customer List">
      <div class="dash-stat-lbl">Customer Due</div>
      <div class="dash-stat-val" style="color:var(--danger)"><?= $cur . number_format($customerDue, 2) ?></div>
      <div class="dash-stat-sub">Outstanding</div>
    </div>

    <div class="dash-stat" onclick="location='supplier/list.php'" title="View Supplier List">
      <div class="dash-stat-lbl">Supplier Payable</div>
      <div class="dash-stat-val" style="color:var(--brand)"><?= $cur . number_format($supplierDue, 2) ?></div>
      <div class="dash-stat-sub">Outstanding</div>
    </div>

    <div class="dash-stat" onclick="location='product/list.php'" title="View Product List">
      <div class="dash-stat-lbl">Total Stock Value</div>
      <div class="dash-stat-val" id="dash-stock-value" style="color:var(--teal)"><?= $cur . number_format($stockValue, 0) ?></div>
      <div class="dash-stat-sub">All active products</div>
    </div>

    <div class="dash-stat" onclick="location='customer/list.php'" title="View Customer List">
      <div class="dash-stat-lbl">Customer Advance</div>
      <div class="dash-stat-val" style="color:var(--accent)"><?= $cur . number_format($customerAdv, 2) ?></div>
      <div class="dash-stat-sub">Pre-paid balance</div>
    </div>

    <div class="dash-stat" onclick="location='purchase/list.php'" title="View Purchase Record">
      <div class="dash-stat-lbl">Pending PO Dues</div>
      <div class="dash-stat-val" style="color:var(--warn)"><?= $pendingPOs ?></div>
      <div class="dash-stat-sub">Purchase orders with due</div>
    </div>

    <div class="dash-stat" onclick="location='sale/list.php'" title="View Sale Record">
      <div class="dash-stat-lbl">This Month Sales</div>
      <div class="dash-stat-val" style="color:var(--purple)"><?= $cur . number_format($monthSales, 0) ?></div>
      <div class="dash-stat-sub">Purchase: <?= $cur . number_format($monthPurch, 0) ?></div>
    </div>

  </div>

  <!-- ── Row 3 — Alerts ── -->
  <div class="dash-agrid">

    <?php if ($expiredCount > 0): ?>
    <div class="dash-alert danger clickable" onclick="location='product/expired.php'">
      <div class="aic">⏰</div>
      <div class="atxt"><strong><?= $expiredCount ?></strong> expired product batch(es) — click to review</div>
      <div class="achev">›</div>
    </div>
    <?php else: ?>
    <div class="dash-alert ok"><div class="aic">✅</div><div class="atxt">No expired products</div></div>
    <?php endif; ?>

    <div id="dash-lowstock-widget">
    <?php if ($lowStockCount > 0): ?>
    <div class="dash-alert warn clickable" onclick="location='product/list.php?stock=low'">
      <div class="aic">⚠</div>
      <div class="atxt"><strong><?= $lowStockCount ?></strong> product(s) low on stock</div>
      <div class="achev">›</div>
    </div>
    <?php else: ?>
    <div class="dash-alert ok"><div class="aic">✅</div><div class="atxt">Stock levels OK</div></div>
    <?php endif; ?>
    </div>

    <div id="dash-outstock-widget">
    <?php if ($outStockCount > 0): ?>
    <div class="dash-alert danger clickable" onclick="location='product/list.php?stock=out'">
      <div class="aic">🚫</div>
      <div class="atxt"><strong><?= $outStockCount ?></strong> product(s) out of stock</div>
      <div class="achev">›</div>
    </div>
    <?php else: ?>
    <div class="dash-alert ok"><div class="aic">✅</div><div class="atxt">No out-of-stock items</div></div>
    <?php endif; ?>
    </div>

  </div>

  <!-- ── Pending Requisitions ── -->
  <?php if ($pendingReqs > 0): ?>
  <div class="dash-agrid" style="grid-template-columns:repeat(auto-fit,minmax(280px,1fr))">
    <div class="dash-alert warn clickable" onclick="location='product/req-record.php'">
      <div class="aic">📝</div>
      <div class="atxt"><strong><?= $pendingReqs ?></strong> pending requisition(s) awaiting purchase order</div>
      <div class="achev">›</div>
    </div>
    <div class="dash-alert info clickable" onclick="location='product/smart-requisition.php'">
      <div class="aic">🤖</div>
      <div class="atxt">Smart Requisition available — view priority list</div>
      <div class="achev">›</div>
    </div>
  </div>
  <?php endif; ?>

  <!-- ── Row 4 — Chart + Recent Sales ── -->
  <div class="dash-cardgrid">

    <div class="dash-card">
      <div class="dash-card-hd">
        <div class="tt">📊 <?= can_view_profit() ? '6-Month Sales vs Profit' : '6-Month Sales' ?></div>
      </div>
      <canvas id="salesChart" height="170"></canvas>
    </div>

    <div class="dash-card">
      <div class="dash-card-hd">
        <div class="tt">🧾 Today's Sales</div>
        <a href="sale/list.php" class="lnk">View all →</a>
      </div>
      <?php if ($todaySales): ?>
      <div class="tw"><table>
        <thead><tr>
          <th>Invoice</th><th>Customer</th><th>Amount</th><th>Status</th>
        </tr></thead>
        <tbody>
          <?php foreach (array_slice($todaySales, 0, 8) as $s): ?>
          <tr>
            <td class="mono" style="color:var(--brand);font-weight:700">
              <?= htmlspecialchars($s['invoice']) ?>
            </td>
            <td><?= htmlspecialchars($s['customer_name']) ?></td>
            <td class="mono"><?= $cur . number_format($s['final_price'], 2) ?></td>
            <td>
              <?php
                $bc = match($s['status']) {
                  'Paid'    => 'background:#d4f0e6;color:var(--accent)',
                  'Partial' => 'background:#fff3dc;color:var(--warn)',
                  default   => 'background:#fde8e8;color:var(--danger)',
                };
              ?>
              <span class="badge" style="<?= $bc ?>"><?= $s['status'] ?></span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table></div>
      <?php else: ?>
      <div class="empty-state">No sales today</div>
      <?php endif; ?>
    </div>

  </div>

</div>

<!-- ── Chart.js ──────────────────────────────────── -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('salesChart').getContext('2d'), {
  type: 'bar',
  data: {
    labels: <?= json_encode(array_column($months, 'label'))  ?>,
    datasets: [
      {
        label: 'Sales',
        data:  <?= json_encode(array_column($months, 'amount')) ?>,
        backgroundColor: 'rgba(45,58,140,0.75)',
        hoverBackgroundColor: 'rgba(45,58,140,0.95)',
        borderRadius: 6,
        maxBarThickness: 34,
        order: 2
      },
      <?php if (can_view_profit()): ?>
      {
        label: 'Profit',
        data:  <?= json_encode(array_column($months, 'profit')) ?>,
        type:  'line',
        borderColor: 'rgba(26,158,110,1)',
        backgroundColor: 'rgba(26,158,110,0.12)',
        borderWidth: 2.5,
        pointRadius: 3,
        pointBackgroundColor: 'rgba(26,158,110,1)',
        fill: true,
        tension: 0.35,
        order: 1
      }
      <?php endif; ?>
    ]
  },
  options: {
    plugins: { legend: { labels: { font: { size: 10.5 }, usePointStyle: true, boxWidth: 8 } } },
    scales: {
      y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,.05)' }, ticks: { font: { size: 10 } } },
      x: { grid: { display: false }, ticks: { font: { size: 10 } } }
    }
  }
});
</script>

<!-- ── Live stock widgets ────────────────────────────────────────
     assets/stock-sync.js polls in the background and fires this
     event every ~2-3s; rebuild the two alert widgets + stock value
     card in place so another terminal's sale/purchase shows up here
     without a reload. Mirrors the exact PHP conditionals above so
     the two never disagree. -->
<!-- ── KPI value auto-fit ─────────────────────────────────────────
     Currency/quantity figures vary a lot in width (৳500.00 vs
     ৳12,45,000.00) and the boxes are a fixed grid size, so instead of
     wrapping or spilling out of the card, each .dash-kpi-val/.dash-stat-val
     shrinks its own font-size just enough to fit on one line. Re-run
     on resize (grid column widths change) and after the live
     stock-sync update below touches #dash-stock-value's text. -->
<script>
function fitKpiValue(el) {
  if (!el) return;
  if (!el.dataset.maxFont) {
    el.dataset.maxFont = parseFloat(getComputedStyle(el).fontSize);
  }
  const maxSize = parseFloat(el.dataset.maxFont);
  const minSize = 11;
  let size = maxSize;
  el.style.fontSize = size + 'px';
  while (el.scrollWidth > el.clientWidth + 1 && size > minSize) {
    size -= 1;
    el.style.fontSize = size + 'px';
  }
}
function fitAllKpiValues() {
  document.querySelectorAll('.dash-kpi-val, .dash-stat-val').forEach(fitKpiValue);
}
document.addEventListener('DOMContentLoaded', fitAllKpiValues);
let kpiResizeTmr = null;
window.addEventListener('resize', () => {
  clearTimeout(kpiResizeTmr);
  kpiResizeTmr = setTimeout(fitAllKpiValues, 150);
});
</script>

<script>
const CUR = '<?= addslashes($cur) ?>';

function fmtWhole(n) {
  return Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

window.addEventListener('medi:stock-sync', (e) => {
  const { lowStockCount, outOfStockCount, stockValue } = e.detail;

  if (typeof stockValue === 'number') {
    const el = document.getElementById('dash-stock-value');
    if (el) { el.textContent = CUR + fmtWhole(stockValue); fitKpiValue(el); }
  }

  if (typeof lowStockCount === 'number') {
    const el = document.getElementById('dash-lowstock-widget');
    if (el) {
      el.innerHTML = lowStockCount > 0
        ? `<div class="dash-alert warn clickable" onclick="location='product/list.php?stock=low'">
             <div class="aic">⚠</div>
             <div class="atxt"><strong>${lowStockCount}</strong> product(s) low on stock</div>
             <div class="achev">›</div>
           </div>`
        : `<div class="dash-alert ok"><div class="aic">✅</div><div class="atxt">Stock levels OK</div></div>`;
    }
  }

  if (typeof outOfStockCount === 'number') {
    const el = document.getElementById('dash-outstock-widget');
    if (el) {
      el.innerHTML = outOfStockCount > 0
        ? `<div class="dash-alert danger clickable" onclick="location='product/list.php?stock=out'">
             <div class="aic">🚫</div>
             <div class="atxt"><strong>${outOfStockCount}</strong> product(s) out of stock</div>
             <div class="achev">›</div>
           </div>`
        : `<div class="dash-alert ok"><div class="aic">✅</div><div class="atxt">No out-of-stock items</div></div>`;
    }
  }
});
</script>

<?php require_once 'includes/footer.php'; ?>
