<?php $this->load->view("partial/header"); ?>

<script type="text/javascript">
	dialog_support.init("a.modal-dlg");
</script>

<div id="page_title"><?php echo $title ?></div>

<div id="page_subtitle"><?php echo $subtitle ?></div>


<div id="table_holder">
	<table id="table"></table>
</div>


<?php
/** * THE CFO BRAIN: Single Source of Truth 
 * Standardizing all variables and fixing "Undefined" notices
 */

// --- 1. FUNDAMENTALS ---
$total_sales    = (float)($summary_data['total'] ?? 0);
$net_sales      = (float)($summary_data['subtotal'] ?? 0); 
$total_cost     = (float)($summary_data['cost'] ?? 0);
$total_tax      = (float)($summary_data['tax'] ?? 0);
$total_profit    = (float)($summary_data['profit'] ?? 0);
$total_discount  = (float)($summary_data['discount_value'] ?? $summary_data['discount'] ?? 0);
$total_txns      = (int)($summary_data['total_transactions'] ?? 0);
$total_qty       = (float)($summary_data['total_quantity'] ?? 0);

// --- 2. EXPENSE & DATE ENGINE ---
$fixed_monthly     = (float)$this->config->item('fixed_monthly_expenses') ?: 0;
$recorded_expenses = (float)($summary_data['expenses_overall'] ?? 0);
$active_expenses   = ($recorded_expenses > 0) ? $recorded_expenses : $fixed_monthly;

$s_date = $this->input->get('start_date') ?: date('Y-m-d');
$e_date = $this->input->get('end_date') ?: date('Y-m-d');
$days_count = (new DateTime($s_date))->diff(new DateTime($e_date))->days + 1;

// --- 3. BREAK-EVEN & PREDICTED SAFETY DAY ---
$margin_dec       = ($total_sales > 0) ? ($total_profit / $total_sales) : 0.0001;
$breakeven_target = ($margin_dec > 0) ? ($active_expenses / $margin_dec) : 0;
$survival_gap     = $total_sales - $breakeven_target;
$required_daily   = ($days_count > 0) ? ($breakeven_target / $days_count) : 0;
$be_progress      = ($breakeven_target > 0) ? ($total_sales / $breakeven_target) * 100 : 0;

// Velocity math for the "Safety Day" prediction
$velocity = ($days_count > 0) ? ($be_progress / $days_count) : 0;
$predicted_be_day = ($velocity > 0) ? (int)ceil(100 / $velocity) : 0;

// --- 4. CASH RUNWAY & BURN ---
$daily_burn       = ($days_count > 0) ? ($active_expenses / $days_count) : ($active_expenses / 30);
$net_cash_pos     = $total_sales - $active_expenses;
$runway_days      = ($net_cash_pos > 0 && $daily_burn > 0) ? floor($net_cash_pos / $daily_burn) : 0;

// --- 5. PERFORMANCE METRICS ---
$avg_order_value = ($total_txns > 0) ? ($total_sales / $total_txns) : 0;
$ipt             = ($total_txns > 0) ? ($total_qty / $total_txns) : 0; 
$daily_avg_sales = ($days_count > 0) ? ($total_sales / $days_count) : 0;

$growth_target   = (float)$this->config->item('daily_sales_goal') ?: 0;
$growth_pct      = ($growth_target > 0) ? ($daily_avg_sales / $growth_target) * 100 : 0;

// --- 6. MARGIN SAFETY (THE SHIELD) ---
$ideal_sales      = $total_sales + $total_discount; 
$margin_leakage   = ($ideal_sales > 0) ? ($total_discount / $ideal_sales) * 100 : 0;
$effective_margin = $margin_dec * 100;

// --- 7. INVENTORY INTELLIGENCE ---
$inv_cost_val     = (float)($summary_data['inventory_cost_value'] ?? 0);
$gmroi            = ($inv_cost_val > 0) ? ($total_profit / $inv_cost_val) : 0;
$doi              = ($total_cost > 0 && $inv_cost_val > 0) ? ($inv_cost_val / ($total_cost / $days_count)) : 0;

// --- 9. DOMINANT CHANNEL LOGIC ---
$max_payment_amt = 0;
$dominant_channel = 'None';
if(isset($data)) {
    foreach($data as $row) {
        if(isset($row['trans_group']) && strtolower($row['trans_group']) == 'payments') {
            $p_amt = (float)filter_var($row['trans_payments'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
            if($p_amt > $max_payment_amt) {
                $max_payment_amt = $p_amt;
                $dominant_channel = $row['trans_type'];
            }
        }
    }
}
// Categorize the channel
$is_digital = (preg_match('/(card|mpesa|bank|online|stripe|paypal|transfer)/i', $dominant_channel));
$channel_label = $is_digital ? "DIGITAL-HEAVY" : "CASH-HEAVY";
$channel_color = $is_digital ? "var(--accent-blue)" : "var(--accent-orange)";


// --- 8. CASHFLOW CALCULATIONS (The missing calc_paid / collection_realization) ---
$calc_paid = 0; 
$calc_due  = 0;

if(isset($data)) {
    foreach($data as $row) {
        // We only calculate payments from rows marked as 'payments' or totals
        $p_val = (float)filter_var($row['trans_payments'] ?? 0, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        $d_val = (float)filter_var($row['trans_due'] ?? 0, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        
        // Add to totals if the group is 'payments'
        if(isset($row['trans_group']) && strtolower($row['trans_group']) == 'payments') {
            $calc_paid += $p_val;
        }
        $calc_due += $d_val;
    }
}
$collection_realization = (($calc_paid + $calc_due) > 0) ? ($calc_paid / ($calc_paid + $calc_due)) * 100 : 0;
?>


<div id="report_summary">
    <?php
    foreach($summary_data as $name => $value)
    { 
        // 1. Skip Tables: We don't want to print "Array" for our Best Seller lists
        if (is_array($value)) continue;

        // 2. Define non-currency fields
        $non_currency_fields = [
            'total_quantity', 
            'discount_count', 
            'sku_count', 
            'inventory_count', 
            'inventory_distinct_skus', 
            'total_transactions',
            'best_seller' // This is a name, not money
        ];

        // 3. Render the row
        if (in_array($name, $non_currency_fields))
        {
            // Print as a raw number or text (No Ksh)
            $display_value = is_numeric($value) ? number_format($value) : $value;
    ?>
            <div class="summary_row"><?php echo $this->lang->line('reports_'.$name) . ': ' . $display_value; ?></div>
    <?php
        }
        else
        {
            // Print as Currency (Ksh)
    ?>
            <div class="summary_row"><?php echo $this->lang->line('reports_'.$name) . ': ' . to_currency($value); ?></div>
    <?php
        }
    }
    ?>
</div>
<!-------------------------------------------------SUMMARY CARD--------------------------------------------->
<style>
    /* 1. DASHBOARD THEME VARIABLES */
    :root {
        --bg-body: #f8fafc;
        --card-bg: #ffffff;
        --text-main: #1e293b;
        --text-muted: #64748b;
        --accent-blue: #3b82f6;   /* Performance */
        --accent-green: #10b981;  /* Profits/Collected */
        --accent-red: #ef4444;    /* Costs/Outstanding */
        --accent-orange: #f59e0b; /* Invoices/Pending */
        --accent-purple: #8b5cf6; /* Tax/Discounts */
        --radius: 12px;
        --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
    }

    #executive_dashboard { background: var(--bg-body); padding: 5px; border-radius: var(--radius); font-family: 'Inter', sans-serif; }

    /* 2. CARD ARCHITECTURE */
    .summary-card {
        background: var(--card-bg);
        border: 1px solid #e2e8f0;
        border-radius: var(--radius);
        box-shadow: var(--shadow);
        padding: 18px;
        margin-bottom: 15px;
        display: flex;
        flex-direction: column;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .summary-card:hover {
        box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
        transform: translateY(-2px);
    }

    /* 3. TYPOGRAPHY & TEXT */
    .card-label {
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        font-weight: 700;
        color: var(--text-muted);
        margin-bottom: 6px;
    }

    .card-value {
        font-size: 1.4rem;
        font-weight: 800;
        color: var(--text-main);
        line-height: 1.2;
    }

    .section-header {
        font-size: 0.85rem;
        font-weight: 800;
        color: var(--text-main);
        margin: 35px 0 15px 0;
        display: flex;
        align-items: center;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .section-header::after {
        content: ""; flex: 1; height: 1px; background: #e2e8f0; margin-left: 15px;
    }

    /* 4. METRIC GRIDS & PROGRESS BARS */
    .metric-grid {
        display: grid; grid-template-columns: 1fr 1fr; gap: 10px;
        margin-top: 12px; padding-top: 12px; border-top: 1px solid #f1f5f9;
    }
    .metric-item { display: flex; flex-direction: column; }
    .metric-label { font-size: 9px; text-transform: uppercase; color: var(--text-muted); font-weight: 700; }
    .metric-value { font-size: 11px; font-weight: 700; color: var(--text-main); }

    .efficiency-wrapper { margin-top: 12px; }
    .progress-container { width: 100%; height: 6px; background-color: #f1f5f9; border-radius: 10px; overflow: hidden; margin-bottom: 4px; }
    .progress-bar { height: 100%; border-radius: 10px; transition: width 0.5s ease; }
    .efficiency-stats { display: flex; justify-content: space-between; font-size: 10px; font-weight: 700; color: var(--text-muted); }

    /* 5. UTILITY CLASSES */
    .text-success-modern { color: var(--accent-green) !important; }
    .text-danger-modern { color: var(--accent-red) !important; }
    .text-primary-modern { color: var(--accent-blue) !important; }
    
    .type-pos { border-left: 4px solid var(--accent-blue); }
    .type-invoice { border-left: 4px solid var(--accent-orange); }
    .type-return { border-left: 4px solid var(--accent-red); }
    
    
    .insight-badge {
        background: #f1f5f9;
        color: var(--text-main);
        padding: 4px 8px;
        border-radius: 6px;
        font-size: 11px;
        font-weight: 700;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        margin-top: 10px;
    }
    
    /* NEW HIERARCHY CLASSES */
    .kpi-main { 
        font-size: 1.8rem; /* Level 1: BIG */
        display: block; 
        letter-spacing: -1px;
    }
    .kpi-sub { 
        font-size: 1.1rem; /* Level 2: Medium */
        color: var(--text-main);
        font-weight: 700;
    }
    .kpi-label-main {
        font-size: 0.85rem;
        color: var(--text-main);
        font-weight: 800;
        margin-bottom: 2px;
    }
    /* Visual separation for the sub-sections */
    .sub-metric-row {
        margin-top: 10px;
        padding-top: 8px;
        border-top: 1px dashed #e2e8f0;
    }
    
    /* KPI HIERARCHY */
    .kpi-main-value { 
        font-size: 1.9rem !important; 
        font-weight: 900 !important; 
        letter-spacing: -1px;
        line-height: 1;
        display: block;
        margin-bottom: 4px;
    }
    .kpi-label-top {
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--text-muted);
        text-transform: uppercase;
        margin-bottom: 8px;
    }
    .kpi-divider {
        margin: 12px 0;
        border-top: 1px solid #f1f5f9;
        padding-top: 12px;
    }
    .kpi-sub-label {
        font-size: 0.7rem;
        font-weight: 700;
        color: var(--text-muted);
        text-transform: uppercase;
    }
    .kpi-sub-value {
        font-size: 1.2rem;
        font-weight: 700;
        color: var(--text-main);
        
        /* SURVIVAL PROGRESS BAR */
    .progress-container {
        background-color: #e2e8f0;
        border-radius: 10px;
        height: 8px;
        width: 100%;
        margin: 10px 0;
        overflow: hidden;
    }
    .progress-fill {
        height: 100%;
        transition: width 0.5s ease-in-out;
    }
    .status-tag {
        font-size: 0.65rem;
        padding: 2px 8px;
        border-radius: 4px;
        font-weight: 800;
        text-transform: uppercase;
    }
    }
</style>

<div id="executive_dashboard">
    
    <h5 class="section-header">Heartbeat & Margin Safety</h5>
    <div class="row">
        <div class="col-md-6">
            <div class="summary-card" style="border-top: 4px solid var(--accent-green);">
                <div class="kpi-label-top">Level 1: Profitability</div>
                <span class="kpi-main-value text-success-modern"><?php echo to_currency($total_profit); ?></span>
                <div class="row">
                    <div class="col-xs-4">
                        <span class="kpi-sub-label">Margin</span>
                        <div class="kpi-sub"><?php echo number_format($effective_margin, 1); ?>%</div>
                    </div>
                    <div class="col-xs-4">
                        <span class="kpi-sub-label">Markup</span>
                        <div class="kpi-sub"><?php echo ($total_cost > 0) ? round(($total_profit/$total_cost)*100, 1) : 0; ?>%</div>
                    </div>
                    <div class="col-xs-4">
                        <span class="kpi-sub-label">Growth Goal</span>
                        <div class="kpi-sub"><?php echo number_format($growth_pct, 0); ?>%</div>
                    </div>
                </div>

                <div class="kpi-divider"></div>
                
                <div class="kpi-label-top">Level 2: Profit Components</div>
                <div class="row">
                    <div class="col-xs-6">
                        <span class="kpi-sub-label">Net Sales</span>
                        <div class="metric-value"><?php echo to_currency($net_sales); ?></div>
                    </div>
                    <div class="col-xs-6 text-right">
                        <span class="kpi-sub-label">COGS</span>
                        <div class="metric-value"><?php echo to_currency($total_cost); ?></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="summary-card" style="border-top: 4px solid var(--accent-purple);">
                <div class="kpi-label-top">Level 1: Effective Margin (The Shield)</div>
                <span class="kpi-main-value" style="color: var(--accent-purple);"><?php echo number_format($effective_margin, 1); ?>%</span>
                
                <div class="kpi-divider"></div>
                
                <div class="kpi-label-top">Level 2: Leakage & Impacts</div>
                <div class="row">
                    <div class="col-xs-4">
                        <span class="kpi-sub-label">Discount Impact</span>
                        <div class="text-danger-modern">-<?php echo number_format($margin_leakage, 1); ?>%</div>
                    </div>
                    <div class="col-xs-4 text-center">
                        <span class="kpi-sub-label">Disc. Count</span>
                        <div><?php echo $summary_data['discount_count'] ?? 0; ?></div>
                    </div>
                    <div class="col-xs-4 text-right">
                        <span class="kpi-sub-label">Returns</span>
                        <div class="text-danger-modern"><?php echo to_currency($summary_data['returns_total'] ?? 0); ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <h5 class="section-header">Survival & Runway</h5>
    <div class="row">
        <div class="col-md-12">
            <div class="summary-card" style="border-top: 4px solid <?php echo ($survival_gap >= 0) ? 'var(--accent-green)' : 'var(--accent-orange)'; ?>;">
                <div class="row">
                    <div class="col-md-3">
                        <div class="kpi-label-top">Level 1: Monthly Gap</div>
                        <div class="kpi-main-value <?php echo ($survival_gap >= 0) ? 'text-success-modern' : 'text-danger-modern'; ?>">
                            <?php echo to_currency($survival_gap); ?>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="kpi-label-top">Recovery Pace Req.</div>
                        <div class="kpi-main-value" style="font-size: 1.4rem !important;"><?php echo to_currency($required_daily); ?>/day</div>
                    </div>
                    <div class="col-md-3">
                        <div class="kpi-label-top">Cash Runway</div>
                        <div class="kpi-main-value text-primary-modern"><?php echo $runway_days; ?> Days</div>
                    </div>
                    <div class="col-md-3">
                        <div class="kpi-label-top">Safety Day (EST)</div>
                        <div class="kpi-main-value"><?php echo $predicted_be_day; ?><sup>th</sup></div>
                    </div>
                </div>

                <div class="kpi-divider"></div>

                <div class="kpi-label-top">Level 2: Survival Diagnostics</div>
                <div class="row">
                    <div class="col-xs-2">
                        <span class="kpi-sub-label">Total Sales</span>
                        <div class="metric-value"><?php echo to_currency($total_sales); ?></div>
                    </div>
                    <div class="col-xs-2">
                        <span class="kpi-sub-label">Avg Daily</span>
                        <div class="metric-value"><?php echo to_currency($daily_avg_sales); ?></div>
                    </div>
                    <div class="col-xs-3">
                        <span class="kpi-sub-label">Fixed + Variable</span>
                        <div class="metric-value"><?php echo to_currency($active_expenses); ?></div>
                    </div>
                    <div class="col-xs-2">
                        <span class="kpi-sub-label">Daily Target</span>
                        <div class="metric-value"><?php echo to_currency($growth_target); ?></div>
                    </div>
                    <div class="col-xs-3 text-right">
                        <span class="kpi-sub-label">Daily Burn</span>
                        <div class="text-danger-modern"><?php echo to_currency($daily_burn); ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <h5 class="section-header">Performance & Inventory</h5>
    <div class="row">
        <div class="col-md-6">
            <div class="summary-card">
                <div class="kpi-label-top">The Engine Room (Performance)</div>
                <div class="metric-grid" style="grid-template-columns: repeat(3, 1fr); border-top:none;">
                    <div class="metric-item">
                        <span class="metric-label">Avg Daily Sale</span>
                        <span class="metric-value"><?php echo to_currency($daily_avg_sales); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Avg Order Val</span>
                        <span class="metric-value"><?php echo to_currency($avg_order_value); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Items / Txn</span>
                        <span class="metric-value"><?php echo number_format($ipt, 1); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Visits</span>
                        <span class="metric-value"><?php echo number_format($total_txns); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Items Sold</span>
                        <span class="metric-value"><?php echo number_format($total_qty); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Returns Qty</span>
                        <span class="metric-value"><?php echo number_format($summary_data['returns_count'] ?? 0); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="summary-card">
                <div class="kpi-label-top">Inventory (Money on the Floor)</div>
                <div class="row">
                    <div class="col-xs-6">
                        <span class="kpi-sub-label">Level 1: DOI (Coverage)</span>
                        <div class="kpi-main-value" style="font-size: 1.5rem !important;"><?php echo number_format($doi, 0); ?> Days</div>
                    </div>
                    <div class="col-xs-6 text-right">
                        <span class="kpi-sub-label">GMROI</span>
                        <div class="kpi-main-value text-success-modern" style="font-size: 1.5rem !important;"><?php echo number_format($gmroi, 2); ?>x</div>
                    </div>
                </div>
                <div class="kpi-divider"></div>
                <div class="row">
                    <div class="col-xs-4">
                        <span class="kpi-sub-label">SKUs Sold</span>
                        <div class="metric-value"><?php echo number_format($summary_data['inventory_distinct_skus'] ?? 0); ?></div>
                    </div>
                    <div class="col-xs-4 text-center">
                        <span class="kpi-sub-label">Stock Count</span>
                        <div class="metric-value"><?php echo number_format($summary_data['inventory_count'] ?? 0); ?></div>
                    </div>
                    <div class="col-xs-4 text-right">
                        <span class="kpi-sub-label">Avg Inv Val</span>
                        <div class="metric-value"><?php echo to_currency($inv_cost_val); ?></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <h5 class="section-header">Compliance & Cashflow</h5>
    <div class="row">
        <div class="col-md-6">
            <div class="summary-card" style="border-right: 4px solid <?php echo $channel_color; ?>;">
                <div class="kpi-label-top">Cashflow & Loyalty</div>
                <div class="row">
                    <div class="col-xs-4">
                        <span class="kpi-sub-label">Collection Rate</span>
                        <div class="kpi-sub"><?php echo round($collection_realization, 1); ?>%</div>
                    </div>
                    <div class="col-xs-4 text-center">
                        <span class="kpi-sub-label">Debt-to-Cash</span>
                        <div class="kpi-sub"><?php echo ($calc_paid > 0) ? round(($calc_due/$calc_paid)*100, 1) : 0; ?>%</div>
                    </div>
                    <div class="col-xs-4 text-right">
                        <span class="kpi-sub-label">Primary Channel</span>
                        <div style="font-size: 10px; font-weight: bold; color: white; background: <?php echo $channel_color; ?>; padding: 2px 6px; border-radius: 4px; display: inline-block; margin-top: 5px;">
                            <?php echo $channel_label; ?>
                        </div>
                        <div style="font-size: 11px; color: <?php echo $channel_color; ?>; font-weight: bold;">
                            via <?php echo $dominant_channel; ?>
                        </div>
                    </div>
                </div>
                
                <div class="kpi-divider"></div>
                <div class="row">
                    <div class="col-xs-6">
                        <span class="kpi-sub-label">Collection Realization</span>
                        <div class="progress-container" style="height:6px; margin-top:5px;">
                            <div class="progress-bar" style="width:<?php echo $collection_realization; ?>%; background: var(--accent-green);"></div>
                        </div>
                    </div>
                    <div class="col-xs-6 text-right">
                        <span class="kpi-sub-label">Repeat Customer Rate</span>
                        <div class="kpi-sub">--%</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php if(isset($data) && $title == $this->lang->line('reports_payments_summary_report')): ?>
        <h5 class="section-header">Transaction Analysis (Sales Mix)</h5>
        <div class="row">
            <?php foreach($data as $row): ?>
                <?php 
                    // Filter for sales groups only
                    if($row['trans_group'] == '--' || strtolower($row['trans_group']) != 'sales') continue; 
                    
                    $r_amt = (float)filter_var($row['trans_amount'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
                    $r_paid = (float)filter_var($row['trans_payments'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
                    $eff = ($r_amt != 0) ? ($r_paid / $r_amt) * 100 : 0;
                    
                    // Styling based on transaction nature
                    $type_class = (stripos($row['trans_type'], 'invoice') !== false) ? 'type-invoice' : ((stripos($row['trans_type'], 'return') !== false) ? 'type-return' : 'type-pos');
                ?>
                <div class="col-6 col-md-4 col-lg-3">
                    <div class="summary-card <?php echo $type_class; ?>" style="border-left: 3px solid var(--accent-blue);">
                        <div class="card-label"><?php echo $row['trans_type']; ?></div>
                        <span class="card-value" style="font-size: 1.2rem;"><?php echo $row['trans_amount']; ?></span>
                        
                        <div class="efficiency-wrapper">
                            <div class="progress-container">
                                <div class="progress-bar" style="width:<?php echo min(max($eff, 0), 100); ?>%; background: var(--accent-blue);"></div>
                            </div>
                            <div class="efficiency-stats">
                                <span>Collected</span>
                                <span><?php echo number_format($eff, 0); ?>%</span>
                            </div>
                        </div>
                        
                        <div class="metric-grid" style="grid-template-columns: 1fr 1fr; border-top: 1px solid #f1f5f9; margin-top: 10px; padding-top: 10px;">
                            <div class="metric-item">
                                <span class="metric-label">Actual Paid</span>
                                <span class="metric-value text-success-modern" style="font-size: 0.9rem;"><?php echo $row['trans_payments']; ?></span>
                            </div>
                            <div class="metric-item">
                                <span class="metric-label">Avg/Sale</span>
                                <span class="metric-value" style="font-size: 0.9rem;"><?php echo ($row['trans_sales'] > 0) ? number_format($r_amt/$row['trans_sales'], 0) : 0; ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    
    
    <?php if(isset($data) && $title == $this->lang->line('reports_payments_summary_report')): ?>
    <h5 class="section-header">Payment Mode Share (Liquidity Mix)</h5>
    <div class="row">
        <?php foreach($data as $row): ?>
            <?php 
                // Only look at rows categorized as payments
                if($row['trans_group'] == '--' || strtolower($row['trans_group']) != 'payments') continue; 
                
                $p_amt = (float)filter_var($row['trans_payments'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
                // Use the global calc_paid from our CFO Brain for the denominator
                $share = ($calc_paid > 0) ? ($p_amt / $calc_paid) * 100 : 0;
            ?>
            <div class="col-6 col-md-3">
                <div class="summary-card" style="border-bottom: 3px solid var(--accent-muted); min-height: 110px; transition: transform 0.2s;">
                    <div class="card-label" style="text-transform: uppercase; letter-spacing: 0.5px; font-size: 10px;">
                        <?php echo $row['trans_type']; ?>
                    </div>
                    <span class="card-value" style="font-size: 1.2rem; display: block; margin: 5px 0;">
                        <?php echo $row['trans_payments']; ?>
                    </span>
                    
                    <div class="efficiency-wrapper">
                        <div class="progress-container" style="height:4px; background: #e2e8f0; border-radius: 2px;">
                            <div class="progress-bar" style="width:<?php echo min($share, 100); ?>%; background: var(--accent-blue); border-radius: 2px;"></div>
                        </div>
                        <div class="efficiency-stats" style="margin-top: 5px;">
                            <span style="font-size: 10px; color: #64748b;">Contribution</span>
                            <span style="font-weight: bold; color: var(--text-dark);"><?php echo round($share, 1); ?>%</span>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>
    
</div>
<!-------------------------------------------------SUMMARY CARD--------------------------------------------->

<script type="text/javascript">
	$(document).ready(function()
	{
		<?php $this->load->view('partial/bootstrap_tables_locale'); ?>

		$('#table')
			.addClass("table-striped")
			.addClass("table-bordered")
			.bootstrapTable({
				columns: <?php echo transform_headers($headers, TRUE, FALSE); ?>,
				stickyHeader: true,
				stickyHeaderOffsetLeft: $('#table').offset().left + 'px',
				stickyHeaderOffsetRight: $('#table').offset().right + 'px',
				pageSize: <?php echo $this->config->item('lines_per_page'); ?>,
				sortable: true,
				showExport: true,
				exportDataType: 'all',
				exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel', 'pdf'],
				pagination: true,
				showColumns: true,
				data: <?php echo json_encode($data); ?>,
				iconSize: 'sm',
				paginationVAlign: 'bottom',
				escape: false,
				search: true
		});


	});
</script>

<?php $this->load->view("partial/footer"); ?>
