<?php
/* $Id: debtoraccount.php - Enhanced with React/Ant Design dashboard */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('Customer Account Management');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

if (isset($_GET['Type']) && $_GET['Type']=='GL') {
    $ViewTopic= 'GeneralLedger';
    $BookMark = 'GLReceipts';
} else {
    $ViewTopic= 'ARTransactions';
    $BookMark = 'CustomerReceipts';
}

$userid = $_SESSION['UserID'];
$timenow = date('Y-m-d H:i:s');

/* ── Direct mysqli for dashboard KPIs ── */
$db_host = 'localhost';
$db_user = 'sooggoo';
$db_pass = '4Compassion*';
$db_name = isset($_SESSION['DatabaseName']) ? $_SESSION['DatabaseName'] : 'evergreenint';
$dbc = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($dbc->connect_error) { $dbc = null; }

$kpi_total_accts = 0; $kpi_unique_custs = 0; $kpi_depts = 0; $kpi_contracted = 0;
$kpi_last_paid_month = 0; $kpi_avg_accts_per_cust = 0;
$deptBreakdown = array();
$topCustomers = array();
$recentAccounts = array();
$billingBreakdown = array();

if ($dbc) {
    /* Total accounts */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM debtoraccount");
    if ($r && $row = $r->fetch_assoc()) { $kpi_total_accts = (int)$row['cnt']; }

    /* Unique customers */
    $r = $dbc->query("SELECT COUNT(DISTINCT debtorno) AS cnt FROM debtoraccount");
    if ($r && $row = $r->fetch_assoc()) { $kpi_unique_custs = (int)$row['cnt']; }

    /* Departments covered */
    $r = $dbc->query("SELECT COUNT(DISTINCT departmentid) AS cnt FROM debtoraccount WHERE departmentid IS NOT NULL AND departmentid > 0");
    if ($r && $row = $r->fetch_assoc()) { $kpi_depts = (int)$row['cnt']; }

    /* Contracted accounts */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM debtoraccount WHERE contracted IS NOT NULL AND contracted != '' AND contracted != '0'");
    if ($r && $row = $r->fetch_assoc()) { $kpi_contracted = (int)$row['cnt']; }

    /* Paid this month */
    $r = $dbc->query("SELECT COUNT(*) AS cnt FROM debtoraccount WHERE YEAR(last_paid_date)=YEAR(CURDATE()) AND MONTH(last_paid_date)=MONTH(CURDATE())");
    if ($r && $row = $r->fetch_assoc()) { $kpi_last_paid_month = (int)$row['cnt']; }

    /* Avg accounts per customer */
    if ($kpi_unique_custs > 0) {
        $kpi_avg_accts_per_cust = round($kpi_total_accts / $kpi_unique_custs, 1);
    }

    /* Accounts by Department (pie chart) */
    $r = $dbc->query("SELECT d.departmentname, COUNT(da.account_number) AS cnt
                      FROM debtoraccount da
                      LEFT JOIN department d ON da.departmentid = d.departmentid
                      WHERE da.departmentid IS NOT NULL AND da.departmentid > 0
                      GROUP BY d.departmentname
                      ORDER BY cnt DESC");
    if ($r) { while ($row = $r->fetch_assoc()) { $deptBreakdown[$row['departmentname']] = (int)$row['cnt']; } }

    /* Top 8 customers by account count */
    $r = $dbc->query("SELECT dm.name, da.debtorno, COUNT(da.account_number) AS acct_count
                      FROM debtoraccount da
                      INNER JOIN debtorsmaster dm ON da.debtorno = dm.debtorno
                      GROUP BY da.debtorno, dm.name
                      ORDER BY acct_count DESC
                      LIMIT 8");
    if ($r) { while ($row = $r->fetch_assoc()) { $topCustomers[] = $row; } }

    /* Recent 5 accounts created (by account_number desc) */
    $r = $dbc->query("SELECT da.account_number, dm.name, d.departmentname, da.contracted, da.last_paid_date
                      FROM debtoraccount da
                      LEFT JOIN debtorsmaster dm ON da.debtorno = dm.debtorno
                      LEFT JOIN department d ON da.departmentid = d.departmentid
                      ORDER BY da.account_number DESC
                      LIMIT 5");
    if ($r) { while ($row = $r->fetch_assoc()) { $recentAccounts[] = $row; } }

    /* Billing name breakdown (bar chart) */
    $r = $dbc->query("SELECT COALESCE(NULLIF(da.billing_name,''), 'Unassigned') AS bname, COUNT(*) AS cnt
                      FROM debtoraccount da
                      GROUP BY bname
                      ORDER BY cnt DESC
                      LIMIT 10");
    if ($r) { while ($row = $r->fetch_assoc()) { $billingBreakdown[$row['bname']] = (int)$row['cnt']; } }
}
?>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>

<style>
/* ── Base ── */
.da-wrap * { box-sizing: border-box; }
.da-wrap {
    font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
    color: #1F2937;
    max-width: 1440px;
    margin: 0 auto;
    padding: 0 20px 20px;
}

/* ── Gradient Banner ── */
.da-banner {
    background: linear-gradient(135deg, #1E8F96 0%, #2AABB3 50%, #35C4CD 100%);
    border-radius: 16px;
    padding: 32px 36px;
    margin: 20px 0 24px;
    color: #fff;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(42,171,179,0.3);
}
.da-banner::before {
    content: '';
    position: absolute;
    top: -40px; right: -40px;
    width: 200px; height: 200px;
    background: rgba(255,255,255,0.06);
    border-radius: 50%;
}
.da-banner::after {
    content: '';
    position: absolute;
    bottom: -60px; right: 80px;
    width: 160px; height: 160px;
    background: rgba(255,255,255,0.04);
    border-radius: 50%;
}
.da-banner h1 { font-size: 26px; font-weight: 700; margin: 0 0 6px; letter-spacing: -0.3px; }
.da-banner p { font-size: 14px; opacity: 0.9; margin: 0; font-weight: 300; }
.da-breadcrumb {
    display: flex; align-items: center; gap: 8px;
    font-size: 13px; color: rgba(255,255,255,0.8); margin-bottom: 12px;
}
.da-breadcrumb a { color: rgba(255,255,255,0.8); text-decoration: none; }
.da-breadcrumb a:hover { color: #fff; }
.da-breadcrumb .sep { opacity: 0.5; }
.da-banner-stats {
    display: flex; gap: 32px; margin-top: 18px;
    padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.15);
}
.da-banner-stat .stat-val { font-size: 22px; font-weight: 700; }
.da-banner-stat .stat-lbl { font-size: 11px; opacity: 0.8; text-transform: uppercase; letter-spacing: 0.5px; }

/* ── Dashboard Toggle ── */
.da-dash-toggle {
    display: flex; align-items: center; gap: 8px;
    cursor: pointer; font-size: 13px; color: #6B7280; font-weight: 500;
    margin-bottom: 16px; user-select: none;
    padding: 8px 14px; background: #F9FAFB; border-radius: 8px;
    width: fit-content; transition: color 0.2s;
}
.da-dash-toggle:hover { color: #2AABB3; }
.da-dash-toggle i.chevron { transition: transform 0.3s; font-size: 11px; }
.da-dash-toggle.collapsed i.chevron { transform: rotate(-90deg); }
.da-dash-wrap {
    overflow: hidden; transition: max-height 0.4s ease, opacity 0.3s;
    max-height: 1200px; opacity: 1;
}
.da-dash-wrap.collapsed { max-height: 0; opacity: 0; }

/* ── KPI Grid ── */
.da-kpi-grid {
    display: grid; grid-template-columns: repeat(4, 1fr);
    gap: 16px; margin-bottom: 20px;
}
.da-kpi {
    background: #fff; border-radius: 12px;
    padding: 20px 22px; border-left: 4px solid #2AABB3;
    box-shadow: 0 1px 8px rgba(0,0,0,0.06);
    transition: transform 0.2s, box-shadow 0.2s;
}
.da-kpi:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0,0,0,0.1); }
.da-kpi-icon {
    width: 42px; height: 42px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px; margin-bottom: 12px;
}
.da-kpi-icon.teal   { background: #E6F7F8; color: #2AABB3; }
.da-kpi-icon.green  { background: #E8F8E8; color: #52C41A; }
.da-kpi-icon.orange { background: #FFF4E6; color: #FAAD14; }
.da-kpi-icon.blue   { background: #E8F4FD; color: #1890FF; }
.da-kpi-icon.purple { background: #F3E8FF; color: #722ED1; }
.da-kpi-icon.red    { background: #FFF1F0; color: #FF4D4F; }
.da-kpi .kpi-value { font-size: 26px; font-weight: 700; color: #1F2937; line-height: 1.1; }
.da-kpi .kpi-label { font-size: 12px; color: #6B7280; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 4px; }

/* ── Panels ── */
.da-panels {
    display: grid; grid-template-columns: 1fr 1fr;
    gap: 16px; margin-bottom: 20px;
}
.da-panel {
    background: #fff; border-radius: 12px;
    box-shadow: 0 1px 8px rgba(0,0,0,0.06);
    border: 1px solid #E5E7EB; overflow: hidden;
}
.da-panel-head {
    padding: 14px 18px; border-bottom: 1px solid #F0F0F0;
    font-weight: 600; font-size: 14px; color: #1F2937;
    display: flex; align-items: center; gap: 8px; background: #FAFBFC;
}
.da-panel-head i { color: #2AABB3; }
.da-panel-body { padding: 16px 18px; }

/* Top customers list */
.da-cust-item {
    display: flex; align-items: center; gap: 12px;
    padding: 8px 0; border-bottom: 1px solid #F5F5F5;
}
.da-cust-item:last-child { border-bottom: none; }
.da-cust-rank {
    width: 28px; height: 28px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 11px; font-weight: 700; flex-shrink: 0;
}
.da-cust-rank.r1 { background: #FFF4E6; color: #AD6800; }
.da-cust-rank.r2 { background: #F0F0F0; color: #595959; }
.da-cust-rank.r3 { background: #FFF1F0; color: #AD4E00; }
.da-cust-rank.rn { background: #F3F4F6; color: #6B7280; }
.da-cust-info { flex: 1; min-width: 0; }
.da-cust-info .da-c-name { font-size: 13px; font-weight: 600; color: #1F2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.da-cust-info .da-c-id { font-size: 11px; color: #9CA3AF; }
.da-cust-count {
    background: #E6F7F8; color: #1E8F96;
    font-size: 12px; font-weight: 700;
    padding: 4px 12px; border-radius: 20px;
    white-space: nowrap;
}

/* Recent accounts */
.da-recent-item {
    display: flex; align-items: center; gap: 12px;
    padding: 10px 0; border-bottom: 1px solid #F5F5F5;
}
.da-recent-item:last-child { border-bottom: none; }
.da-recent-avatar {
    width: 38px; height: 38px; border-radius: 10px;
    background: linear-gradient(135deg, #2AABB3, #1E8F96);
    color: #fff; display: flex; align-items: center; justify-content: center;
    font-size: 12px; font-weight: 700; flex-shrink: 0;
}
.da-recent-info { flex: 1; min-width: 0; }
.da-recent-info .da-r-title { font-size: 13px; font-weight: 600; color: #1F2937; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.da-recent-info .da-r-sub { font-size: 11px; color: #9CA3AF; }
.da-recent-badge {
    display: inline-block; font-size: 10px; font-weight: 600;
    padding: 2px 8px; border-radius: 10px;
}
.da-badge-dept { background: #E8F4FD; color: #096DD9; }
.da-badge-contracted { background: #E8F8E8; color: #389E0D; }

/* Chart */
.da-chart-wrap { position: relative; height: 260px; }

/* ── Responsive ── */
@media (max-width: 1024px) {
    .da-kpi-grid { grid-template-columns: repeat(2, 1fr); }
    .da-panels { grid-template-columns: 1fr; }
}
@media (max-width: 640px) {
    .da-kpi-grid { grid-template-columns: 1fr; }
    .da-banner { padding: 24px 20px; }
    .da-banner h1 { font-size: 20px; }
    .da-banner-stats { flex-wrap: wrap; gap: 16px; }
}
</style>

<div class="da-wrap">

<!-- ── Banner ── -->
<div class="da-banner">
    <div class="da-breadcrumb">
        <a href="index.php"><i class="fas fa-home"></i></a>
        <span class="sep">/</span>
        <a href="index.php">Accounts Receivable</a>
        <span class="sep">/</span>
        <span>Customer Accounts</span>
    </div>
    <h1><i class="fas fa-address-book" style="margin-right:10px;opacity:0.9;"></i>Customer Account Management</h1>
    <p>Manage customer accounts, departments, divisions, and account assignments</p>
    <div class="da-banner-stats">
        <div class="da-banner-stat">
            <div class="stat-val"><?php echo number_format($kpi_total_accts); ?></div>
            <div class="stat-lbl">Total Accounts</div>
        </div>
        <div class="da-banner-stat">
            <div class="stat-val"><?php echo number_format($kpi_unique_custs); ?></div>
            <div class="stat-lbl">Unique Customers</div>
        </div>
        <div class="da-banner-stat">
            <div class="stat-val"><?php echo number_format($kpi_depts); ?></div>
            <div class="stat-lbl">Departments</div>
        </div>
        <div class="da-banner-stat">
            <div class="stat-val"><?php echo number_format($kpi_contracted); ?></div>
            <div class="stat-lbl">Contracted</div>
        </div>
    </div>
</div>

<!-- ── Dashboard Toggle ── -->
<div class="da-dash-toggle" id="daDashToggle" onclick="toggleDaDash()">
    <i class="fas fa-chevron-down chevron"></i>
    <span>Dashboard Overview</span>
</div>

<div class="da-dash-wrap" id="daDashWrap">
    <!-- KPI Cards -->
    <div class="da-kpi-grid">
        <div class="da-kpi">
            <div class="da-kpi-icon teal"><i class="fas fa-address-book"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_total_accts); ?></div>
            <div class="kpi-label">Total Accounts</div>
        </div>
        <div class="da-kpi" style="border-left-color:#1890FF;">
            <div class="da-kpi-icon blue"><i class="fas fa-users"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_unique_custs); ?></div>
            <div class="kpi-label">Unique Customers</div>
        </div>
        <div class="da-kpi" style="border-left-color:#722ED1;">
            <div class="da-kpi-icon purple"><i class="fas fa-layer-group"></i></div>
            <div class="kpi-value"><?php echo $kpi_avg_accts_per_cust; ?></div>
            <div class="kpi-label">Avg Accounts / Customer</div>
        </div>
        <div class="da-kpi" style="border-left-color:#52C41A;">
            <div class="da-kpi-icon green"><i class="fas fa-file-contract"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_contracted); ?></div>
            <div class="kpi-label">Contracted Accounts</div>
        </div>
    </div>

    <!-- Row 1: Pie Chart + Top Customers -->
    <div class="da-panels">
        <!-- Department Pie Chart -->
        <div class="da-panel">
            <div class="da-panel-head"><i class="fas fa-chart-pie"></i> Accounts by Department</div>
            <div class="da-panel-body">
                <div class="da-chart-wrap">
                    <canvas id="daDeptChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Top Customers by Account Count -->
        <div class="da-panel">
            <div class="da-panel-head"><i class="fas fa-trophy"></i> Top Customers by Account Count</div>
            <div class="da-panel-body">
                <?php if (empty($topCustomers)) { ?>
                    <div style="text-align:center;padding:20px;color:#9CA3AF;font-size:13px;">
                        <i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;color:#D1D5DB;"></i>
                        No data available
                    </div>
                <?php } else { $rank = 0; foreach ($topCustomers as $tc) { $rank++;
                    $rankClass = ($rank == 1) ? 'r1' : (($rank == 2) ? 'r2' : (($rank == 3) ? 'r3' : 'rn'));
                ?>
                <div class="da-cust-item">
                    <div class="da-cust-rank <?php echo $rankClass; ?>"><?php echo $rank; ?></div>
                    <div class="da-cust-info">
                        <div class="da-c-name"><?php echo htmlspecialchars($tc['name']); ?></div>
                        <div class="da-c-id">ID: <?php echo $tc['debtorno']; ?></div>
                    </div>
                    <div class="da-cust-count"><?php echo $tc['acct_count']; ?> acct<?php echo ($tc['acct_count'] > 1) ? 's' : ''; ?></div>
                </div>
                <?php } } ?>
            </div>
        </div>
    </div>

    <!-- Row 2: Recent Accounts + Division Bar Chart -->
    <div class="da-panels">
        <!-- Recent Accounts -->
        <div class="da-panel">
            <div class="da-panel-head"><i class="fas fa-history"></i> Latest Accounts</div>
            <div class="da-panel-body">
                <?php if (empty($recentAccounts)) { ?>
                    <div style="text-align:center;padding:20px;color:#9CA3AF;font-size:13px;">No recent accounts</div>
                <?php } else { foreach ($recentAccounts as $ra) {
                    $custName = isset($ra['name']) ? $ra['name'] : 'N/A';
                    $init = strtoupper(substr($custName,0,2));
                    $deptName = isset($ra['departmentname']) ? $ra['departmentname'] : '';
                    $isContracted = isset($ra['contracted']) && $ra['contracted'] != '' && $ra['contracted'] != '0';
                ?>
                <div class="da-recent-item">
                    <div class="da-recent-avatar"><?php echo $init; ?></div>
                    <div class="da-recent-info">
                        <div class="da-r-title"><?php echo htmlspecialchars($ra['account_number']); ?> — <?php echo htmlspecialchars($custName); ?></div>
                        <div class="da-r-sub">
                            <?php if ($deptName) { ?><span class="da-recent-badge da-badge-dept"><?php echo htmlspecialchars($deptName); ?></span><?php } ?>
                            <?php if ($isContracted) { ?> <span class="da-recent-badge da-badge-contracted"><i class="fas fa-check" style="margin-right:3px;"></i>Contracted</span><?php } ?>
                            <?php if (isset($ra['last_paid_date']) && $ra['last_paid_date'] != '' && $ra['last_paid_date'] != '0000-00-00') { ?>
                                <span style="font-size:10px;color:#9CA3AF;margin-left:6px;">Last paid: <?php echo date('d M Y', strtotime($ra['last_paid_date'])); ?></span>
                            <?php } ?>
                        </div>
                    </div>
                </div>
                <?php } } ?>
            </div>
        </div>

        <!-- Billing Name Bar Chart -->
        <div class="da-panel">
            <div class="da-panel-head"><i class="fas fa-chart-bar"></i> Top Billing Names</div>
            <div class="da-panel-body">
                <div class="da-chart-wrap">
                    <canvas id="daBillingChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ── XCRUD Table (untouched) ── -->
<?php
    echo '<div class="col-sm-12">';

    include('xcrud/xcrud.php');
    $xcrud = Xcrud::get_instance();
    $xcrud->table('debtoraccount');

    $xcrud->relation('debtorno','debtorsmaster','debtorno',array('name','debtorno'));
    $xcrud->relation('branchcode','custbranch','branchcode','brname','','','','','','branchcode','debtorno');
    $xcrud->relation('departmentid','department','departmentid','departmentname');

    $xcrud->label('debtorno','Customer Name');
    $xcrud->label('branchcode','Customer Branch');
    $xcrud->label('departmentid','Department');
    $xcrud->column_name('debtorno','Customer Name');
    $xcrud->column_name('branchcode','Customer Branch');
    $xcrud->column_name('departmentid','Department');

    /* ── Hide unused balance/financial fields ── */
    $xcrud->columns('account_number,billing_name,sub_billing_name,debtorno,branchcode,departmentid,contracted,last_paid,last_paid_date',false);
    $xcrud->fields('account_number,billing_name,sub_billing_name,debtorno,branchcode,departmentid,contracted,last_paid,last_paid_date',false);

    $xcrud->table_name('Customer Account Management');

    $xcrud->sum('balance');

    /* Row highlights by department */
    $xcrud->highlight_row('departmentid','=','1','#e6ff99');
    $xcrud->highlight_row('departmentid','=','2','#e6ffff');
    $xcrud->highlight_row('departmentid','=','11','#ffe6ff');
    $xcrud->highlight_row('departmentid','=','6','#ffcce0');
    $xcrud->highlight_row('departmentid','=','7','#ffcce0');
    $xcrud->highlight_row('departmentid','=','8','#ffcce0');
    $xcrud->highlight_row('departmentid','=','9','#ff9980');
    $xcrud->highlight_row('departmentid','=','10','#ff9980');
    $xcrud->highlight_row('departmentid','=','21','#ff9980');

    $xcrud->order_by('account_number','desc');
    $xcrud->button('PrintStatements.php?FromCust={debtorno}&accountnumber={account_number}', 'Print Latest Statement','glyphicon glyphicon-download-alt','westpac');

    $xcrud->column_pattern('debtorno', '<a href="#" class="xcrud-action" data-task="view" data-primary="{account_number}">{value}</a>');

    /* ── Nested Table: Customer Details ── */
    $details = $xcrud->nested_table('Customer Details','debtorno','debtorsmaster','debtorno');
    $details->disabled('debtorno');
    $details->label('address1','Street Address');
    $details->label('address2','Street Address');
    $details->label('address3','Surburb');
    $details->label('address4','State');
    $details->label('address5','PostCode');
    $details->label('address6','Country');

    echo $xcrud->render();
    echo '</div>';
?>

</div><!-- end da-wrap -->

<!-- ── Dashboard JS ── -->
<script>
/* Dashboard toggle with localStorage */
function toggleDaDash() {
    var wrap = document.getElementById('daDashWrap');
    var toggle = document.getElementById('daDashToggle');
    if (wrap.classList.contains('collapsed')) {
        wrap.classList.remove('collapsed');
        toggle.classList.remove('collapsed');
        localStorage.setItem('daAcctDashCollapsed', 'false');
    } else {
        wrap.classList.add('collapsed');
        toggle.classList.add('collapsed');
        localStorage.setItem('daAcctDashCollapsed', 'true');
    }
}
(function(){
    if (localStorage.getItem('daAcctDashCollapsed') === 'true') {
        document.getElementById('daDashWrap').classList.add('collapsed');
        document.getElementById('daDashToggle').classList.add('collapsed');
    }
})();

/* Department Pie/Doughnut Chart */
(function(){
    var ctx = document.getElementById('daDeptChart');
    if (!ctx) return;
    var labels = <?php echo json_encode(array_keys($deptBreakdown)); ?>;
    var data = <?php echo json_encode(array_values($deptBreakdown)); ?>;
    var palette = ['#2AABB3','#1890FF','#52C41A','#FAAD14','#722ED1','#FF4D4F','#13C2C2','#EB2F96',
                   '#FA8C16','#A0D911','#2F54EB','#F5222D','#87D068','#108EE9','#FF85C0'];
    var colors = labels.map(function(l,i){ return palette[i % palette.length]; });

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{ data: data, backgroundColor: colors, borderWidth: 2, borderColor: '#fff' }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '55%',
            plugins: {
                legend: {
                    position: 'right',
                    labels: { font: { family: 'Poppins', size: 11 }, padding: 10, usePointStyle: true, pointStyleWidth: 8 }
                },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            var total = ctx.dataset.data.reduce(function(a,b){ return a+b; }, 0);
                            var pct = total > 0 ? ((ctx.parsed / total) * 100).toFixed(1) : 0;
                            return ctx.label + ': ' + ctx.parsed + ' accounts (' + pct + '%)';
                        }
                    }
                }
            }
        }
    });
})();

/* Billing Name Bar Chart */
(function(){
    var ctx = document.getElementById('daBillingChart');
    if (!ctx) return;
    var labels = <?php echo json_encode(array_keys($billingBreakdown)); ?>;
    var data = <?php echo json_encode(array_values($billingBreakdown)); ?>;

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Accounts',
                data: data,
                backgroundColor: 'rgba(42,171,179,0.7)',
                borderColor: '#2AABB3',
                borderWidth: 1,
                borderRadius: 6,
                barPercentage: 0.65
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            plugins: {
                legend: { display: false }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0,0,0,0.04)' },
                    ticks: { font: { family: 'Poppins', size: 11 } }
                },
                y: {
                    grid: { display: false },
                    ticks: { font: { family: 'Poppins', size: 11 } }
                }
            }
        }
    });
})();
</script>

<?php
if ($dbc) { $dbc->close(); }

/* ── Footer / Menu Logic (preserved) ── */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
    echo '<table class="table_index">
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p></td></tr>
        </table>';
    include('includes/footer.inc');
    exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
    echo '<table class="table_index">
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p></td></tr>
            <tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p></td></tr>
        </table>';
    include('includes/footer.inc');
    exit;
}

if (isset($_GET['Application'])){
    $_SESSION['Module'] = $_GET['Application'];
}

function GetRptLinks($GroupID) {
    global $db, $RootPath, $ReportList;
    require_once('reportwriter/languages/en_US/reports.php');
    require_once('reportwriter/admin/defaults.php');
    $GroupID=$ReportList[$GroupID];
    $Title= array(_('Custom Reports'), _('Standard Reports and Forms'));
    $sql= "SELECT id, reporttype, defaultreport, groupname, reportname FROM reports ORDER BY groupname, reportname";
    $Result=DB_query($sql,'','',false,true);
    $ReportList = '';
    while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;
    $RptLinks = '';
    for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers"><b>' .  $Title[$Def] . '</b></li>';
        $NoEntries = true;
        if ($ReportList) {
            foreach ($ReportList as $Report) {
                if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p></li>';
                    $NoEntries = false;
                }
            }
            $NoForms = true;
            foreach ($ReportList as $Report) {
                $Group=explode(':',$Report['groupname']);
                if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item"><img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
                    $RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
                    $RptLinks .= $FormGroups[$Report['groupname']] . '</a></li>';
                    $NoForms = false;
                    $NoEntries = false;
                }
            }
        }
        if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
    }
    return $RptLinks;
}
?>

<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
});
</script>
