<?php /* dashboard/index.php — Advanced Edition */
$sym = setting('currency_symbol','Rs.');

// ── Safe defaults ─────────────────────────────────────────
$todaySales     = is_array($todaySales??null) ? $todaySales : ['gross'=>0,'paid'=>0,'balance'=>0,'invoice_count'=>0];
$todayProfit    = (float)($todayProfit    ?? 0);
$todayExpenses  = (float)($todayExpenses  ?? 0);
$todayPurchases = (float)($todayPurchases ?? 0);
$mtdSales       = (float)($mtdSales       ?? 0);
$mtdChange      = (float)($mtdChange      ?? 0);
$mtdNetProfit   = (float)($mtdNetProfit   ?? 0);
$mtdPurchases   = (float)($mtdPurchases   ?? 0);
$mtdExpenses    = (float)($mtdExpenses    ?? 0);
$lowStockCount  = (int)($lowStockCount  ?? 0);
$outStockCount  = (int)($outStockCount  ?? 0);
$expiredCount   = (int)($expiredCount   ?? 0);
$expiringSoon   = (int)($expiringSoon   ?? 0);
$pendingCheques = (int)($pendingCheques ?? 0);
$overdueCheques = (int)($overdueCheques ?? 0);
$chequePending  = (float)($chequePending ?? 0);
$customerDues   = (float)($customerDues  ?? 0);
$supplierDues   = (float)($supplierDues  ?? 0);
$totalCashBank  = (float)($totalCashBank ?? 0);
$cashBankAccounts = is_array($cashBankAccounts??null) ? $cashBankAccounts : [];
$totalReceivables = (float)($totalReceivables ?? $customerDues);
$totalPayables    = (float)($totalPayables    ?? $supplierDues);
$totalProducts  = (int)($totalProducts  ?? 0);
$totalCustomers = (int)($totalCustomers ?? 0);
$totalSuppliers = (int)($totalSuppliers ?? 0);
$weekTrend      = is_array($weekTrend    ??null)?$weekTrend:[];
$topProducts    = is_array($topProducts  ??null)?$topProducts:[];
$recentSales    = is_array($recentSales  ??null)?$recentSales:[];
$cashierSales   = is_array($cashierSales ??null)?$cashierSales:[];
$todayAtt       = is_array($todayAtt     ??null)?$todayAtt:['present'=>0,'absent'=>0,'late'=>0,'half_day'=>0,'leave'=>0,'total'=>0];
$attList        = is_array($attList      ??null)?$attList:[];

$hr = (int)date('H');
$greeting = $hr < 12 ? 'Good Morning' : ($hr < 17 ? 'Good Afternoon' : 'Good Evening');
$npClr  = $mtdNetProfit >= 0 ? '#16a34a' : '#dc2626';
$npBg   = $mtdNetProfit >= 0 ? '#f0fdf4' : '#fef2f2';
?>

<style>
/* ── Reset & base ───────────────────────────────────────── */
.db-card{border-radius:14px;border:1px solid #e8ecf0;background:#fff;overflow:hidden;
  box-shadow:0 1px 6px rgba(0,0,0,.04);transition:box-shadow .18s,transform .18s}
.db-card:hover{box-shadow:0 6px 24px rgba(0,0,0,.1);transform:translateY(-1px)}

/* ── KPI Tiles ──────────────────────────────────────────── */
.kpi-tile{border-radius:14px;padding:20px 22px;color:#fff;position:relative;overflow:hidden;height:100%}
.kpi-tile::after{content:'';position:absolute;bottom:-20px;right:-20px;width:100px;height:100px;
  border-radius:50%;background:rgba(255,255,255,.08)}
.kpi-tile .kt-icon{width:44px;height:44px;border-radius:12px;background:rgba(255,255,255,.18);
  display:flex;align-items:center;justify-content:center;font-size:1.2rem;margin-bottom:14px}
.kpi-tile .kt-val{font-size:1.7rem;font-weight:900;line-height:1;margin-bottom:5px}
.kpi-tile .kt-lbl{font-size:.7rem;text-transform:uppercase;letter-spacing:.07em;opacity:.8}
.kpi-tile .kt-sub{font-size:.72rem;opacity:.85;margin-top:8px}
.kpi-tile .kt-badge{display:inline-flex;align-items:center;gap:3px;background:rgba(255,255,255,.2);
  border-radius:20px;padding:2px 8px;font-size:.65rem;font-weight:700;margin-top:6px}

/* ── Stat rows ──────────────────────────────────────────── */
.stat-link{display:flex;align-items:center;gap:10px;padding:8px 14px;text-decoration:none;
  border-radius:10px;transition:background .12s;font-size:.82rem}
.stat-link:hover{background:#f8fafc}
.stat-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}

/* ── Alert pills ───────────────────────────────────────── */
.al-pill{border-radius:10px;padding:10px 14px;display:flex;align-items:center;gap:10px;
  text-decoration:none;border:1.5px solid transparent;transition:all .15s}
.al-pill:hover{transform:translateY(-2px);box-shadow:0 4px 14px rgba(0,0,0,.1)}
.al-pill .ap-ico{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;
  justify-content:center;font-size:1rem;flex-shrink:0}
.al-pill .ap-val{font-size:1rem;font-weight:900;line-height:1}
.al-pill .ap-lbl{font-size:.62rem;font-weight:600;margin-top:1px;opacity:.85}

/* ── Sale rows ──────────────────────────────────────────── */
.sl-row{display:flex;align-items:center;gap:10px;padding:8px 16px;
  border-bottom:1px solid #f1f5f9;transition:background .1s;font-size:.8rem}
.sl-row:hover{background:#fafbff}
.sl-row:last-child{border-bottom:none}
.sl-avatar{width:34px;height:34px;border-radius:10px;display:flex;align-items:center;
  justify-content:center;font-size:.72rem;font-weight:700;flex-shrink:0}

/* ── Progress bar ───────────────────────────────────────── */
.prog-bar{height:5px;border-radius:3px;background:#f1f5f9;overflow:hidden;margin-top:4px}
.prog-fill{height:5px;border-radius:3px;transition:width .4s ease}

/* ── Section headers ─────────────────────────────────────── */
.sec-hdr{display:flex;justify-content:space-between;align-items:center;
  padding:10px 16px;border-bottom:1px solid #f1f5f9}
.sec-hdr .sec-title{font-size:.78rem;font-weight:700;color:#334155;
  display:flex;align-items:center;gap:6px}

/* ── Attendance grid ─────────────────────────────────────── */
.att-box{border-radius:10px;padding:10px;text-align:center}
.att-box .av{font-size:1.3rem;font-weight:900;line-height:1}
.att-box .al{font-size:.6rem;font-weight:700;text-transform:uppercase;margin-top:2px}

/* ── Finance snapshot ─────────────────────────────────────── */
.fin-box{border-radius:12px;padding:14px 16px;border:1.5px solid transparent}
.fin-box .fv{font-size:1.3rem;font-weight:900;margin-bottom:4px}
.fin-box .fl{font-size:.65rem;font-weight:700;text-transform:uppercase;opacity:.75;margin-bottom:4px}
.fin-box .fs{font-size:.7rem}

/* ── Live clock ─────────────────────────────────────────── */
#liveClock{font-size:.78rem;color:#94a3b8;font-variant-numeric:tabular-nums}

/* ── Chart tooltip fix ───────────────────────────────────── */
canvas{max-width:100%}

/* ── Page hero header (matches all other pages) ────────── */
.db-hero{
  background:#012d95;
  border-radius:14px;padding:20px 26px;color:#fff;margin-bottom:22px;
  border:1px solid #1e293b;
  box-shadow:0 4px 20px rgba(0,0,0,.15);
}
.db-hero .page-title{font-size:1.25rem;font-weight:800;letter-spacing:-.01em;
  display:flex;align-items:center;gap:10px;margin-bottom:4px}
.db-hero .page-meta{font-size:.78rem;color:#94a3b8;
  display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.db-hero .page-meta .sep{color:#334155}
.db-hero .hero-btn{border-radius:10px;font-weight:600;font-size:.82rem;padding:7px 16px;
  display:inline-flex;align-items:center;gap:6px;text-decoration:none;transition:all .15s}
.db-hero .btn-primary-dash{background:#3b82f6;color:#fff;border:none}
.db-hero .btn-primary-dash:hover{background:##ffff;color:#fff;transform:translateY(-1px)}
.db-hero .btn-ghost{background:transparent;color:#94a3b8;border:1px solid #fff}
.db-hero .btn-ghost:hover{background:#1e293b;color:#fff;border-color:#475569}
#liveClock{color:#94a3b8;font-variant-numeric:tabular-nums}
</style>

<?= flashMessages() ?>

<!-- ══════════════════════════════════════════════════════ -->
<!-- HEADER BAR — matches all page headers                  -->
<!-- ══════════════════════════════════════════════════════ -->
<div class="db-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
    <div>
      <div class="page-title">
        <?= $hr < 12 ? '☀️' : ($hr < 17 ? '🌤' : '🌙') ?>
        <?= $greeting ?>, <?= e(Auth::name()) ?>!
      </div>
      <div class="page-meta">
        <i class="bi bi-calendar3" style="font-size:.7rem"></i>
        <?= date('l, d F Y') ?>
        <span class="sep">·</span>
        <i class="bi bi-shop" style="font-size:.7rem"></i>
        <?= e(setting('shop_name','MJPOS')) ?>
        <span class="sep">·</span>
        <i class="bi bi-clock" style="font-size:.7rem"></i>
        <span id="liveClock"><?= date('H:i:s') ?></span>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/reports/daily" class="hero-btn btn-ghost">
        <i class="bi bi-file-earmark-bar-graph"></i>Daily Report
      </a>
      <a href="<?=APP_URL?>/pos" class="hero-btn btn-primary-dash">
        <i class="bi bi-receipt"></i>Open POS
      </a>
    </div>
  </div>
</div>

<!-- ══════════════════════════════════════════════════════ -->
<!-- ROW 1 — 4 KPI TILES                                    -->
<!-- ══════════════════════════════════════════════════════ -->
<div class="row g-3 mb-4">

  <!-- Today Sales -->
  <div class="col-6 col-xl-3">
    <div class="kpi-tile" style="background:linear-gradient(135deg,#1e40af,#3b82f6)">
      <div class="kt-icon"><i class="bi bi-receipt"></i></div>
      <div class="kt-lbl">Today's Sales</div>
      <div class="kt-val"><?=$sym?><?=number_format((float)$todaySales['gross'],0)?></div>
      <div class="kt-sub">
        <?=(int)$todaySales['invoice_count']?> invoice<?=(int)$todaySales['invoice_count']!==1?'s':''?>
        &nbsp;·&nbsp; Collected <?=$sym?><?=number_format((float)$todaySales['paid'],0)?>
      </div>
      <?php if((float)$todaySales['balance']>0):?>
      <span class="kt-badge">
        <i class="bi bi-clock"></i>Due <?=$sym?><?=number_format((float)$todaySales['balance'],0)?>
      </span>
      <?php endif;?>
    </div>
  </div>

  <!-- Today Profit -->
  <div class="col-6 col-xl-3">
    <div class="kpi-tile" style="background:linear-gradient(135deg,#14532d,#16a34a)">
      <div class="kt-icon"><i class="bi bi-graph-up"></i></div>
      <div class="kt-lbl">Today's Profit</div>
      <div class="kt-val"><?=$sym?><?=number_format($todayProfit,0)?></div>
      <div class="kt-sub">
        Purchases <?=$sym?><?=number_format($todayPurchases,0)?>
        &nbsp;·&nbsp; Expenses <?=$sym?><?=number_format($todayExpenses,0)?>
      </div>
    </div>
  </div>

  <!-- MTD Sales -->
  <div class="col-6 col-xl-3">
    <div class="kpi-tile" style="background:linear-gradient(135deg,#4c1d95,#7c3aed)">
      <div class="kt-icon"><i class="bi bi-bar-chart-fill"></i></div>
      <div class="kt-lbl">MTD Sales</div>
      <div class="kt-val"><?=$sym?><?=number_format($mtdSales,0)?></div>
      <?php if($mtdChange!=0):?>
      <span class="kt-badge">
        <?=$mtdChange>0?'↑':'↓'?><?=abs($mtdChange)?>% vs last month
      </span>
      <?php else:?>
      <div class="kt-sub">→ Same as last month</div>
      <?php endif;?>
    </div>
  </div>

  <!-- Net Profit -->
  <div class="col-6 col-xl-3">
    <div class="kpi-tile" style="background:linear-gradient(135deg,<?=$mtdNetProfit>=0?'#134e4a,#0d9488':'#7f1d1d,#dc2626'?>)">
      <div class="kt-icon">
        <i class="bi <?=$mtdNetProfit>=0?'bi-trending-up':'bi-trending-down'?>"></i>
      </div>
      <div class="kt-lbl">MTD Net <?=$mtdNetProfit>=0?'Profit':'Loss'?></div>
      <div class="kt-val"><?=$sym?><?=number_format(abs($mtdNetProfit),0)?></div>
      <div class="kt-sub">
        Sales <?=$sym?><?=number_format($mtdSales,0)?> −
        Cost <?=$sym?><?=number_format($mtdPurchases+$mtdExpenses,0)?>
      </div>
    </div>
  </div>

</div>

<!-- ══════════════════════════════════════════════════════ -->
<!-- ROW 2 — ALERTS (only show if any exist)                -->
<!-- ══════════════════════════════════════════════════════ -->
<?php
$allAlerts = [
  ['expiry=expired', '#fef2f2','#dc2626', $expiredCount,  'bi-calendar-x-fill',   'Expired Products',  '/stock'],
  ['expiry=soon',    '#fff7ed','#d97706', $expiringSoon,  'bi-clock-fill',         'Expiring ≤30d',     '/stock'],
  ['stock=out',      '#fef2f2','#dc2626', $outStockCount, 'bi-exclamation-octagon-fill','Out of Stock', '/stock'],
  ['stock=low',      '#fff7ed','#f97316', $lowStockCount, 'bi-exclamation-triangle-fill','Low Stock',   '/stock'],
  ['',               '#fef2f2','#dc2626', $overdueCheques,'bi-bank2',              'Overdue Cheques',   '/cheques/pending'],
  ['',               '#eff6ff','#1d4ed8', $pendingCheques,'bi-bank',               'Pending Cheques',   '/cheques/pending'],
  ['',               '#fffbeb','#d97706', $customerDues>0?$sym.number_format($customerDues,0):0,'bi-person-lines-fill','Customer Dues','/finance/credit-book'],
  ['',               '#fef2f2','#dc2626', $supplierDues>0?$sym.number_format($supplierDues,0):0,'bi-truck','Supplier Dues','/suppliers'],
];
$activeAlerts = array_filter($allAlerts, fn($a)=>$a[3]!=0&&$a[3]!='0'&&$a[3]!=$sym.'0');
if(!empty($activeAlerts)):?>
<div class="mb-4">
  <div class="d-flex align-items-center gap-2 mb-2">
    <i class="bi bi-bell-fill text-danger" style="font-size:.85rem"></i>
    <span class="fw-bold small" style="color:#334155">Action Required</span>
    <span class="badge bg-danger rounded-pill" style="font-size:.6rem"><?=count($activeAlerts)?></span>
  </div>
  <div class="row g-2">
    <?php foreach($activeAlerts as[$q,$bg,$clr,$val,$ico,$lbl,$path]):?>
    <div class="col-6 col-md-3">
      <a href="<?=APP_URL?><?=$path?><?=$q?'?'.$q:''?>" class="al-pill h-100"
         style="background:<?=$bg?>;border-color:<?=$clr?>33">
        <div class="ap-ico" style="background:<?=$clr?>18;color:<?=$clr?>">
          <i class="bi <?=$ico?>"></i>
        </div>
        <div>
          <div class="ap-val" style="color:<?=$clr?>"><?=$val?></div>
          <div class="ap-lbl" style="color:<?=$clr?>"><?=$lbl?></div>
        </div>
      </a>
    </div>
    <?php endforeach;?>
  </div>
</div>
<?php endif;?>

<!-- ══════════════════════════════════════════════════════ -->
<!-- ROW 3 — FINANCE SNAPSHOT                               -->
<!-- ══════════════════════════════════════════════════════ -->
<?php if(Auth::can('finance.overview')||Auth::can('accounts.view')):?>
<div class="db-card mb-4">
  <div class="sec-hdr">
    <div class="sec-title">
      <i class="bi bi-graph-up-arrow text-info"></i>
      Accounting Snapshot — <?= date('F Y') ?>
    </div>
    <a href="<?=APP_URL?>/finance/overview" class="btn btn-sm btn-outline-info py-0" style="font-size:.75rem">
      Full Finance <i class="bi bi-arrow-right ms-1"></i>
    </a>
  </div>
  <div class="p-3">
    <div class="row g-3">
      <div class="col-6 col-lg-3">
        <div class="fin-box" style="background:<?=$npBg?>;border-color:<?=$npClr?>33">
          <div class="fl" style="color:<?=$npClr?>"><?=$mtdNetProfit>=0?'Net Profit':'Net Loss'?></div>
          <div class="fv" style="color:<?=$npClr?>"><?=$sym?><?=number_format(abs($mtdNetProfit),0)?></div>
          <div class="fs text-muted">Sales − Purchases − Expenses</div>
        </div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="fin-box" style="background:#eff6ff;border-color:#bfdbfe">
          <div class="fl text-primary">Cash & Bank</div>
          <div class="fv text-primary"><?=$sym?><?=number_format($totalCashBank,0)?></div>
          <?php foreach(array_slice($cashBankAccounts,0,2) as $ac):?>
          <div class="fs text-muted"><?=e($ac['account_name'])?>: <?=$sym?><?=number_format($ac['current_balance'],0)?></div>
          <?php endforeach;?>
        </div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="fin-box" style="background:#fffbeb;border-color:#fde68a">
          <div class="fl text-warning">Receivables</div>
          <div class="fv text-warning"><?=$sym?><?=number_format($totalReceivables,0)?></div>
          <a href="<?=APP_URL?>/finance/credit-book" class="fs text-decoration-none" style="color:#d97706">View Credit Book →</a>
        </div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="fin-box" style="background:#fef2f2;border-color:#fca5a5">
          <div class="fl text-danger">Payables</div>
          <div class="fv text-danger"><?=$sym?><?=number_format($totalPayables,0)?></div>
          <a href="<?=APP_URL?>/suppliers" class="fs text-decoration-none text-danger">View Suppliers →</a>
        </div>
      </div>
    </div>
  </div>
</div>
<?php endif;?>

<!-- ══════════════════════════════════════════════════════ -->
<!-- ROW 4 — CHART + STATS + ATTENDANCE                     -->
<!-- ══════════════════════════════════════════════════════ -->
<div class="row g-3 mb-4">

  <!-- 7-day sales chart -->
  <div class="col-xl-6">
    <div class="db-card h-100">
      <div class="sec-hdr">
        <div class="sec-title">
          <i class="bi bi-bar-chart-line text-primary"></i>Sales — Last 7 Days
        </div>
        <a href="<?=APP_URL?>/sales" class="btn btn-sm btn-outline-secondary py-0" style="font-size:.72rem">View All</a>
      </div>
      <div class="p-3">
        <?php if(empty($weekTrend)):?>
        <div class="text-center text-muted py-4 small">
          <i class="bi bi-bar-chart d-block fs-2 mb-2 opacity-25"></i>No sales data
        </div>
        <?php else:?>
        <canvas id="weekChart" height="110"></canvas>
        <?php endif;?>
      </div>
    </div>
  </div>

  <!-- Stats + Attendance -->
  <div class="col-xl-6">
    <div class="row g-3 h-100">

      <!-- Quick stats -->
      <div class="col-md-6">
        <div class="db-card h-100">
          <div class="sec-hdr">
            <div class="sec-title"><i class="bi bi-lightning-fill text-warning"></i>System Stats</div>
          </div>
          <div class="py-1">
            <?php foreach([
              [APP_URL.'/products', 'bi-box-seam',   '#b45309', 'Products',  $totalProducts],
              [APP_URL.'/customers','bi-people',      '#1d4ed8', 'Customers', $totalCustomers],
              [APP_URL.'/suppliers','bi-truck',       '#16a34a', 'Suppliers', $totalSuppliers],
              [APP_URL.'/stock?stock=out','bi-exclamation-octagon','#dc2626','Out of Stock',$outStockCount],
              [APP_URL.'/stock?expiry=expired','bi-calendar-x','#dc2626','Expired Products',$expiredCount],
            ] as[$url,$ico,$clr,$lbl,$val]):?>
            <a href="<?=$url?>" class="stat-link" style="color:#334155">
              <i class="bi <?=$ico?>" style="color:<?=$clr?>;width:18px;text-align:center"></i>
              <span class="flex-grow-1 small"><?=$lbl?></span>
              <span class="fw-bold small" style="color:<?=$clr?>"><?=$val?></span>
            </a>
            <?php endforeach;?>
          </div>
        </div>
      </div>

      <!-- Today Attendance -->
      <div class="col-md-6">
        <div class="db-card h-100">
          <div class="sec-hdr">
            <div class="sec-title"><i class="bi bi-people text-success"></i>Attendance Today</div>
            <span class="text-muted" style="font-size:.7rem"><?=date('d M')?></span>
          </div>
          <div class="p-2">
            <div class="row g-2 mb-2">
              <?php foreach([
                ['present','#16a34a','Present'],
                ['late',   '#d97706','Late'],
                ['absent', '#dc2626','Absent'],
                ['leave',  '#6366f1','Leave'],
              ] as[$k,$c,$l]):?>
              <div class="col-6">
                <div class="att-box" style="background:<?=$c?>0d;border:1px solid <?=$c?>33">
                  <div class="av" style="color:<?=$c?>"><?=(int)($todayAtt[$k]??0)?></div>
                  <div class="al" style="color:<?=$c?>"><?=$l?></div>
                </div>
              </div>
              <?php endforeach;?>
            </div>
            <?php foreach(array_slice($attList,0,3) as $a):
              $ac=match($a['status']??''){
                'present'=>'#16a34a','late'=>'#d97706','absent'=>'#dc2626',default=>'#94a3b8'
              };
            ?>
            <div class="d-flex align-items-center gap-2 py-1" style="font-size:.7rem;border-top:1px solid #f8fafc">
              <span class="stat-dot" style="background:<?=$ac?>"></span>
              <span class="flex-grow-1 text-truncate"><?=e($a['full_name']??'')?></span>
              <?php if(!empty($a['check_in'])):?>
              <span class="text-muted"><?=date('H:i',strtotime($a['check_in']))?></span>
              <?php endif;?>
            </div>
            <?php endforeach;?>
          </div>
        </div>
      </div>

    </div>
  </div>

</div>

<!-- ══════════════════════════════════════════════════════ -->
<!-- ROW 5 — RECENT SALES + TOP PRODUCTS + CASHIERS        -->
<!-- ══════════════════════════════════════════════════════ -->
<div class="row g-3">

  <!-- Recent Sales -->
  <div class="col-xl-5">
    <div class="db-card">
      <div class="sec-hdr">
        <div class="sec-title"><i class="bi bi-receipt text-primary"></i>Recent Sales</div>
        <a href="<?=APP_URL?>/sales" class="btn btn-sm btn-outline-primary py-0" style="font-size:.72rem">All Sales</a>
      </div>
      <?php foreach($recentSales as $s):
        $pmtClr = match($s['payment_status']??'due'){
          'paid'   =>'#16a34a','partial'=>'#d97706',default=>'#dc2626'
        };
        $init = strtoupper(substr($s['customer_name']??'W',0,1));
        $colors = ['#3b82f6','#8b5cf6','#ec4899','#f59e0b','#10b981','#ef4444'];
        $cc = $colors[abs(crc32($s['customer_name']??''))%count($colors)];
      ?>
      <div class="sl-row">
        <div class="sl-avatar" style="background:<?=$cc?>18;color:<?=$cc?>"><?=$init?></div>
        <div class="flex-grow-1 min-w-0">
          <div class="fw-semibold" style="font-size:.8rem">
            <a href="<?=APP_URL?>/sales/view/<?=$s['id']?>" class="text-decoration-none text-dark">
              <?=e($s['invoice_no'])?>
            </a>
          </div>
          <div class="text-truncate" style="font-size:.67rem;color:#94a3b8">
            <?=e($s['customer_name'])?> · <?=e($s['cashier_name']??'')?>
          </div>
        </div>
        <div class="text-end flex-shrink-0">
          <div class="fw-bold" style="font-size:.82rem"><?=$sym?><?=number_format($s['total'],0)?></div>
          <span style="background:<?=$pmtClr?>12;color:<?=$pmtClr?>;font-size:.58rem;
                       font-weight:700;padding:1px 6px;border-radius:8px">
            <?=ucfirst($s['payment_status']??'—')?>
          </span>
        </div>
      </div>
      <?php endforeach;?>
      <?php if(empty($recentSales)):?>
      <div class="text-center text-muted py-5 small">
        <i class="bi bi-receipt d-block fs-2 mb-2 opacity-25"></i>No sales yet today
      </div>
      <?php endif;?>
    </div>
  </div>

  <!-- Top Products -->
  <div class="col-xl-4">
    <div class="db-card">
      <div class="sec-hdr">
        <div class="sec-title"><i class="bi bi-trophy text-warning"></i>Top Products (30 days)</div>
      </div>
      <div class="p-3">
        <?php
        $maxQty = !empty($topProducts) ? max(array_column($topProducts,'qty_sold')) : 1;
        $tpColors = ['#3b82f6','#8b5cf6','#ec4899','#f59e0b','#10b981'];
        foreach($topProducts as $i=>$p):
          $pct = $maxQty>0 ? round((float)$p['qty_sold']/$maxQty*100) : 0;
          $tc  = $tpColors[$i%count($tpColors)];
        ?>
        <div class="mb-3">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <span style="font-size:.8rem;font-weight:600">
              <span class="me-1" style="color:<?=$tc?>;font-size:.7rem">●</span>
              <?=e(mb_strimwidth($p['product_name'],0,24,'…'))?>
            </span>
            <span style="font-size:.72rem;color:#64748b;white-space:nowrap">
              <?=number_format((float)$p['qty_sold'],0)?> pcs &nbsp;
              <span style="color:<?=$tc?>;font-weight:700"><?=$sym?><?=number_format((float)$p['revenue'],0)?></span>
            </span>
          </div>
          <div class="prog-bar">
            <div class="prog-fill" style="width:<?=$pct?>%;background:<?=$tc?>"></div>
          </div>
        </div>
        <?php endforeach;?>
        <?php if(empty($topProducts)):?>
        <div class="text-center text-muted small py-3">No data yet</div>
        <?php endif;?>
      </div>
    </div>
  </div>

  <!-- Cashiers Today -->
  <div class="col-xl-3">
    <div class="db-card h-100">
      <div class="sec-hdr">
        <div class="sec-title"><i class="bi bi-person-badge text-primary"></i>Cashiers Today</div>
      </div>
      <div class="p-3">
        <?php
        $maxC = !empty($cashierSales) ? max(array_column($cashierSales,'total')) : 1;
        foreach($cashierSales as $cs):
          $pct = $maxC>0 ? round((float)$cs['total']/$maxC*100) : 0;
          $init2 = strtoupper(substr($cs['name'],0,1));
        ?>
        <div class="mb-3">
          <div class="d-flex align-items-center gap-2 mb-1">
            <div style="width:28px;height:28px;border-radius:8px;background:#eff6ff;
                        color:#1d4ed8;display:flex;align-items:center;justify-content:center;
                        font-size:.65rem;font-weight:700;flex-shrink:0">
              <?=$init2?>
            </div>
            <div class="flex-grow-1">
              <div style="font-size:.78rem;font-weight:600"><?=e($cs['name'])?></div>
              <div style="font-size:.65rem;color:#94a3b8">
                <?=$cs['bills']?> bills · <?=$sym?><?=number_format((float)$cs['total'],0)?>
              </div>
            </div>
          </div>
          <div class="prog-bar">
            <div class="prog-fill" style="width:<?=$pct?>%;background:#6366f1"></div>
          </div>
        </div>
        <?php endforeach;?>
        <?php if(empty($cashierSales)):?>
        <div class="text-center text-muted small py-4">
          <i class="bi bi-person-badge d-block fs-3 mb-2 opacity-25"></i>No sales today
        </div>
        <?php endif;?>
      </div>
    </div>
  </div>

</div>

<!-- ══════════════════════════════════════════════════════ -->
<!-- SCRIPTS                                                 -->
<!-- ══════════════════════════════════════════════════════ -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// ── Live clock ──────────────────────────────────────────
setInterval(()=>{
  const n=new Date();
  const cl=document.getElementById('liveClock');
  if(cl) cl.textContent=n.toTimeString().slice(0,8);
},1000);

// ── 7-day chart ──────────────────────────────────────────
(function(){
  const canvas = document.getElementById('weekChart');
  if(!canvas) return;

  const days   = <?= json_encode(array_map(fn($r)=>$r['day'],$weekTrend)) ?>;
  const totals = <?= json_encode(array_map(fn($r)=>(float)$r['total'],$weekTrend)) ?>;
  const counts = <?= json_encode(array_map(fn($r)=>(int)$r['count'],$weekTrend)) ?>;

  const labels = days.map(d=>{
    const dt=new Date(d);
    return dt.toLocaleDateString('en-GB',{weekday:'short',day:'numeric'});
  });

  const maxVal = Math.max(...totals,1);
  const gradient = canvas.getContext('2d').createLinearGradient(0,0,0,200);
  gradient.addColorStop(0,'rgba(59,130,246,.6)');
  gradient.addColorStop(1,'rgba(59,130,246,.05)');

  new Chart(canvas,{
    type:'bar',
    data:{
      labels,
      datasets:[{
        label:'Sales',
        data:totals,
        backgroundColor: totals.map(v =>
          v===maxVal ? '#1d4ed8' : '#3b82f6'),
        borderRadius:8,
        borderSkipped:false,
      }]
    },
    options:{
      plugins:{
        legend:{display:false},
        tooltip:{
          backgroundColor:'#0f172a',
          padding:10,
          callbacks:{
            title:ctx=>'📅 '+ctx[0].label,
            label:ctx=>'  💰 <?=$sym?> '+ctx.parsed.y.toLocaleString()+'  ('+counts[ctx.dataIndex]+' bills)'
          }
        }
      },
      scales:{
        x:{grid:{display:false},ticks:{font:{size:11}}},
        y:{
          beginAtZero:true,
          grid:{color:'#f1f5f9'},
          ticks:{
            callback:v=>'<?=$sym?>'+v.toLocaleString(),
            font:{size:11}
          }
        }
      },
      responsive:true,
      maintainAspectRatio:true,
      animation:{duration:600}
    }
  });
})();
</script>