<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'agency') {
    header('Location: ../login.php');
    exit;
}

function esc($v): string {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function money($amt): string {
    return '₹' . number_format((float)$amt, 2);
}

function bindParamsDynamic(mysqli_stmt $stmt, string $types, array &$params): void {
    if ($types === '' || empty($params)) {
        return;
    }
    $bind = [$types];
    foreach ($params as $k => $v) {
        $bind[] = &$params[$k];
    }
    call_user_func_array([$stmt, 'bind_param'], $bind);
}

function runScalar(mysqli $conn, string $sql, string $key, array $params = [], string $types = '') {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return 0;
    }
    if (!empty($params)) {
        bindParamsDynamic($stmt, $types, $params);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt->close();
    return $row[$key] ?? 0;
}

function runRows(mysqli $conn, string $sql, array $params = [], string $types = ''): array {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return [];
    }
    if (!empty($params)) {
        bindParamsDynamic($stmt, $types, $params);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    $rows = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    $stmt->close();
    return $rows;
}

$agencyId = (int)$_SESSION['user_id'];

$scopeSql = "
    b.created_by IN (
        SELECT id FROM users WHERE id = ?
        UNION
        SELECT id FROM users WHERE agency_id = ?
        UNION
        SELECT id FROM users
        WHERE manager_id IN (
            SELECT id FROM users WHERE agency_id = ?
        )
    )
";
$scopeParams = [$agencyId, $agencyId, $agencyId];
$scopeTypes = 'iii';

$totalBills = (int) runScalar($conn, "SELECT COUNT(*) AS total FROM bills b WHERE $scopeSql", 'total', $scopeParams, $scopeTypes);
$totalSales = (float) runScalar($conn, "
SELECT COALESCE(SUM(b.total_amount),0) AS total 
FROM bills b 
WHERE $scopeSql 
AND MONTH(b.created_at)=MONTH(CURDATE()) 
AND YEAR(b.created_at)=YEAR(CURDATE())
", 'total', $scopeParams, $scopeTypes);
$todaySales = (float) runScalar($conn, "SELECT COALESCE(SUM(b.total_amount),0) AS total FROM bills b WHERE $scopeSql AND DATE(b.created_at)=CURDATE()", 'total', $scopeParams, $scopeTypes);
$totalDue = (float) runScalar($conn, "SELECT COALESCE(SUM(b.due_amount),0) AS total FROM bills b WHERE $scopeSql", 'total', $scopeParams, $scopeTypes);
$dueBills = (int) runScalar($conn, "SELECT COUNT(*) AS total FROM bills b WHERE $scopeSql AND b.due_amount > 0", 'total', $scopeParams, $scopeTypes);
$clients = (int) runScalar($conn, "SELECT COUNT(*) AS total FROM users u WHERE u.role='medical_representative' AND (u.agency_id = ? OR u.manager_id IN (SELECT id FROM users WHERE agency_id = ?) OR u.id = ?)", 'total', [$agencyId, $agencyId, $agencyId], 'iii');

$pendingBills = (int) runScalar($conn, "SELECT COUNT(*) AS total FROM bills b WHERE $scopeSql AND b.payment_status='unpaid'", 'total', $scopeParams, $scopeTypes);
$advanceBills = (int) runScalar($conn, "SELECT COUNT(*) AS total FROM bills b WHERE $scopeSql AND b.payment_status='advance'", 'total', $scopeParams, $scopeTypes);
$paidBills = (int) runScalar($conn, "SELECT COUNT(*) AS total FROM bills b WHERE $scopeSql AND b.payment_status='paid'", 'total', $scopeParams, $scopeTypes);

/* Sales trend (last 7 days) */
$trendRows = runRows($conn, "
    SELECT DATE(b.created_at) AS day, COALESCE(SUM(b.total_amount),0) AS total
    FROM bills b
    WHERE $scopeSql AND b.created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    GROUP BY DATE(b.created_at)
    ORDER BY day ASC
", $scopeParams, $scopeTypes);

$trendMap = [];
foreach ($trendRows as $row) {
    $trendMap[$row['day']] = (float)$row['total'];
}
$trendLabels = [];
$trendValues = [];
for ($i = 6; $i >= 0; $i--) {
    $day = date('Y-m-d', strtotime("-$i days"));
    $trendLabels[] = date('d M', strtotime($day));
    $trendValues[] = $trendMap[$day] ?? 0;
}

/* Top selling products */
$topProducts = runRows($conn, "
    SELECT
        p.id,
        p.product_name,
        p.brand_name,
        SUM(bi.qty) AS total_qty,
        COALESCE(SUM(bi.total),0) AS total_value
    FROM bills b
    JOIN bill_items bi ON bi.bill_id = b.id
    JOIN products p ON p.id = bi.product_id
    WHERE $scopeSql
    GROUP BY p.id, p.product_name, p.brand_name
    ORDER BY total_qty DESC, total_value DESC
    LIMIT 5
", $scopeParams, $scopeTypes);

/* Due alerts */
$dueAlerts = runRows($conn, "
    SELECT
        b.id,
        b.customer_name,
        b.total_amount,
        b.paid_amount,
        b.due_amount,
        b.due_date,
        b.created_at,
        u.name AS created_by_name
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    WHERE $scopeSql AND b.due_amount > 0
    ORDER BY b.due_amount DESC, b.created_at DESC
    LIMIT 5
", $scopeParams, $scopeTypes);

/* Last 5 bills */
$lastBills = runRows($conn, "
    SELECT
        b.id,
        b.customer_name,
        b.total_amount,
        b.paid_amount,
        b.due_amount,
        b.payment_status,
        b.created_at,
        u.name AS created_by_name
    FROM bills b
    LEFT JOIN users u ON b.created_by = u.id
    WHERE $scopeSql
    ORDER BY b.created_at DESC, b.id DESC
    LIMIT 5
", $scopeParams, $scopeTypes);

/* Payment summary */
$statusCounts = runRows($conn, "
    SELECT b.payment_status, COUNT(*) AS total
    FROM bills b
    WHERE $scopeSql
    GROUP BY b.payment_status
", $scopeParams, $scopeTypes);

$statusMap = ['paid' => 0, 'unpaid' => 0, 'advance' => 0];
foreach ($statusCounts as $row) {
    $status = $row['payment_status'] ?? '';
    if (isset($statusMap[$status])) {
        $statusMap[$status] = (int)$row['total'];
    }
}

$topLabels = [];
$topValues = [];
foreach ($topProducts as $row) {
    $topLabels[] = $row['product_name'];
    $topValues[] = (float)$row['total_qty'];
}
?>
<?php include "agencysidebar.php"; ?>
<?php include "../header.php"; ?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Agency Dashboard</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
:root{
    --bg:#eef3f9;
    --panel:#ffffff;
    --panel-2:#f8fbff;
    --line:#e2e8f0;
    --line-2:#d8e1ec;
    --text:#0f172a;
    --muted:#64748b;
    --theme:#374155;
    --theme-dark:#2c3445;
    --blue:#2563eb;
    --green:#16a34a;
    --amber:#f59e0b;
    --red:#dc2626;
    --violet:#8b5cf6;
    --sky:#0ea5e9;
    --shadow:0 10px 28px rgba(15,23,42,.08);
    --shadow-soft:0 8px 20px rgba(15,23,42,.05);
    --shadow-hover:0 14px 30px rgba(15,23,42,.12);
}

*{
    box-sizing:border-box
}

body{
    margin:0;
    background:linear-gradient(180deg,#eef3f9 0%, #e9eef6 100%);
    color:var(--text);
    font-family:Inter, Arial, Helvetica, sans-serif;
}

/* ===== DASHBOARD ===== */
.dashboard{
    margin-left:260px;
    width:calc(100% - 260px);
    min-height:100vh;
    padding:24px;
    padding-top:85px;
}

/* ===== HERO ===== */
.hero{
    background:linear-gradient(135deg,#ffffff 0%, #fbfdff 100%);
    border:1px solid rgba(226,232,240,.95);
    border-radius:20px;
    box-shadow:var(--shadow-soft);
    padding:16px 18px;
    margin:12px 0 16px;
    position:relative;
    overflow:hidden;
}

.hero::before{
    content:"";
    position:absolute;
    inset:auto -40px -55px auto;
    width:180px;
    height:180px;
    background:radial-gradient(circle, rgba(37,99,235,.08), transparent 70%);
    pointer-events:none;
}

.hero-top{
    display:flex;
    justify-content:space-between;
    gap:10px;
    align-items:center;
    flex-wrap:wrap;
    position:relative;
    z-index:1;
}

.hero h1{
    margin:0;
    font-size:21px;
    font-weight:800;
    letter-spacing:-.03em;
    color:var(--theme);
    display:flex;
    align-items:center;
    gap:8px;
}

.hero h1 i{
    color:var(--blue);
    font-size:19px;
}

.hero p{
    margin:4px 0 0;
    color:var(--muted);
    font-size:12px;
    max-width:580px;
    line-height:1.45;
}

/* BADGES */
.hero-badges{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
}

.hero-badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:7px 11px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
    border:1px solid #e2e8f0;
    background:#f8fafc;
    color:var(--theme);
    box-shadow:0 6px 14px rgba(15,23,42,.03);
}

.hero-badge i{
    color:var(--blue);
}

/* ===== CARDS ===== */
.cards{
    display:grid;
    grid-template-columns:repeat(6, minmax(0, 1fr));
    gap:12px;
    margin:14px 0 18px;
}
.stat-card{
    background:#fff;
    border:1px solid #e2e8f0;
    border-radius:16px;
    padding:16px;
    box-shadow:0 4px 12px rgba(0,0,0,0.04);
    transition:0.2s;
}

.stat-card:hover{
    transform:translateY(-2px);
    box-shadow:0 8px 20px rgba(0,0,0,0.06);
}
.stat-card::before{
    display:none !important;
}

.stat-card:nth-child(1)::before{background:var(--blue)}
.stat-card:nth-child(2)::before{background:var(--green)}
.stat-card:nth-child(3)::before{background:var(--amber)}
.stat-card:nth-child(4)::before{background:var(--red)}
.stat-card:nth-child(5)::before{background:var(--sky)}
.stat-card:nth-child(6)::before{background:var(--violet)}

.stat-head{
    display:flex;
    justify-content:space-between;
    gap:10px;
    align-items:flex-start;
}

.stat-label{
    font-size:11px;
    color:#94a3b8;
    font-weight:700;
    letter-spacing:.08em;
}

.stat-value{
    font-size:22px;
    font-weight:800;
    margin-top:6px;
}

.stat-sub{
    font-size:12px;
    color:#64748b;
    margin-top:4px;
}

.stat-card:nth-child(1) .stat-value{color:#111827;}
.stat-card:nth-child(2) .stat-value{color:#16a34a;}
.stat-card:nth-child(3) .stat-value{color:#111827;}
.stat-card:nth-child(4) .stat-value{color:#dc2626;}
.stat-card:nth-child(5) .stat-value{color:#111827;}
.stat-card:nth-child(6) .stat-value{color:#111827;}

.stat-icon{
    width:38px;
    height:38px;
    border-radius:12px;
    display:flex;
    align-items:center;
    justify-content:center;
    flex-shrink:0;
    background:#f1f5f9;
    box-shadow:inset 0 1px 0 rgba(255,255,255,.8);
}

.stat-card:nth-child(1) .stat-icon{background:rgba(37,99,235,.10);color:var(--blue)}
.stat-card:nth-child(2) .stat-icon{background:rgba(22,163,74,.10);color:var(--green)}
.stat-card:nth-child(3) .stat-icon{background:rgba(245,158,11,.12);color:var(--amber)}
.stat-card:nth-child(4) .stat-icon{background:rgba(220,38,38,.10);color:var(--red)}
.stat-card:nth-child(5) .stat-icon{background:rgba(14,165,233,.10);color:var(--sky)}
.stat-card:nth-child(6) .stat-icon{background:rgba(139,92,246,.10);color:var(--violet)}

/* ===== GRID ===== */
.grid-2{
    display:grid;
    grid-template-columns:1.2fr 1fr;
    gap:14px;
    margin-bottom:14px;
}

/* ===== PANEL ===== */
.panel{
    background:#fff;
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow-soft);
    overflow:hidden;
    position:relative;
    display:flex;
    flex-direction:column;
}

/* .panel::before{
    content:"";
    position:absolute;
    left:0;
    top:0;
    width:100%;
    height:3px;
    background:linear-gradient(90deg, rgba(37,99,235,.95), rgba(139,92,246,.85));
} */

    .panel{
border:1px solid #e2e8f0;
box-shadow:0 8px 20px rgba(0,0,0,0.05);
}
.panel-head{
    padding:12px 14px;
    border-bottom:1px solid var(--line);
    background:linear-gradient(180deg,#ffffff 0%, #fbfdff 100%);
}

.panel-title{
    margin:0;
    font-size:15px;
    font-weight:800;
    color:var(--theme);
}

.panel-sub{
    margin-top:4px;
    font-size:11px;
    color:var(--muted);
}

.panel-body{
    padding:14px;
    flex:1;
}

/* ===== CHART ===== */
.chart-wrap{
    height:260px;
    width:100%;
}

/* ===== TABLE ===== */
.mini-table{
    width:100%;
    border-collapse:separate;
    border-spacing:0;
}

.mini-table th,
.mini-table td{
    padding:10px;
    font-size:12px;
    border-bottom:1px solid #eef2f7;
    vertical-align:top;
}

.mini-table th{
    background:#f8fafc;
    font-size:11px;
    color:#334155;
    text-transform:uppercase;
    letter-spacing:.08em;
    font-weight:800;
}

.mini-table tr:hover td{
    background:#fafcff;
}

/* ===== BADGES ===== */
.badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:5px 8px;
    font-size:11px;
    border-radius:999px;
    font-weight:800;
    text-transform:capitalize;
    white-space:nowrap;
}

.badge-paid{background:#ecfdf5;color:#15803d}
.badge-unpaid{background:#fef2f2;color:#b91c1c}
.badge-advance{background:#fffbeb;color:#b45309}
.badge-due{background:#fff1f2;color:#be123c}

/* ===== LIST ===== */
.list{
    display:flex;
    flex-direction:column;
    gap:8px;
}

.list-item{
    display:flex;
    justify-content:space-between;
    gap:10px;
    padding:10px 11px;
    border-radius:14px;
    border:1px solid #e2e8f0;
    background:linear-gradient(180deg,#fff,#fbfdff);
    transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease;
}

.list-item:hover{
    transform:translateY(-1px);
    box-shadow:0 10px 18px rgba(15,23,42,.05);
    border-color:#d8e1ec;
}

.list-left{
    min-width:0;
}

.list-title{
    font-weight:800;
    color:var(--theme);
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

.list-meta{
    margin-top:4px;
    font-size:12px;
    color:var(--muted);
    line-height:1.35;
}

.list-right{
    text-align:right;
    flex-shrink:0;
}

.amount{
    font-weight:900;
    font-size:16px;
    line-height:1.1;
}

.amount.green{color:var(--green)}
.amount.red{color:var(--red)}
.amount.amber{color:var(--amber)}
.amount.blue{color:var(--blue)}

/* ===== EMPTY STATE ===== */
.empty-state{
    padding:28px 16px;
    text-align:center;
    color:var(--muted);
    background:#f8fafc;
    border:1px dashed #cbd5e1;
    border-radius:16px;
}

.empty-state i{
    display:block;
    font-size:40px;
    margin-bottom:10px;
    color:#94a3b8;
}

/* ===== SECTION SPLIT (Due Alerts + Recent Bills) ===== */
.section-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:14px;
    margin-bottom:16px;
    align-items:stretch;
}

.section-grid > .panel{
    min-height:100%;
}

.section-grid > .panel:first-child{
    border-top:3px solid var(--red);
}

.section-grid > .panel:last-child{
    border-top:3px solid var(--blue);
}

.section-grid .panel-body{
    display:flex;
    flex-direction:column;
}

/* ===== BUTTON ===== */
.view-btn{
    width:32px;
    height:32px;
    border-radius:9px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    background:#eef2f7;
    color:var(--theme);
    border:1px solid #dbe3ec;
    transition:all .2s ease;
    text-decoration:none;
}

.view-btn:hover{
    background:var(--theme);
    color:#fff;
    transform:translateY(-1px);
}

.stat-icon{
    display:none !important;
}
.stat-head{
    justify-content:flex-start;
}
.stat-card{
    padding:18px;
}
/* ===== RESPONSIVE ===== */
@media (max-width:1200px){
    .cards{
        grid-template-columns:repeat(3, minmax(0, 1fr));
    }

    .grid-2,
    .section-grid{
        grid-template-columns:1fr;
    }
}

@media (max-width:768px){
    .dashboard{
        margin-left:0;
        width:100%;
        padding:12px;
        padding-top:80px;
    }

    .hero{
        padding:12px;
        border-radius:16px;
    }

    .hero h1{
        font-size:18px;
    }

    .hero p{
        font-size:11.5px;
    }

    .cards{
        grid-template-columns:1fr;
    }

    .stat-card{
        padding:13px;
    }

    .stat-value{
        font-size:18px;
    }

    .grid-2,
    .section-grid{
        grid-template-columns:1fr;
    }

    .panel-head,
    .panel-body{
        padding:12px;
    }

    .chart-wrap{
        height:220px;
    }

    .mini-table th,
    .mini-table td{
        padding:9px 8px;
        font-size:11px;
    }
}

@media (max-width:480px){
    .hero-badges{
        width:100%;
    }

    .hero-badge{
        flex:1;
        justify-content:center;
    }

    .stat-head{
        gap:8px;
    }

    .list-item{
        padding:9px 10px;
    }

    .amount{
        font-size:15px;
    }
}
</style>
</head>
<body>
<div class="dashboard">
    <div class="hero">
        <div class="hero-top">
            <div>
                <h1><i class="fa-solid fa-chart-line"></i> Agency Dashboard</h1>
                <p>Live overview of sales, due alerts, top-selling products, and the latest bills. Everything is scoped to your agency activity.</p>
            </div>
            <div class="hero-badges">
                <div class="hero-badge"><i class="fa-solid fa-receipt"></i> <?= $totalBills ?> Bills</div>
                <div class="hero-badge"><i class="fa-solid fa-indian-rupee-sign"></i> <?= money($totalSales) ?></div>
                <div class="hero-badge"><i class="fa-solid fa-triangle-exclamation"></i> <?= $dueBills ?> Due Alerts</div>
            </div>
        </div>
    </div>

    <div class="cards">
        <div class="stat-card">
            <div class="stat-head">
                <div>
                    <div class="stat-label">Total Bills</div>
                    <div class="stat-value"><?= $totalBills ?></div>
                    <div class="stat-sub">All agency-linked bills</div>
                </div>
                <div class="stat-icon"><i class="fa-solid fa-receipt"></i></div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-head">
                <div>
                    <div class="stat-label">Total Sales</div>
                    <div class="stat-value"><?= money($totalSales) ?></div>
                    <div class="stat-sub">Current month revenue</div>
                </div>
                <div class="stat-icon"><i class="fa-solid fa-indian-rupee-sign"></i></div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-head">
                <div>
                    <div class="stat-label">Today Sales</div>
                    <div class="stat-value"><?= money($todaySales) ?></div>
                    <div class="stat-sub">Sales generated today</div>
                </div>
                <div class="stat-icon"><i class="fa-solid fa-sun"></i></div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-head">
                <div>
                    <div class="stat-label">Total Due</div>
                    <div class="stat-value"><?= money($totalDue) ?></div>
                    <div class="stat-sub"><?= $dueBills ?> bills pending</div>
                </div>
                <div class="stat-icon"><i class="fa-solid fa-clock"></i></div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-head">
                <div>
                    <div class="stat-label">Active Clients</div>
                    <div class="stat-value"><?= $clients ?></div>
                    <div class="stat-sub">Medical Representatives under scope</div>
                </div>
                <div class="stat-icon"><i class="fa-solid fa-users"></i></div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-head">
                <div>
                    <div class="stat-label">Approved / Pending</div>
                    <div class="stat-value"><?= $paidBills + $advanceBills ?></div>
                    <div class="stat-sub"><?= $paidBills ?> paid, <?= $advanceBills ?> advance</div>
                </div>
                <div class="stat-icon"><i class="fa-solid fa-circle-check"></i></div>
            </div>
        </div>
    </div>

    <div class="grid-2">
        <div class="panel">
            <div class="panel-head">
                <div>
                    <h2 class="panel-title"><i class="fa-solid fa-chart-line"></i> Sales Trend</h2>
                    <div class="panel-sub">Last 7 days performance</div>
                </div>
            </div>
            <div class="panel-body">
                <div class="chart-wrap">
                    <canvas id="salesTrendChart"></canvas>
                </div>
            </div>
        </div>

        <div class="panel">
            <div class="panel-head">
                <div>
                    <h2 class="panel-title"><i class="fa-solid fa-chart-column"></i> Top Selling Products</h2>
                    <div class="panel-sub">Highest quantity sold products</div>
                </div>
            </div>
            <div class="panel-body">
                <div class="chart-wrap" style="height:260px;">
                    <canvas id="topProductsChart"></canvas>
                </div>
                <div style="height:14px"></div>
                <div class="list">
                    <?php if (!empty($topProducts)): ?>
                        <?php foreach ($topProducts as $row): ?>
                            <div class="list-item">
                                <div class="list-left">
                                    <div class="list-title"><?= esc($row['product_name']) ?></div>
                                    <div class="list-meta"><?= esc($row['brand_name'] ?: 'Brand not set') ?></div>
                                </div>
                                <div class="list-right">
                                    <div class="amount blue"><?= (int)$row['total_qty'] ?> pcs</div>
                                    <div class="list-meta"><?= money($row['total_value']) ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fa-regular fa-chart-bar"></i>
                            No product sales data found.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="section-grid">
        <div class="panel">
            <div class="panel-head">
                <div>
                    <h2 class="panel-title"><i class="fa-solid fa-triangle-exclamation"></i> Due Alerts</h2>
                    <div class="panel-sub">Bills with outstanding dues</div>
                </div>
            </div>
            <div class="panel-body">
                <?php if (!empty($dueAlerts)): ?>
                    <table class="mini-table">
                        <thead>
                            <tr>
                                <th>Bill</th>
                                <th>Customer</th>
                                <th>Due</th>
                                <th>Due Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($dueAlerts as $row): ?>
                                <?php
                                    $dueDate = !empty($row['due_date']) ? date('d M Y', strtotime($row['due_date'])) : '-';
                                    $isOverdue = !empty($row['due_date']) && strtotime($row['due_date']) < strtotime(date('Y-m-d'));
                                ?>
                                <tr>
                                    <td>#<?= (int)$row['id'] ?></td>
                                    <td>
                                        <div style="font-weight:800;color:var(--theme)"><?= esc($row['customer_name'] ?: 'Walk-in') ?></div>
                                        <div style="font-size:12px;color:var(--muted)"><?= esc($row['created_by_name'] ?: '') ?></div>
                                    </td>
                                    <td>
                                        <span class="badge badge-due"><?= money($row['due_amount']) ?></span>
                                    </td>
                                    <td>
                                        <span class="badge <?= $isOverdue ? 'badge-unpaid' : 'badge-advance' ?>">
                                            <?= $dueDate ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fa-regular fa-circle-check"></i>
                        No due alerts right now.
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="panel">
            <div class="panel-head">
                <div>
                    <h2 class="panel-title"><i class="fa-solid fa-clock-rotate-left"></i> Last 5 Bills</h2>
                    <div class="panel-sub">Most recent bill activity</div>
                </div>
            </div>
            <div class="panel-body">
                <?php if (!empty($lastBills)): ?>
                    <table class="mini-table">
                        <thead>
                            <tr>
                                <th>Bill</th>
                                <th>Customer</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($lastBills as $row): ?>
                                <tr>
                                    <td>
                                        <div style="font-weight:900;color:var(--theme)">#<?= (int)$row['id'] ?></div>
                                        <div style="font-size:12px;color:var(--muted)"><?= date('d M Y', strtotime($row['created_at'])) ?></div>
                                    </td>
                                    <td>
                                        <div style="font-weight:800;color:var(--theme)"><?= esc($row['customer_name'] ?: 'Walk-in') ?></div>
                                        <div style="font-size:12px;color:var(--muted)"><?= money($row['total_amount']) ?></div>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?= esc($row['payment_status']) ?>">
                                            <?= esc($row['payment_status']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a class="view-btn" href="invoice_view.php?id=<?= (int)$row['id'] ?>" title="View bill">
                                            <i class="fa-solid fa-eye"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fa-regular fa-folder-open"></i>
                        No recent bills found.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
const trendLabels = <?= json_encode($trendLabels, JSON_UNESCAPED_UNICODE) ?>;
const trendValues = <?= json_encode($trendValues, JSON_UNESCAPED_UNICODE) ?>;
const topLabels = <?= json_encode($topLabels, JSON_UNESCAPED_UNICODE) ?>;
const topValues = <?= json_encode($topValues, JSON_UNESCAPED_UNICODE) ?>;

const salesCtx = document.getElementById('salesTrendChart').getContext('2d');
const salesGradient = salesCtx.createLinearGradient(0, 0, 0, 320);
salesGradient.addColorStop(0, 'rgba(37,99,235,0.35)');
salesGradient.addColorStop(1, 'rgba(37,99,235,0.02)');

new Chart(salesCtx, {
    type: 'line',
    data: {
        labels: trendLabels,
        datasets: [{
            data: trendValues,
            borderColor: '#2563eb',
            backgroundColor: salesGradient,
            fill: true,
            tension: 0.38,
            borderWidth: 3,
            pointRadius: 4,
            pointHoverRadius: 6,
            pointBackgroundColor: '#fff',
            pointBorderColor: '#2563eb',
            pointBorderWidth: 2
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { display: false },
            tooltip: {
                callbacks: {
                    label: function(ctx) {
                        return ' ' + new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(ctx.parsed.y || 0);
                    }
                }
            }
        },
        scales: {
            x: {
                grid: { display: false },
                ticks: { color: '#64748b' }
            },
            y: {
                grid: { color: 'rgba(148,163,184,0.18)' },
                ticks: {
                    color: '#64748b',
                    callback: function(value) {
                        return '₹' + value;
                    }
                }
            }
        }
    }
});

const barColors = [
  'rgba(59,130,246,0.7)',  // blue
  'rgba(244,114,182,0.7)', // pink
  'rgba(59,130,246,0.7)',
  'rgba(244,114,182,0.7)',
  'rgba(59,130,246,0.7)',
  'rgba(244,114,182,0.7)'
];
new Chart(document.getElementById('topProductsChart').getContext('2d'), {
    type: 'bar',
    data: {
        labels: topLabels,
        datasets: [{
            data: topValues,
            backgroundColor: barColors.slice(0, topValues.length),
            borderRadius: 10,
            borderSkipped: false
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { display: false }
        },
        scales: {
            x: {
                grid: { display: false },
                ticks: { color: '#64748b' }
            },
            y: {
                beginAtZero: true,
                grid: { color: 'rgba(148,163,184,0.18)' },
                ticks: { color: '#64748b' }
            }
        }
    }
});
</script>
</body>
</html>