<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");

$zdb       = $_SESSION["zdbyear_" . $dbname];
$compcd    = $_SESSION["comp_" . $dbname];
$usertype  = (int)($_SESSION["usertype_" . $dbname] ?? 0);
$agentcode = (int)($_SESSION["agentcode_" . $dbname] ?? 0);
mysqli_select_db($conn, $zdb);

// Staff (salesman) logins only see their own Order Pipeline entries;
// Admin/Manager see everything, same scoping already used in sale.php/saleorder.php.
$soCond   = ($usertype === 3 && $agentcode > 0) ? " WHERE `salesman`='$agentcode'" : '';
$soCondAnd = ($usertype === 3 && $agentcode > 0) ? " AND `salesman`='$agentcode'" : '';

function qs($conn,$sql){ try { $r=mysqli_query($conn,$sql); if(!$r) return 0; $row=mysqli_fetch_row($r); return $row?($row[0]??0):0; } catch(Exception $e){ return 0; } }
function qf($conn,$sql){ return (float)qs($conn,$sql); }

// ── Masters ──────────────────────────────────────────────────────────────
$cntCust = qs($conn,"SELECT COUNT(*) FROM accmast WHERE grpcode='010' AND accode>50");
$cntSupp = qs($conn,"SELECT COUNT(*) FROM accmast WHERE grpcode='009' AND accode>50");
$cntProd = qs($conn,"SELECT COUNT(*) FROM product");
$cntGodown = qs($conn,"SELECT COUNT(*) FROM godown");

// ── Sales & Purchases ────────────────────────────────────────────────────
$cntSale = qs($conn,"SELECT COUNT(*) FROM sale" . $soCond);
$saleAmt = qf($conn,"SELECT SUM(totamt) FROM sale" . $soCond);
$cntPur  = qs($conn,"SELECT COUNT(*) FROM purchentry");
$purAmt  = qf($conn,"SELECT SUM(netamount) FROM purchentry");
$cntPEX  = qs($conn,"SELECT COUNT(*) FROM purchaseimport");
$pexAmt  = qf($conn,"SELECT SUM(netamount) FROM purchaseimport");
$totalPurAmt = $purAmt + $pexAmt;
$totalPurCnt = $cntPur + $cntPEX;

// ── Sale Order → Dispatch → Invoice pipeline ────────────────────────────
$cntSO         = qs($conn,"SELECT COUNT(*) FROM saleorder" . $soCond);
$soPending     = qs($conn,"SELECT COUNT(*) FROM saleorder WHERE (dispatchdate IS NULL OR dispatchdate='0000-00-00')" . $soCondAnd);
$soDispatched  = qs($conn,"SELECT COUNT(*) FROM saleorder WHERE (dispatchdate IS NOT NULL AND dispatchdate!='0000-00-00')" . $soCondAnd);
$soPendingInv  = qs($conn,"SELECT COUNT(*) FROM saleorder WHERE (dispatchdate IS NOT NULL AND dispatchdate!='0000-00-00') AND (invoiceno=0 OR invoiceno IS NULL)" . $soCondAnd);
$soInvoiced    = qs($conn,"SELECT COUNT(*) FROM saleorder WHERE invoiceno>0" . $soCondAnd);

// ── Stock movement counts ────────────────────────────────────────────────
$cntInward  = qs($conn,"SELECT COUNT(*) FROM inward");
$cntOutward = qs($conn,"SELECT COUNT(*) FROM outward");
$cntDamage  = qs($conn,"SELECT COUNT(*) FROM damage");

// ── Stock quantity (from transacn, signed IN/OUT) ───────────────────────
$stockQty = qf($conn,"SELECT SUM(qty) FROM transacn");

// ── Stock by Godown (dynamic — pulled from godown master, not hardcoded) ──
$stockByGodown = [];
$sgq = mysqli_query($conn, "SELECT g.code, g.name, COALESCE(SUM(t.qty),0) AS qty
    FROM godown g
    LEFT JOIN transacn t ON t.godown = g.code
    GROUP BY g.code, g.name
    ORDER BY qty DESC");
if ($sgq) while ($r = mysqli_fetch_assoc($sgq)) $stockByGodown[] = $r;

// ── Bank & Cash balances (opening bal, signed by Dr/Cr, + all actran movement) ─
$bankBal = qf($conn,"SELECT SUM((CASE WHEN a.dc='D' THEN -a.openbal ELSE a.openbal END) + COALESCE(t.amt,0))
    FROM accmast a LEFT JOIN (SELECT accode, SUM(amount) amt FROM actran GROUP BY accode) t ON t.accode=a.accode
    WHERE a.grpcode='001'");
$cashBal = qf($conn,"SELECT SUM((CASE WHEN a.dc='D' THEN -a.openbal ELSE a.openbal END) + COALESCE(t.amt,0))
    FROM accmast a LEFT JOIN (SELECT accode, SUM(amount) amt FROM actran GROUP BY accode) t ON t.accode=a.accode
    WHERE a.grpcode='002'");

// ── Receivable / Payable ─────────────────────────────────────────────────
$totalPaidByCust = qf($conn,"SELECT SUM(amount) FROM actran WHERE source IN ('BR','CR') AND grpcode='010' AND amount > 0");
$totalReceivable = $saleAmt - $totalPaidByCust;
$totalPaidToSupp = qf($conn,"SELECT SUM(amount) FROM actran WHERE source IN ('BP','CP') AND grpcode='009' AND amount > 0");
$totalPayable    = $totalPurAmt - $totalPaidToSupp;

// ── 6-month trends ────────────────────────────────────────────────────────
$saleMonths=[]; $purMonths=[];
$msale = mysqli_query($conn,"SELECT DATE_FORMAT(vouchdt,'%b %y') AS mo, DATE_FORMAT(vouchdt,'%Y-%m') AS ym, SUM(totamt) AS amt FROM sale WHERE vouchdt>=DATE_SUB(CURDATE(),INTERVAL 6 MONTH) GROUP BY ym ORDER BY ym");
if ($msale) while($r=mysqli_fetch_assoc($msale)) $saleMonths[]=$r;
$mpur = mysqli_query($conn,"SELECT mo, ym, SUM(amt) AS amt FROM (
    SELECT DATE_FORMAT(vouchdt,'%b %y') AS mo, DATE_FORMAT(vouchdt,'%Y-%m') AS ym, netamount AS amt FROM purchentry WHERE vouchdt>=DATE_SUB(CURDATE(),INTERVAL 6 MONTH)
    UNION ALL
    SELECT DATE_FORMAT(vouchdt,'%b %y') AS mo, DATE_FORMAT(vouchdt,'%Y-%m') AS ym, netamount AS amt FROM purchaseimport WHERE vouchdt>=DATE_SUB(CURDATE(),INTERVAL 6 MONTH)
) pu GROUP BY ym ORDER BY ym");
if ($mpur) while($r=mysqli_fetch_assoc($mpur)) $purMonths[]=$r;

// ── Sales vs Collection — Last 6 Months (canonical month list built in PHP
//    so both series share the exact same x-axis, even if one has a month
//    with zero activity that the other doesn't) ─────────────────────────────
$svcLabels = []; $svcYm = [];
for ($i = 5; $i >= 0; $i--) {
    $svcYm[]     = date('Y-m', strtotime("-$i months"));
    $svcLabels[] = date('M y', strtotime("-$i months"));
}
$svcSalesByYm = array_fill_keys($svcYm, 0.0);
$svcCollByYm  = array_fill_keys($svcYm, 0.0);

// Sales = customer-side postings in actran (grpcode='010'). Every invoice
// (Sale + Sale GST) debits the customer, and that leg is stored negative in
// this schema (see sale.php: $dr = $totamt * -1), so amount<0 isolates the
// invoicing postings — flip sign back to positive for display.
$svcSaleQ = mysqli_query($conn, "SELECT DATE_FORMAT(vouchdt,'%Y-%m') AS ym, SUM(-amount) AS amt
    FROM actran WHERE grpcode='010' AND amount<0
      AND vouchdt>=DATE_SUB(CURDATE(),INTERVAL 6 MONTH)
    GROUP BY ym");
if ($svcSaleQ) while ($r = mysqli_fetch_assoc($svcSaleQ)) { if (isset($svcSalesByYm[$r['ym']])) $svcSalesByYm[$r['ym']] = (float)$r['amt']; }

// Collection = actual money received from customers (actran, grpcode='010', amount>0)
$svcCollQ = mysqli_query($conn, "SELECT DATE_FORMAT(vouchdt,'%Y-%m') AS ym, SUM(amount) AS amt
    FROM actran WHERE grpcode='010' AND amount>0
      AND vouchdt>=DATE_SUB(CURDATE(),INTERVAL 6 MONTH)
    GROUP BY ym");
if ($svcCollQ) while ($r = mysqli_fetch_assoc($svcCollQ)) { if (isset($svcCollByYm[$r['ym']])) $svcCollByYm[$r['ym']] = (float)$r['amt']; }

$svcSalesData = array_values($svcSalesByYm);
$svcCollData  = array_values($svcCollByYm);

// ── Expense Trend — Last 6 Months (same canonical-month-list pattern as
//    Sales vs Collection above, so a month with zero expense still shows
//    as a 0 point instead of being skipped) ─────────────────────────────
$expYm = []; $expLabels = [];
for ($i = 5; $i >= 0; $i--) {
    $expYm[]     = date('Y-m', strtotime("-$i months"));
    $expLabels[] = date('M y', strtotime("-$i months"));
}
$expByYm = array_fill_keys($expYm, 0.0);
$expQ = mysqli_query($conn, "SELECT DATE_FORMAT(vouchdt,'%Y-%m') AS ym, SUM(-amount) AS amt
    FROM actran WHERE grpcode='012'
      AND vouchdt>=DATE_SUB(CURDATE(),INTERVAL 6 MONTH)
    GROUP BY ym");
if ($expQ) while ($r = mysqli_fetch_assoc($expQ)) { if (isset($expByYm[$r['ym']])) $expByYm[$r['ym']] = (float)$r['amt']; }
$expData = array_values($expByYm);

// ── Recent Sales ──────────────────────────────────────────────────────────
$recentSale=[];
$rs = mysqli_query($conn,"SELECT s.vouchno,s.vouchdt,s.totamt,c.name AS cname FROM sale s LEFT JOIN accmast c ON c.accode=s.customer ORDER BY s.vouchno DESC LIMIT 6");
if ($rs) while($r=mysqli_fetch_assoc($rs)) $recentSale[]=$r;

// ── Recent Purchases ──────────────────────────────────────────────────────
$recentPur=[];
$rp = mysqli_query($conn,"SELECT p.vouchno,p.vouchdt,p.netamount,s.name AS sname FROM purchentry p LEFT JOIN accmast s ON s.accode=p.supplier ORDER BY p.vouchno DESC LIMIT 6");
if ($rp) while($r=mysqli_fetch_assoc($rp)) $recentPur[]=$r;

// ── Recent Purchase Imports ────────────────────────────────────────────────
$recentPEX=[];
$rpx = mysqli_query($conn,"SELECT p.vouchno,p.vouchdt,p.netamount,s.name AS sname FROM purchaseimport p LEFT JOIN accmast s ON s.accode=p.supplier ORDER BY p.vouchno DESC LIMIT 6");
if ($rpx) while($r=mysqli_fetch_assoc($rpx)) $recentPEX[]=$r;

// ── Top Customers ─────────────────────────────────────────────────────────
$topCust=[];
$tc = mysqli_query($conn,"SELECT a.name,SUM(s.totamt) AS amt FROM sale s LEFT JOIN accmast a ON a.accode=s.customer GROUP BY s.customer ORDER BY amt DESC LIMIT 5");
if ($tc) while($r=mysqli_fetch_assoc($tc)) $topCust[]=$r;

// ── Top Suppliers (Purchase Entry + Purchase Import combined) ───────────────
$topSup=[];
$ts = mysqli_query($conn,"SELECT a.name, SUM(t.amt) AS amt FROM (
        SELECT supplier, netamount AS amt FROM purchentry
        UNION ALL
        SELECT supplier, netamount AS amt FROM purchaseimport
    ) t LEFT JOIN accmast a ON a.accode=t.supplier GROUP BY t.supplier ORDER BY amt DESC LIMIT 5");
if ($ts) while($r=mysqli_fetch_assoc($ts)) $topSup[]=$r;

// ── Top Salesman (Sale Invoice + Sale GST Invoice combined) ─────────────────
$topSales=[];
$tsm = mysqli_query($conn,"SELECT a.name, SUM(t.amt) AS amt FROM (
        SELECT salesman, totamt AS amt FROM sale
        UNION ALL
        SELECT salesman, totamt AS amt FROM salegst
    ) t LEFT JOIN accmast a ON a.accode=t.salesman WHERE t.salesman>0 GROUP BY t.salesman ORDER BY amt DESC LIMIT 5");
if ($tsm) while($r=mysqli_fetch_assoc($tsm)) $topSales[]=$r;

// ── Sale GST ──────────────────────────────────────────────────────────────
$cntSGST = qs($conn,"SELECT COUNT(*) FROM salegst" . $soCond);
$sgstAmt = qf($conn,"SELECT SUM(totamt) FROM salegst" . $soCond);

// ── Recent Sale GST ───────────────────────────────────────────────────────
$recentSGST=[];
$rsg = mysqli_query($conn,"SELECT g.vouchno,g.vouchdt,g.totamt,c.name AS cname FROM salegst g LEFT JOIN accmast c ON c.accode=g.customer ORDER BY g.vouchno DESC LIMIT 6");
if ($rsg) while($r=mysqli_fetch_assoc($rsg)) $recentSGST[]=$r;

// ── Expense details (accmast grpcode='012', posted to actran via Cash/Bank
//    Payment vouchers — the party leg of that posting carries the expense
//    account's own grpcode, so filtering actran by grpcode='012' isolates
//    every expense payment. Amount is stored negative on that leg, hence
//    the sign flip below to show it as a positive expense figure.) ─────────
$totalExpense = qf($conn,"SELECT SUM(-amount) FROM actran WHERE grpcode='012'");
$cntExpHead   = qs($conn,"SELECT COUNT(*) FROM accmast WHERE grpcode='012' AND accode>50");

$recentExp=[];
$rex = mysqli_query($conn,"SELECT a.vouchno,a.vouchdt,a.source,-a.amount AS amt,e.name AS ename
    FROM actran a LEFT JOIN accmast e ON e.accode=a.accode
    WHERE a.grpcode='012' ORDER BY a.vouchdt DESC, a.vouchno DESC LIMIT 6");
if ($rex) while($r=mysqli_fetch_assoc($rex)) $recentExp[]=$r;

$topExp=[];
$tex = mysqli_query($conn,"SELECT e.name, SUM(-a.amount) AS amt
    FROM actran a LEFT JOIN accmast e ON e.accode=a.accode
    WHERE a.grpcode='012' GROUP BY a.accode ORDER BY amt DESC LIMIT 5");
if ($tex) while($r=mysqli_fetch_assoc($tex)) $topExp[]=$r;

$clrs = ['#3b82f6','#10b981','#8b5cf6','#f59e0b','#f43f5e','#06b6d4','#a855f7','#ef4444','#0ea5e9','#84cc16'];

$compRes  = mysqli_query($conn,"SELECT name FROM `$dbname`.company WHERE code='$compcd'");
$compName = ($compRes && ($cr=mysqli_fetch_assoc($compRes))) ? $cr['name'] : $project_name;
$finyear  = $_SESSION['tit_'.$dbname] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0;}
body{background:#f0f4f8;font-family:'Segoe UI',system-ui,sans-serif;color:#1e293b;font-size:13px;}
.wrap{padding:18px 22px;}

/* Top bar */
.topbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px;flex-wrap:wrap;gap:8px;}
.topbar h1{font-size:17px;font-weight:800;color:#0f172a;letter-spacing:-.3px;}
.topbar .sub{font-size:11.5px;color:#64748b;margin-top:2px;}
.ybadge{background:#fff;border:1.5px solid #e2e8f0;border-radius:8px;padding:5px 14px;font-size:12px;color:#374151;font-weight:700;}

/* Section label */
.sec-label{font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:#94a3b8;margin:18px 0 10px;}

/* Stat cards */
.stats8{display:grid;grid-template-columns:repeat(10,1fr);gap:10px;margin-bottom:6px;}
.scard{background:#fff;border-radius:12px;padding:16px 14px;box-shadow:0 1px 2px rgba(0,0,0,.05),0 4px 12px rgba(0,0,0,.04);position:relative;overflow:hidden;cursor:default;transition:box-shadow .15s;}
.scard:hover{box-shadow:0 4px 16px rgba(0,0,0,.1);}
.scard::before{content:'';position:absolute;right:-12px;top:-12px;width:72px;height:72px;border-radius:50%;opacity:.07;}
.scard.c1::before{background:#3b82f6;} .scard.c2::before{background:#10b981;} .scard.c3::before{background:#8b5cf6;}
.scard.c4::before{background:#f59e0b;} .scard.c5::before{background:#06b6d4;} .scard.c6::before{background:#0ea5e9;}
.scard.c7::before{background:#f43f5e;} .scard.c8::before{background:#a855f7;} .scard.c9::before{background:#ef4444;}
.scard.c10::before{background:#dc2626;}
.sicn{width:36px;height:36px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:15px;color:#fff;margin-bottom:10px;}
.scard.c1 .sicn{background:linear-gradient(135deg,#3b82f6,#2563eb);}
.scard.c2 .sicn{background:linear-gradient(135deg,#10b981,#059669);}
.scard.c3 .sicn{background:linear-gradient(135deg,#8b5cf6,#7c3aed);}
.scard.c4 .sicn{background:linear-gradient(135deg,#f59e0b,#d97706);}
.scard.c5 .sicn{background:linear-gradient(135deg,#06b6d4,#0891b2);}
.scard.c6 .sicn{background:linear-gradient(135deg,#0ea5e9,#0284c7);}
.scard.c7 .sicn{background:linear-gradient(135deg,#f43f5e,#e11d48);}
.scard.c8 .sicn{background:linear-gradient(135deg,#a855f7,#9333ea);}
.scard.c9 .sicn{background:linear-gradient(135deg,#ef4444,#dc2626);}
.scard.c10 .sicn{background:linear-gradient(135deg,#dc2626,#991b1b);}
.sval{font-size:20px;font-weight:800;color:#0f172a;line-height:1;}
.slbl{font-size:11px;color:#64748b;margin-top:4px;font-weight:500;}
.ssub{font-size:10.5px;color:#94a3b8;margin-top:2px;}
.ssub.warn{color:#f59e0b;font-weight:600;}
.ssub.good{color:#10b981;font-weight:600;}
.ssub.bad{color:#e11d48;font-weight:600;}

/* Pipeline */
.pipeline{display:flex;align-items:stretch;gap:0;margin-bottom:18px;overflow-x:auto;}
.pipe-step{flex:1;min-width:130px;background:#fff;padding:14px 12px;text-align:center;position:relative;border-right:1px solid #f1f5f9;}
.pipe-step:first-child{border-radius:12px 0 0 12px;}
.pipe-step:last-child{border-radius:0 12px 12px 0;border-right:none;}
.pipe-step::after{content:'→';position:absolute;right:-10px;top:50%;transform:translateY(-50%);font-size:16px;color:#cbd5e1;z-index:1;}
.pipe-step:last-child::after{display:none;}
.pipe-num{font-size:26px;font-weight:800;color:#1e293b;line-height:1;}
.pipe-lbl{font-size:10.5px;color:#64748b;margin-top:4px;font-weight:600;}
.pipe-sub{font-size:10px;color:#94a3b8;margin-top:2px;}
.pipe-step.active .pipe-num{color:#3b82f6;}
.pipe-step.warn   .pipe-num{color:#f59e0b;}
.pipe-step.good   .pipe-num{color:#10b981;}

/* Financial Summary strip — flex + overflow-x:auto instead of a fixed grid,
   same pattern as .pipeline, so on narrow screens it scrolls horizontally
   instead of squeezing 4 columns into unreadable slivers. */
.finsum-grid{display:flex;gap:12px;overflow-x:auto;-webkit-overflow-scrolling:touch;padding-bottom:2px;}
.finsum-item{flex:1;min-width:170px;border-radius:8px;padding:14px 16px;border-left:4px solid;}

/* Stock split */
.stock-split{display:flex;gap:10px;align-items:center;margin-top:8px;}

/* Two/three/four col */
.two-col{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px;}
.three-col{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-bottom:14px;}
.four-col{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:14px;margin-bottom:14px;}

/* Card */
.card{background:#fff;border-radius:12px;padding:16px;box-shadow:0 1px 2px rgba(0,0,0,.05),0 4px 12px rgba(0,0,0,.04);}
.ctitle{font-size:12.5px;font-weight:700;color:#1e293b;margin-bottom:12px;display:flex;align-items:center;gap:7px;}
.chart-box{position:relative;height:180px;}

/* Tables */
.mt{width:100%;border-collapse:collapse;font-size:11.5px;}
.mt th{background:#f8fafc;color:#64748b;font-weight:700;font-size:10px;text-transform:uppercase;letter-spacing:.04em;padding:6px 8px;border-bottom:2px solid #f1f5f9;text-align:left;}
.mt td{padding:7px 8px;border-bottom:1px solid #f8fafc;color:#374151;}
.mt tr:last-child td{border-bottom:none;}
.mt tr:hover td{background:#fafbff;}
.nr{text-align:right;}
.badge{display:inline-block;padding:2px 7px;border-radius:12px;font-size:10px;font-weight:700;}
.bg{background:#d1fae5;color:#065f46;} .bb{background:#dbeafe;color:#1e40af;} .bp{background:#ede9fe;color:#5b21b6;}

/* Bar */
.barrow{display:flex;align-items:center;gap:8px;margin-bottom:7px;}
.barlbl{font-size:11px;min-width:90px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#374151;}
.bartrk{flex:1;background:#f1f5f9;border-radius:4px;height:7px;overflow:hidden;}
.barfil{height:100%;border-radius:4px;}
.barval{font-size:10.5px;color:#64748b;min-width:62px;text-align:right;font-weight:600;}

@media(max-width:1300px){.stats8{grid-template-columns:repeat(3,1fr);}.four-col{grid-template-columns:1fr 1fr;}}
@media(max-width:900px){.stats8{grid-template-columns:repeat(3,1fr);}}
@media(max-width:800px){.two-col,.three-col,.four-col{grid-template-columns:1fr;}.stats8{grid-template-columns:repeat(2,1fr);}}
</style>
</head>
<body>
<div class="wrap">

<!-- Top bar -->
<div class="topbar">
    <div>
        <h1><i class="fa fa-briefcase" style="color:#3b82f6;margin-right:8px;"></i><?php echo htmlspecialchars($compName); ?></h1>
        <div class="sub">Dashboard &nbsp;·&nbsp; <?php echo htmlspecialchars($project_title); ?> &nbsp;·&nbsp; Financial Year <?php echo htmlspecialchars($finyear); ?></div>
    </div>
    <div class="ybadge"><i class="fa fa-calendar-day" style="color:#6366f1;margin-right:6px;"></i><?php echo date('d M Y, D'); ?></div>
</div>

<!-- Order Pipeline -->
<div class="sec-label"><i class="fa fa-arrow-right-arrow-left" style="margin-right:5px;"></i>Order Pipeline</div>
<div class="pipeline">
    <div class="pipe-step active">
        <div class="pipe-num"><?php echo $cntSO; ?></div>
        <div class="pipe-lbl">Sale Orders</div>
        <div class="pipe-sub"><?php echo $soPending; ?> awaiting dispatch</div>
    </div>
    <div class="pipe-step">
        <div class="pipe-num"><?php echo $soDispatched; ?></div>
        <div class="pipe-lbl">Dispatched</div>
        <div class="pipe-sub"><?php echo $soPendingInv; ?> awaiting invoice</div>
    </div>
    <div class="pipe-step warn">
        <div class="pipe-num"><?php echo $soPendingInv; ?></div>
        <div class="pipe-lbl">Pending Invoice</div>
        <div class="pipe-sub">Dispatched, not billed</div>
    </div>
    <div class="pipe-step good">
        <div class="pipe-num"><?php echo $cntSale; ?></div>
        <div class="pipe-lbl">Sale Invoices</div>
        <div class="pipe-sub">₹<?php echo number_format($saleAmt,0); ?></div>
    </div>
</div>

<?php if ($usertype === 1): ?>
<!-- Stat cards -->
<div class="sec-label"><i class="fa fa-gauge" style="margin-right:5px;"></i>Key Metrics</div>
<div class="stats8" style="margin-bottom:12px;">
    <div class="scard c1">
        <div class="sicn"><i class="fa fa-users"></i></div>
        <div class="sval"><?php echo $cntCust; ?></div>
        <div class="slbl">Customers</div>
        <div class="ssub"><?php echo $cntSupp; ?> suppliers</div>
    </div>
    <div class="scard c2">
        <div class="sicn"><i class="fa fa-cart-arrow-down"></i></div>
        <div class="sval"><?php echo $cntSale; ?></div>
        <div class="slbl">Sales</div>
        <div class="ssub">₹<?php echo number_format($saleAmt,0); ?></div>
    </div>
    <div class="scard c3">
        <div class="sicn"><i class="fa fa-cart-plus"></i></div>
        <div class="sval"><?php echo $cntPur; ?></div>
        <div class="slbl">Purchases</div>
        <div class="ssub">₹<?php echo number_format($purAmt,0); ?></div>
    </div>
    <div class="scard c4">
        <div class="sicn"><i class="fa fa-truck-ramp-box"></i></div>
        <div class="sval"><?php echo $cntPEX; ?></div>
        <div class="slbl">Purchase Import</div>
        <div class="ssub">₹<?php echo number_format($pexAmt,0); ?></div>
    </div>
    <div class="scard c5">
        <div class="sicn"><i class="fa fa-boxes-stacked"></i></div>
        <div class="sval"><?php echo number_format($stockQty,0); ?></div>
        <div class="slbl">Stock on Hand</div>
        <div class="ssub"><?php echo $cntProd; ?> products</div>
    </div>
    <div class="scard c6">
        <div class="sicn"><i class="fa fa-landmark"></i></div>
        <div class="sval" style="font-size:16px;">₹<?php echo number_format(abs($bankBal),0); ?></div>
        <div class="slbl">Bank Balance</div>
        <div class="ssub <?php echo $bankBal>=0?'good':'bad'; ?>"><?php echo $bankBal>=0?'Available':'Overdrawn'; ?></div>
    </div>
    <div class="scard c7">
        <div class="sicn"><i class="fa fa-money-bill-wave"></i></div>
        <div class="sval" style="font-size:16px;">₹<?php echo number_format(abs($cashBal),0); ?></div>
        <div class="slbl">Cash Balance</div>
        <div class="ssub <?php echo $cashBal>=0?'good':'bad'; ?>"><?php echo $cashBal>=0?'Available':'Overdrawn'; ?></div>
    </div>
    <div class="scard c8">
        <div class="sicn"><i class="fa fa-clock-rotate-left"></i></div>
        <div class="sval" style="font-size:16px;">₹<?php echo number_format($totalReceivable,0); ?></div>
        <div class="slbl">Receivable</div>
        <div class="ssub <?php echo $totalReceivable>0?'warn':'good'; ?>"><?php echo $totalReceivable>0 ? 'From customers' : 'All received'; ?></div>
    </div>
    <div class="scard c9">
        <div class="sicn"><i class="fa fa-file-invoice-dollar"></i></div>
        <div class="sval" style="font-size:16px;">₹<?php echo number_format($totalPayable,0); ?></div>
        <div class="slbl">Payable</div>
        <div class="ssub <?php echo $totalPayable>0?'warn':'good'; ?>"><?php echo $totalPayable>0 ? 'To suppliers' : 'All paid'; ?></div>
    </div>
    <div class="scard c10">
        <div class="sicn"><i class="fa fa-receipt"></i></div>
        <div class="sval" style="font-size:16px;">₹<?php echo number_format($totalExpense,0); ?></div>
        <div class="slbl">Expense</div>
        <div class="ssub"><?php echo $cntExpHead; ?> expense heads</div>
    </div>
</div>

<!-- Financial Summary strip -->
<div class="card" style="margin-bottom:14px;">
    <div class="ctitle"><i class="fa fa-chart-pie" style="color:#3b82f6;"></i>Financial Summary</div>
    <div class="finsum-grid">
        <div class="finsum-item" style="background:#eff6ff;border-left-color:#3b82f6;">
            <div style="font-size:11px;font-weight:600;color:#1d4ed8;margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em;">Total Sales</div>
            <div style="font-size:18px;font-weight:800;color:#1e40af;">₹<?php echo number_format($saleAmt,2); ?></div>
        </div>
        <div class="finsum-item" style="background:#fef9c3;border-left-color:#f59e0b;">
            <div style="font-size:11px;font-weight:600;color:#92400e;margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em;">Pending Receivable</div>
            <div style="font-size:18px;font-weight:800;color:#78350f;">₹<?php echo number_format($totalReceivable,2); ?></div>
        </div>
        <div class="finsum-item" style="background:#f0fdf4;border-left-color:#10b981;">
            <div style="font-size:11px;font-weight:600;color:#166534;margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em;">Total Purchases (Entry + Import)</div>
            <div style="font-size:18px;font-weight:800;color:#065f46;">₹<?php echo number_format($totalPurAmt,2); ?></div>
        </div>
        <div class="finsum-item" style="background:#fef2f2;border-left-color:#f43f5e;">
            <div style="font-size:11px;font-weight:600;color:#9f1239;margin-bottom:4px;text-transform:uppercase;letter-spacing:.04em;">Pending Payable</div>
            <div style="font-size:18px;font-weight:800;color:#881337;">₹<?php echo number_format($totalPayable,2); ?></div>
        </div>
    </div>
</div>

<!-- Stock split card (dynamic — one segment per godown from godown master) -->
<div class="scard" style="margin-bottom:18px;padding:16px 18px;">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;">
        <div>
            <div class="slbl" style="font-size:12.5px;font-weight:700;color:#1e293b;">Total Stock</div>
            <div class="sval" style="font-size:28px;margin-top:4px;"><?php echo number_format($stockQty,0); ?> <span style="font-size:14px;color:#64748b;font-weight:500;">Units</span></div>
        </div>
        <div style="text-align:right;">
            <?php foreach (array_slice($stockByGodown,0,5) as $i => $sg): ?>
            <div style="font-size:11px;color:#64748b;<?php echo $i>0?'margin-top:3px;':''; ?>"><?php echo htmlspecialchars($sg['name']); ?>: <b style="color:<?php echo $clrs[$i%count($clrs)]; ?>;"><?php echo number_format((float)$sg['qty'],0); ?></b></div>
            <?php endforeach; ?>
            <?php if (count($stockByGodown) > 5): ?><div style="font-size:10.5px;color:#94a3b8;margin-top:3px;">+<?php echo count($stockByGodown)-5; ?> more godowns</div><?php endif; ?>
            <?php if (!$stockByGodown): ?><div style="font-size:11px;color:#94a3b8;">No godowns set up yet</div><?php endif; ?>
        </div>
    </div>
    <?php $totalG = max($stockQty, 1); ?>
    <div style="margin-top:12px;background:#f1f5f9;border-radius:6px;height:12px;overflow:hidden;display:flex;">
        <?php foreach ($stockByGodown as $i => $sg): $gp = round(max((float)$sg['qty'],0) / $totalG * 100); if ($gp <= 0) continue; ?>
        <div style="width:<?php echo $gp; ?>%;background:<?php echo $clrs[$i%count($clrs)]; ?>;"></div>
        <?php endforeach; ?>
    </div>
    <div style="display:flex;flex-wrap:wrap;gap:12px 16px;margin-top:8px;font-size:11px;">
        <?php foreach ($stockByGodown as $i => $sg): $gp = $totalG>0 ? round(max((float)$sg['qty'],0) / $totalG * 100) : 0; ?>
        <span><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:<?php echo $clrs[$i%count($clrs)]; ?>;margin-right:4px;"></span><?php echo htmlspecialchars($sg['name']); ?> <?php echo $gp; ?>%</span>
        <?php endforeach; ?>
        <span style="margin-left:auto;color:#94a3b8;"><?php echo $cntGodown; ?> godowns &nbsp;·&nbsp; <?php echo $cntInward; ?> inward, <?php echo $cntOutward; ?> outward, <?php echo $cntDamage; ?> damage entries</span>
    </div>
</div>

<!-- Charts -->
<div class="three-col">
    <div class="card">
        <div class="ctitle"><i class="fa fa-chart-line" style="color:#3b82f6;"></i>Sales Trend — Last 6 Months</div>
        <div class="chart-box"><canvas id="saleChart"></canvas></div>
    </div>
    <div class="card">
        <div class="ctitle"><i class="fa fa-chart-bar" style="color:#8b5cf6;"></i>Purchase Trend (Entry + Import) — Last 6 Months</div>
        <div class="chart-box"><canvas id="purChart"></canvas></div>
    </div>
    <div class="card">
        <div class="ctitle"><i class="fa fa-chart-line" style="color:#dc2626;"></i>Expense Trend — Last 6 Months</div>
        <div class="chart-box"><canvas id="expChart"></canvas></div>
    </div>
</div>

<!-- Sales vs Collection -->
<div class="card" style="margin-bottom:14px;">
    <div class="ctitle"><i class="fa fa-scale-balanced" style="color:#16a34a;"></i>Sales vs Collection — Last 6 Months</div>
    <div class="chart-box" style="height:230px;"><canvas id="svcChart"></canvas></div>
</div>

<!-- Bottom 4 col -->
<div class="four-col">
    <!-- Recent Sales -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-cart-arrow-down" style="color:#2563eb;"></i>Recent Sales</div>
        <table class="mt">
            <thead><tr><th>#</th><th>Date</th><th>Customer</th><th class="nr">Amt</th></tr></thead>
            <tbody>
            <?php foreach ($recentSale as $r): ?>
            <tr>
                <td><span class="badge bb">S#<?php echo $r['vouchno']; ?></span></td>
                <td style="font-size:10.5px;"><?php echo $r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-y',strtotime($r['vouchdt'])):''; ?></td>
                <td style="max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;"><?php echo htmlspecialchars($r['cname']??''); ?></td>
                <td class="nr" style="font-weight:600;">₹<?php echo number_format((float)$r['totamt'],0); ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$recentSale): ?><tr><td colspan="4" style="text-align:center;color:#94a3b8;padding:12px;">No sales yet</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Recent Purchases -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-cart-plus" style="color:#7c3aed;"></i>Recent Purchases</div>
        <table class="mt">
            <thead><tr><th>#</th><th>Date</th><th>Supplier</th><th class="nr">Amt</th></tr></thead>
            <tbody>
            <?php foreach ($recentPur as $r): ?>
            <tr>
                <td><span class="badge bp">P#<?php echo $r['vouchno']; ?></span></td>
                <td style="font-size:10.5px;"><?php echo $r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-y',strtotime($r['vouchdt'])):''; ?></td>
                <td style="max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;"><?php echo htmlspecialchars($r['sname']??''); ?></td>
                <td class="nr" style="font-weight:600;">₹<?php echo number_format((float)$r['netamount'],0); ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$recentPur): ?><tr><td colspan="4" style="text-align:center;color:#94a3b8;padding:12px;">No purchases yet</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Recent Purchase Imports -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-truck-ramp-box" style="color:#16a34a;"></i>Recent Purchase Imports</div>
        <table class="mt">
            <thead><tr><th>#</th><th>Date</th><th>Supplier</th><th class="nr">Amt</th></tr></thead>
            <tbody>
            <?php foreach ($recentPEX as $r): ?>
            <tr>
                <td><span class="badge bg">PI#<?php echo $r['vouchno']; ?></span></td>
                <td style="font-size:10.5px;"><?php echo $r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-y',strtotime($r['vouchdt'])):''; ?></td>
                <td style="max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;"><?php echo htmlspecialchars($r['sname']??''); ?></td>
                <td class="nr" style="font-weight:600;">₹<?php echo number_format((float)$r['netamount'],0); ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$recentPEX): ?><tr><td colspan="4" style="text-align:center;color:#94a3b8;padding:12px;">No purchase imports yet</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Recent Sale GST -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-receipt" style="color:#d97706;"></i>Recent Sale GST</div>
        <table class="mt">
            <thead><tr><th>#</th><th>Date</th><th>Customer</th><th class="nr">Amt</th></tr></thead>
            <tbody>
            <?php foreach ($recentSGST as $r): ?>
            <tr>
                <td><span class="badge" style="background:#fef3c7;color:#92400e;">SG#<?php echo $r['vouchno']; ?></span></td>
                <td style="font-size:10.5px;"><?php echo $r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-y',strtotime($r['vouchdt'])):''; ?></td>
                <td style="max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;"><?php echo htmlspecialchars($r['cname']??''); ?></td>
                <td class="nr" style="font-weight:600;">₹<?php echo number_format((float)$r['totamt'],0); ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$recentSGST): ?><tr><td colspan="4" style="text-align:center;color:#94a3b8;padding:12px;">No Sale GST invoices yet</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Expense Details -->
<div class="sec-label"><i class="fa fa-receipt" style="margin-right:5px;"></i>Expense Details</div>
<div class="two-col">
    <!-- Recent Expenses -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-money-bill-transfer" style="color:#dc2626;"></i>Recent Expenses</div>
        <table class="mt">
            <thead><tr><th>#</th><th>Date</th><th>Expense Head</th><th class="nr">Amt</th></tr></thead>
            <tbody>
            <?php foreach ($recentExp as $r): ?>
            <tr>
                <td><span class="badge" style="background:#fee2e2;color:#991b1b;"><?php echo htmlspecialchars($r['source']); ?>#<?php echo $r['vouchno']; ?></span></td>
                <td style="font-size:10.5px;"><?php echo $r['vouchdt']&&$r['vouchdt']!='0000-00-00'?date('d-m-y',strtotime($r['vouchdt'])):''; ?></td>
                <td style="max-width:110px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10.5px;"><?php echo htmlspecialchars($r['ename']??''); ?></td>
                <td class="nr" style="font-weight:600;">₹<?php echo number_format((float)$r['amt'],0); ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$recentExp): ?><tr><td colspan="4" style="text-align:center;color:#94a3b8;padding:12px;">No expenses recorded yet</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Top Expense Heads -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-chart-simple" style="color:#dc2626;"></i>Top Expense Heads</div>
        <?php
        $maxE = $topExp ? max(array_column($topExp,'amt')) : 1;
        foreach ($topExp as $i => $teRow):
            $pct = $maxE > 0 ? (float)$teRow['amt'] / $maxE * 100 : 0;
        ?>
        <div class="barrow">
            <div class="barlbl"><?php echo htmlspecialchars($teRow['name']??'?'); ?></div>
            <div class="bartrk"><div class="barfil" style="width:<?php echo round($pct); ?>%;background:<?php echo $clrs[$i%5]; ?>;"></div></div>
            <div class="barval">₹<?php echo number_format((float)abs($teRow['amt']),0); ?></div>
        </div>
        <?php endforeach; ?>
        <?php if (!$topExp): ?><p style="color:#94a3b8;font-size:12px;text-align:center;padding:12px;">No data yet</p><?php endif; ?>
    </div>
</div>

<!-- Top Customers | Top Suppliers | Top Salesman -->
<div class="sec-label"><i class="fa fa-ranking-star" style="margin-right:5px;"></i>Top Performers</div>
<div class="three-col">
    <!-- Top Customers -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-ranking-star" style="color:#f59e0b;"></i>Top Customers</div>
        <?php
        $maxC = $topCust ? max(array_column($topCust,'amt')) : 1;
        foreach ($topCust as $i => $tcRow):
            $pct = $maxC > 0 ? (float)$tcRow['amt'] / $maxC * 100 : 0;
        ?>
        <div class="barrow">
            <div class="barlbl"><?php echo htmlspecialchars($tcRow['name']??'?'); ?></div>
            <div class="bartrk"><div class="barfil" style="width:<?php echo round($pct); ?>%;background:<?php echo $clrs[$i%5]; ?>;"></div></div>
            <div class="barval">₹<?php echo number_format((float)$tcRow['amt'],0); ?></div>
        </div>
        <?php endforeach; ?>
        <?php if (!$topCust): ?><p style="color:#94a3b8;font-size:12px;text-align:center;padding:12px;">No data yet</p><?php endif; ?>
    </div>

    <!-- Top Suppliers (Purchase Entry + Purchase Import combined) -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-truck" style="color:#10b981;"></i>Top Suppliers</div>
        <?php
        $maxS = $topSup ? max(array_column($topSup,'amt')) : 1;
        foreach ($topSup as $i => $tsRow):
            $pct = $maxS > 0 ? (float)$tsRow['amt'] / $maxS * 100 : 0;
        ?>
        <div class="barrow">
            <div class="barlbl"><?php echo htmlspecialchars($tsRow['name']??'?'); ?></div>
            <div class="bartrk"><div class="barfil" style="width:<?php echo round($pct); ?>%;background:<?php echo $clrs[$i%5]; ?>;"></div></div>
            <div class="barval">₹<?php echo number_format((float)$tsRow['amt'],0); ?></div>
        </div>
        <?php endforeach; ?>
        <?php if (!$topSup): ?><p style="color:#94a3b8;font-size:12px;text-align:center;padding:12px;">No data yet</p><?php endif; ?>
    </div>

    <!-- Top Salesman (Sale + Sale GST invoices combined) -->
    <div class="card">
        <div class="ctitle"><i class="fa fa-user-tie" style="color:#3b82f6;"></i>Top Salesman</div>
        <?php
        $maxSm = $topSales ? max(array_column($topSales,'amt')) : 1;
        foreach ($topSales as $i => $smRow):
            $pct = $maxSm > 0 ? (float)$smRow['amt'] / $maxSm * 100 : 0;
        ?>
        <div class="barrow">
            <div class="barlbl"><?php echo htmlspecialchars($smRow['name']??'Unassigned'); ?></div>
            <div class="bartrk"><div class="barfil" style="width:<?php echo round($pct); ?>%;background:<?php echo $clrs[$i%5]; ?>;"></div></div>
            <div class="barval">₹<?php echo number_format((float)$smRow['amt'],0); ?></div>
        </div>
        <?php endforeach; ?>
        <?php if (!$topSales): ?><p style="color:#94a3b8;font-size:12px;text-align:center;padding:12px;">No data yet</p><?php endif; ?>
    </div>
</div>
<?php endif; ?>

</div><!-- /wrap -->

<?php if ($usertype === 1): ?>
<script>
var saleL=<?php echo json_encode(array_column($saleMonths,'mo')); ?>;
var saleD=<?php echo json_encode(array_map(function($r){return round((float)$r['amt'],0);},$saleMonths)); ?>;
var purL =<?php echo json_encode(array_column($purMonths,'mo')); ?>;
var purD =<?php echo json_encode(array_map(function($r){return round((float)$r['amt'],0);},$purMonths)); ?>;

var co={responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{x:{grid:{display:false},ticks:{font:{size:9}}},y:{grid:{color:'#f1f5f9'},ticks:{font:{size:9},callback:v=>'₹'+v.toLocaleString()}}}};

var expL=<?php echo json_encode($expLabels); ?>;
var expD=<?php echo json_encode(array_map(function($v){return round((float)$v,0);},$expData)); ?>;

new Chart(document.getElementById('saleChart'),{type:'line',data:{labels:saleL,datasets:[{data:saleD,borderColor:'#3b82f6',backgroundColor:'rgba(59,130,246,.1)',borderWidth:2.5,pointRadius:3.5,pointBackgroundColor:'#3b82f6',fill:true,tension:0.4}]},options:co});
new Chart(document.getElementById('purChart'),{type:'bar',data:{labels:purL,datasets:[{data:purD,backgroundColor:'rgba(139,92,246,.7)',borderRadius:5,borderSkipped:false}]},options:co});
new Chart(document.getElementById('expChart'),{type:'line',data:{labels:expL,datasets:[{data:expD,borderColor:'#dc2626',backgroundColor:'rgba(220,38,38,.1)',borderWidth:2.5,pointRadius:3.5,pointBackgroundColor:'#dc2626',fill:true,tension:0.4}]},options:co});

// Sales vs Collection — bars for invoiced Sales, line for actual money Collected
var svcL    = <?php echo json_encode($svcLabels); ?>;
var svcSale = <?php echo json_encode(array_map(function($v){return round((float)$v,0);},$svcSalesData)); ?>;
var svcColl = <?php echo json_encode(array_map(function($v){return round((float)$v,0);},$svcCollData)); ?>;

var svcOpt = {
    responsive:true, maintainAspectRatio:false,
    plugins:{legend:{display:true, position:'top', align:'end', labels:{boxWidth:10, font:{size:10.5}}}},
    scales:{
        x:{grid:{display:false},ticks:{font:{size:9}}},
        y:{grid:{color:'#f1f5f9'},ticks:{font:{size:9},callback:v=>'₹'+v.toLocaleString()}}
    }
};

new Chart(document.getElementById('svcChart'),{
    type:'bar',
    data:{
        labels:svcL,
        datasets:[
            {type:'bar',  label:'Sales',      data:svcSale, backgroundColor:'rgba(59,130,246,.75)', borderRadius:5, borderSkipped:false},
            {type:'bar',  label:'Collection', data:svcColl, backgroundColor:'rgba(22,163,74,.75)', borderRadius:5, borderSkipped:false}
        ]
    },
    options:svcOpt
});
</script>
<?php endif; ?>
</body>
</html>
