<?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>
<? /* ---Old logic--->
<div id="report_summary">
	<?php
	foreach($summary_data as $name => $value)
	{ 
		if($name == "total_quantity")
		{
	?>
			<div class="summary_row"><?php echo $this->lang->line('reports_quantity_sold') . ': ' .$value; ?></div>
	<?php
		}
		else
		{
	?>
			<div class="summary_row"><?php echo $this->lang->line('reports_'.$name) . ': ' . to_currency($value); ?></div>
	<?php
		}
	}
	?>
</div>
*/ ?>


<?php
// --- UNIVERSAL DATA MAPPING ---
$total_sales    = (float)($summary_data['total'] ?? 0);
$net_sales      = (float)($summary_data['subtotal'] ?? 0); 
$total_tax      = (float)($summary_data['tax'] ?? 0);
$total_profit   = (float)($summary_data['profit'] ?? 0);
$total_cost     = (float)($summary_data['cost'] ?? 0);
$total_discount = (float)($summary_data['discount_value'] ?? $summary_data['discount'] ?? 0);
$recorded_expenses  = (float)($summary_data['expenses_overall'] ?? 0);
$fixed_setting      = (float)$this->config->item('fixed_monthly_expenses') ?: 0;
$active_baseline    = ($recorded_expenses > 0) ? $recorded_expenses : $fixed_setting;

// Metrics
$total_transactions = (int)($summary_data['total_transactions'] ?? 0);
$total_quantity     = (float)($summary_data['total_quantity'] ?? 0);


// Calculations
$margin_pct = ($total_sales > 0) ? ($total_profit / $total_sales) * 100 : 0;
$global_avg_sale = ($total_transactions > 0) ? ($total_sales / $total_transactions) : 0;
$global_avg_profit = ($total_transactions > 0) ? ($total_profit / $total_transactions) : 0;



// MONTHLY NORTH STAR

$recorded_expenses  = (float)($summary_data['expenses_overall'] ?? 0);
$fixed_setting      = (float)$this->config->item('fixed_monthly_expenses') ?: 0;

// --- 2. TIME LOGIC ---
$s_date = $this->input->get('start_date') ?: date('Y-m-01'); // Default to start of month
$e_date = $this->input->get('end_date') ?: date('Y-m-d');
$d1 = new DateTime($s_date);
$d2 = new DateTime($e_date);
$days_selected = $d1->diff($d2)->days + 1;

// Month remaining logic
$days_in_month = (int)date('t');
$day_of_month  = (int)date('j');
$days_left     = ($days_in_month - $day_of_month) + 1;

// --- 3. THE MONTHLY NORTH STAR (The Mountain) ---
// Use the higher of fixed bills or actual logged expenses for the month
$monthly_expense_mountain = ($recorded_expenses > $fixed_setting) ? $recorded_expenses : $fixed_setting;

// Calculate Margin Decimal (Avoid division by zero)
$margin_dec = ($total_sales > 0) ? ($total_profit / $total_sales) : 0.0001; 

// Revenue needed to cover the mountain
$total_revenue_needed_for_month = $monthly_expense_mountain / $margin_dec;

// --- 4. PERFORMANCE & GAP INSIGHTS ---
// The Gap: How much is left for the month?
$monthly_survival_gap = $total_revenue_needed_for_month - $total_sales;
$be_progress_pct      = ($total_revenue_needed_for_month > 0) ? ($total_sales / $total_revenue_needed_for_month) * 100 : 0;

// Required Daily Pace: To clear the remaining gap in the days left
$required_daily_pace = ($days_left > 0 && $monthly_survival_gap > 0) ? ($monthly_survival_gap / $days_left) : 0;
$actual_daily_avg    = $total_sales / $days_selected;

// Growth Logic (Custom Setting)
$daily_growth_goal = (float)$this->config->item('daily_sales_goal') ?: 0;
$growth_progress   = ($daily_growth_goal > 0) ? ($actual_daily_avg / $daily_growth_goal) * 100 : 0;

// Colors
$be_color = ($be_progress_pct >= 100) ? '#16a34a' : '#ea580c';
?>



<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">
    <div class="dashboard-actions">
        <button onclick="window.print()" class="btn-print">
            <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M6 9V2h12v7M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2m-12 0v4h12v-4m-12 0h12"></path></svg>
            Print PDF Report
        </button>
    </div>
    
    
    
    <?php 
        /** * DATA PRE-CALCULATION BLOCK */
        $calc_paid = 0; 
        $calc_due = 0;
        
        // 1. Calculate Collections from the table data (Payments Report specific)
        if(isset($data)) {
            foreach($data as $row) {
                if(!isset($row['trans_group']) || $row['trans_group'] == '--') continue;
                $p_val = (float)filter_var($row['trans_payments'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
                $d_val = (float)filter_var($row['trans_due'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
                if(strtolower($row['trans_group']) == 'payments') { $calc_paid += $p_val; }
                $calc_due += $d_val;
            }
        }
    
        // 2. Pull Global Stats from our merged $summary_data array
        $total_sales    = (float)($summary_data['total'] ?? 0);
        $total_profit   = (float)($summary_data['profit'] ?? 0);
        $total_cost     = (float)($summary_data['cost'] ?? 0);
        $total_tax      = (float)($summary_data['tax'] ?? 0);
        $total_discount = (float)($summary_data['discount'] ?? 0);
        $total_expenses = (float)($summary_data['total_expenses'] ?? $summary_data['total_amount'] ?? 0);
        $fixed_costs = ($total_expenses > 0) ? $total_expenses : (float)$this->config->item('fixed_monthly_expenses');
    
        // 3. THE MAGIC FIX: These come from the Sales Model merge in your Controller
       
        $total_transactions = (int)($summary_data['total_transactions'] ?? 0);
        $total_quantity     = (float)($summary_data['total_quantity'] ?? 0);
    
        // 4. Insights logic - Using the database counts for accuracy
        $margin_pct = ($total_sales > 0) ? ($total_profit / $total_sales) * 100 : 0;
        $collection_realization = (($calc_paid + $calc_due) > 0) ? ($calc_paid / ($calc_paid + $calc_due)) * 100 : 0;
        
        // Average Sale and Profit based on TRUE transaction counts
        $global_avg_sale = ($total_transactions > 0) ? ($total_sales / $total_transactions) : 0;
        $global_avg_profit = ($total_transactions > 0) ? ($total_profit / $total_transactions) : 0;
        
        
        
    ?>
    
    <?php if(isset($summary_data)): ?>
    <!-- Section Header (Only one needed) -->
    <h5 class="section-header">Financial Pulse</h5>
    
        <div class="row">
        <div class="col-md-4">
            <div class="summary-card" style="border-top: 4px solid var(--accent-blue);">
                <div class="kpi-label-top">NET SALES (Total - Tax)</div>
                <span class="kpi-main-value text-primary-modern">
                    <?php echo to_currency($summary_data['subtotal'] ?? 0); ?>
                </span>
                
                <div class="kpi-divider">
                    <div class="kpi-sub-label">Gross Sales (Total)</div>
                    <div class="kpi-sub-value"><?php echo to_currency($total_sales); ?></div>
                </div>
    
                <div class="metric-grid">
                    <div class="metric-item">
                        <span class="metric-label">Discounts</span>
                        <span class="metric-value text-danger-modern">-<?php echo to_currency($summary_data['discount_value'] ?? 0); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Disc. Count</span>
                        <span class="metric-value"><?php echo $summary_data['discount_count'] ?? 0; ?></span>
                    </div>
                </div>
                
                <div class="metric-grid">
                    <div class="metric-item">
                        <span class="metric-label">Total Visits</span>
                        <span class="metric-value"><?php echo number_format($total_transactions); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Avg. Revenue</span>
                        <span class="metric-value"><?php echo to_currency($global_avg_sale); ?></span>
                    </div>
                </div>
                
            </div>
        </div>
    
        <div class="col-md-4">
            <div class="summary-card" style="border-top: 4px solid var(--accent-green);">
                <div class="kpi-label-top">NET PROFIT & MARGIN</div>
                <span class="kpi-main-value text-success-modern">
                    <?php echo round($margin_pct, 1); ?>%
                </span>
                
                <div class="kpi-divider">
                    <div class="kpi-sub-label">Gross Profit Value</div>
                    <div class="kpi-sub-value text-success-modern"><?php echo to_currency($total_profit); ?></div>
                </div>
    
                <div class="metric-grid">
                    <div class="metric-item">
                        <span class="metric-label">COGS (Wholesale)</span>
                        <span class="metric-value"><?php echo to_currency($total_cost); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Markup</span>
                        <span class="metric-value">
                            <?php echo ($total_cost > 0) ? round(($total_profit/$total_cost)*100, 1) : 0; ?>%
                        </span>
                    </div>
                </div>
            </div>
        </div>
    
        <div class="col-md-4">
            <div class="summary-card" style="border-top: 4px solid var(--accent-purple);">
                <div class="kpi-label-top">TAX COLLECTED</div>
                <span class="kpi-main-value" style="color: var(--accent-purple);">
                    <?php echo to_currency($total_tax); ?>
                </span>
                
                <div class="kpi-divider">
                    <div class="kpi-sub-label">Tax Efficiency Ratio</div>
                    <div class="kpi-sub-value">
                        <?php echo ($total_sales > 0) ? round(($total_tax/$total_sales)*100, 2) : 0; ?>%
                    </div>
                </div>
                
            </div>
        </div>
</div>
    
    <div class="row" style="margin: 20px 0;">
        <div class="col-md-6">
            <div class="summary-card" style="border-top: 4px solid <?php echo $be_color; ?>; padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);">
                <div class="kpi-label-top" style="font-weight: bold; color: #64748b; margin-bottom: 15px;">
                    MONTHLY SURVIVAL STATUS
                    <span class="pull-right" style="font-size: 10px; padding: 4px 8px; border-radius: 12px; background: <?php echo $be_color; ?>20; color: <?php echo $be_color; ?>;">
                        <?php echo ($be_progress_pct >= 100) ? 'BREAK-EVEN REACHED' : 'CLIMBING MOUNTAIN'; ?>
                    </span>
                </div>

                <div class="row">
                    <div class="col-xs-7">
                        <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase;">Remaining Monthly Gap</div>
                        <div style="font-size: 32px; font-weight: 900; color: <?php echo ($monthly_survival_gap <= 0) ? '#16a34a' : '#ef4444'; ?>;">
                            <?php echo ($monthly_survival_gap <= 0) ? 'CLEARED' : to_currency($monthly_survival_gap); ?>
                        </div>
                        <div style="background: #f1f5f9; height: 8px; border-radius: 4px; margin: 10px 0;">
                            <div style="width: <?php echo min($be_progress_pct, 100); ?>%; background: <?php echo $be_color; ?>; height: 100%; border-radius: 4px;"></div>
                        </div>
                    </div>
                    <div class="col-xs-5 text-right" style="border-left: 1px solid #f1f5f9;">
                        <div style="font-size: 11px; color: #94a3b8;">RECOVERY PACE REQ.</div>
                        <div style="font-size: 18px; font-weight: 800; color: #ea580c;">
                            <?php echo to_currency($required_daily_pace); ?> <span style="font-size:10px; color:#94a3b8;">/day</span>
                        </div>
                        <div style="font-size: 10px; color: #64748b;"><?php echo $days_left; ?> days remaining</div>
                    </div>
                </div>

                <hr style="margin: 15px 0; border: 0; border-top: 1px solid #f1f5f9;">

                <div class="row">
                    <div class="col-xs-4">
                        <div style="font-size: 10px; color: #94a3b8;">TOTAL SALES</div>
                        <div style="font-size: 13px; font-weight: 700;"><?php echo to_currency($total_sales); ?></div>
                    </div>
                    <div class="col-xs-4">
                        <div style="font-size: 10px; color: #94a3b8;">AVG DAILY</div>
                        <div style="font-size: 13px; font-weight: 700;"><?php echo to_currency($actual_daily_avg); ?></div>
                    </div>
                    <div class="col-xs-4 text-right">
                        <div style="font-size: 10px; color: #94a3b8;">GROWTH GOAL</div>
                        <div style="font-size: 13px; font-weight: 700; color: #3b82f6;"><?php echo number_format($growth_progress, 0); ?>%</div>
                    </div>
                </div>

                <?php if($monthly_survival_gap > 0): ?>
                    <div style="margin-top: 15px; background: #fffbeb; border: 1px solid #fef3c7; color: #92400e; padding: 10px; border-radius: 6px; font-size: 11px; font-weight: 600;">
                        💡 To break even by month-end, you must increase daily sales to <?php echo to_currency($required_daily_pace); ?>.
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-md-6">
            <div class="summary-card" style="padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);">
                <div style="font-weight: bold; color: #64748b; margin-bottom: 15px;">SALES VOLUME</div>
                <div class="row">
                    <div class="col-xs-6 text-center">
                        <div style="font-size: 11px; color: #94a3b8;">TRANSACTIONS</div>
                        <div style="font-size: 32px; font-weight: 900; color: #1e293b;"><?php echo number_format($total_transactions); ?></div>
                    </div>
                    <div class="col-xs-6 text-center" style="border-left: 1px solid #f1f5f9;">
                        <div style="font-size: 11px; color: #94a3b8;">ITEMS SOLD</div>
                        <div style="font-size: 32px; font-weight: 900; color: #1e293b;"><?php echo number_format($total_quantity); ?></div>
                    </div>
                </div>
                <div class="text-center" style="margin-top: 15px; font-size: 12px; color: #64748b;">
                    Average Order Value: <strong><?php echo to_currency($total_transactions > 0 ? $total_sales/$total_transactions : 0); ?></strong>
                </div>
            </div>
        </div>
    </div>
</div>
    
    <h5 class="section-header">Sales Performance</h5>
    
    
    <div class="row">
        <!-- 1. GROSS SALES CARD -->
        <div class="col-6 col-md-3">
            <div class="summary-card" style="border-top: 3px solid var(--accent-blue);">
                <div class="card-label">Gross Sales</div>
                <span class="card-value"><?php echo to_currency($total_sales); ?></span>
                <div class="card-label">Net Sales</div>
    <span class="card-value"><?php echo to_currency($summary_data['subtotal'] ?? 0); ?></span>
                
                <div class="metric-grid">
                    <div class="metric-item">
                        <span class="metric-label">Tax Incl.</span>
                        <span class="metric-value"><?php echo to_currency($total_tax); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Avg Sale.</span>
                        <span class="metric-value"><?php echo to_currency($global_avg_sale); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Visits</span>
                        <span class="metric-value"><?php echo number_format($total_transactions); ?></span>
                    </div>
                    <div class="metric-item">
                        <span class="metric-label">Qty Sold</span>
                        <span class="metric-value"><?php echo number_format($total_quantity); ?></span>
                    </div>
                </div>
                
                <div class="card-subtext" style="margin-top:10px;">
                    <strong><?php echo number_format($total_transactions); ?></strong> Trans. | 
                    <strong><?php echo number_format($total_quantity); ?></strong> Items
                </div>
            </div>
        </div>

        <!-- 2. GROSS PROFIT CARD -->
        <div class="col-6 col-md-3">
            <div class="summary-card" style="border-top: 3px solid var(--accent-green);">
                <div class="card-label">Gross Profit</div>
                <span class="card-value text-success-modern"><?php echo to_currency($total_profit); ?></span>
                <div class="efficiency-wrapper">
                    <div class="efficiency-stats">
                        <span>Margin</span>
                        <span><?php echo round($margin_pct, 1); ?>%</span>
                    </div>
                    <div class="progress-container">
                        <div class="progress-bar" style="width:<?php echo $margin_pct; ?>%; background: var(--accent-green);"></div>
                    </div>
                    <div class="metric-grid">
                        <div class="metric-item">
                            <span class="metric-label">Avg Profit.</span>
                            <span class="metric-value"><?php echo to_currency($global_avg_profit); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 3. WHOLESALE COST CARD -->
        <div class="col-6 col-md-3">
            <div class="summary-card" style="border-top: 3px solid var(--accent-red);">
                <div class="card-label">Wholesale Cost</div>
                <span class="card-value text-danger-modern"><?php echo to_currency($total_cost); ?></span>
                <div class="metric-grid">
                    <div class="metric-item">
                        <span class="metric-label">Markup</span>
                        <span class="metric-value">
                            <?php echo ($total_cost > 0) ? round(($total_profit/$total_cost)*100, 1) : 0; ?>%
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 4. TAX COLLECTED CARD -->
        <div class="col-6 col-md-3">
            <div class="summary-card" style="border-top: 3px solid var(--accent-purple);">
                <div class="card-label">Tax Collected</div>
                <span class="card-value"><?php echo to_currency($total_tax); ?></span>
                <div class="metric-grid">
                    <div class="metric-item">
                        <span class="metric-label">Tax Ratio</span>
                        <span class="metric-value">
                            <?php echo ($total_sales > 0) ? round(($total_tax/$total_sales)*100, 2) : 0; ?>%
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div> <!-- End Row -->
<?php endif; ?>


    <?php if(isset($data) && $title == $this->lang->line('reports_payments_summary_report')): ?>
    <h5 class="section-header">Transaction Analysis</h5>
    <div class="row">
        <?php foreach($data as $row): ?>
            <?php 
                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;
                $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; ?>">
                    <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">
                        <div class="metric-item"><span class="metric-label">Actual Paid</span><span class="metric-value text-success-modern"><?php echo $row['trans_payments']; ?></span></div>
                        <div class="metric-item"><span class="metric-label">Avg/Sale</span><span class="metric-value"><?php echo ($row['trans_sales'] > 0) ? number_format($r_amt/$row['trans_sales'], 0) : 0; ?></span></div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <h5 class="section-header">Collections & Cash Health</h5>
    <div class="row">
        <div class="col-md-4">
            <div class="summary-card" style="border-left: 4px solid var(--accent-green);">
                <div class="card-label">Total Collected</div>
                <span class="card-value text-success-modern"><?php echo to_currency($calc_paid); ?></span>
                <div class="efficiency-wrapper">
                    <div class="efficiency-stats"><span>Realization Rate</span><span><?php echo round($collection_realization, 1); ?>%</span></div>
                    <div class="progress-container"><div class="progress-bar" style="width:<?php echo $collection_realization; ?>%; background: var(--accent-green);"></div></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="summary-card" style="border-left: 4px solid var(--accent-red);">
                <div class="card-label">Total Outstanding</div>
                <span class="card-value text-danger-modern"><?php echo to_currency($calc_due); ?></span>
                <div class="metric-grid"><div class="metric-item"><span class="metric-label">Debt-to-Cash</span><span class="metric-value"><?php echo ($calc_paid > 0) ? round(($calc_due/$calc_paid)*100, 1) : 0; ?>%</span></div></div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="summary-card" style="border-left: 4px solid var(--accent-purple);">
                <div class="card-label">Discounts Given</div>
                <span class="card-value" style="color: var(--accent-purple);"><?php echo to_currency($total_discount); ?></span>
                <div class="metric-grid"><div class="metric-item"><span class="metric-label">Revenue Impact</span><span class="metric-value"><?php echo ($total_sales > 0) ? round(($total_discount/$total_sales)*100, 1) : 0; ?>%</span></div></div>
            </div>
            <div class="summary-card" style="border-left: 4px solid var(--accent-purple);">    
                <div class="card-label">Discounts</div>
                <span class="card-value"><?php echo to_currency($summary_data['discount_value']); ?></span>
                <div class="card-subtext">Used in <strong><?php echo $summary_data['discount_count']; ?></strong> Sales</div>
            </div>
            
            <div class="summary-card" style="border-left: 4px solid var(--accent-purple);">    
                <div class="card-label">Active Inventory</div>
                <span class="card-value"><?php echo number_format($summary_data['sku_count']); ?></span>
                <div class="card-subtext">Items Sold</div>
            </div>
        </div>
    </div>

    <h5 class="section-header">Payment Mode Share</h5>
        <div class="row">
            <?php foreach($data as $row): ?>
                <?php 
                    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);
                    $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: 100px;">
                        <div class="card-label"><?php echo $row['trans_type']; ?></div>
                        <span class="card-value" style="font-size: 1.1rem;"><?php echo $row['trans_payments']; ?></span>
                        <div class="efficiency-wrapper">
                            <div class="progress-container" style="height:3px;"><div class="progress-bar" style="width:<?php echo $share; ?>%; background: var(--text-muted);"></div></div>
                            <div class="efficiency-stats"><span>Share</span><span><?php echo round($share, 1); ?>%</span></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
</div>

<?php 
    $inv_retail = $summary_data['inventory_retail_value'] ?? 0;
    $inv_cost = $summary_data['inventory_cost_value'] ?? 0;
    $inv_profit_potential = $inv_retail - $inv_cost;
    $inv_margin = ($inv_retail > 0) ? ($inv_profit_potential / $inv_retail) * 100 : 0;
?>

<div class="row">
    <div class="col-md-3">
        <div class="summary-card" style="border-top: 3px solid #e67e22;">
            <div class="card-label">Retail Value</div>
            <span class="card-value"><?php echo to_currency($inv_retail); ?></span>
            <div class="card-subtext">Potential Revenue</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="summary-card" style="border-top: 3px solid #d35400;">
            <div class="card-label">Inventory Cost</div>
            <span class="card-value"><?php echo to_currency($inv_cost); ?></span>
            <div class="card-subtext">Capital Tied Up</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="summary-card" style="border-top: 3px solid #27ae60;">
            <div class="card-label">Expected Margin</div>
            <span class="card-value"><?php echo round($inv_margin, 1); ?>%</span>
            <div class="card-subtext">Profit: <?php echo to_currency($inv_profit_potential); ?></div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="summary-card" style="border-top: 3px solid #2980b9;">
            <div class="card-label">Total Items</div>
            <span class="card-value"><?php echo number_format($summary_data['inventory_count'] ?? 0); ?></span>
            <div class="card-subtext"><?php echo $summary_data['inventory_distinct_skus'] ?? 0; ?> Unique SKUs</div>
        </div>
    </div>
</div>





<?php if(isset($summary_data)): 
    // Initialize our counters
    $total_transactions = 0;
    $total_quantity = 0;

    // Loop through the table rows to sum up the values
    if(isset($data)) {
        foreach($data as $row) {
            // We use filter_var to remove any formatting/commas before adding
            $total_transactions += (float)filter_var($row['sales'] ?? 0, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
            $total_quantity += (float)filter_var($row['quantity'] ?? 0, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        }
    }
?>
    <h5 class="text-uppercase section-header"><?php echo $this->lang->line('reports_sales'); ?> OVERVIEW</h5>
    <div class="row">
        <div class="col-md-3">
            <div class="summary-card border-sales">
                <div class="card-label"><?php echo $this->lang->line('reports_total'); ?></div>
                <span class="card-value"><?php echo to_currency($summary_data['total'] ?? 0); ?></span>
                <div class="card-subtext"><strong><?php echo $total_transactions; ?></strong> Transactions</div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="summary-card border-profit">
                <div class="card-label"><?php echo $this->lang->line('reports_profit'); ?></div>
                <span class="card-value" style="color: #27ae60;"><?php echo to_currency($summary_data['profit'] ?? 0); ?></span>
                <div class="card-subtext"><strong><?php echo $total_quantity; ?></strong> Items Sold</div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="summary-card border-due">
                <div class="card-label"><?php echo $this->lang->line('reports_cost'); ?></div>
                <span class="card-value" style="color: #c0392b;"><?php echo to_currency($summary_data['cost'] ?? 0); ?></span>
            </div>
        </div>

        <div class="col-md-3">
            <div class="summary-card" style="border-top: 3px solid #9b59b6;">
                <div class="card-label"><?php echo $this->lang->line('reports_tax'); ?></div>
                <span class="card-value"><?php echo to_currency($summary_data['tax'] ?? 0); ?></span>
            </div>
        </div>
    </div>
<?php endif; ?>
 
 <hr />
    <div class="row">
        <div class="col-md-6">
            <div class="panel panel-default">
                <div class="panel-heading"><strong>Top 5 Items by Profit</strong></div>
                <table class="table table-condensed table-striped">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th class="text-right">Qty</th>
                            <th class="text-right">Profit</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($summary_data['top_five_items'] as $item): ?>
                            <tr>
                                <td><?php echo $item['name']; ?></td>
                                <td class="text-right"><?php echo number_format($item['quantity_purchased']); ?></td>
                                <td class="text-right text-success"><?php echo to_currency($item['profit']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    
        <div class="col-md-6">
            <div class="panel panel-default">
                <div class="panel-heading"><strong>Top 5 Categories by Volume</strong></div>
                <table class="table table-condensed table-striped">
                    <thead>
                        <tr>
                            <th>Category</th>
                            <th class="text-right">Qty Sold</th>
                            <th class="text-right">Revenue</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($summary_data['top_five_categories'] as $cat): ?>
                            <tr>
                                <td><?php echo $cat['category']; ?></td>
                                <td class="text-right"><?php echo number_format($cat['quantity_purchased']); ?></td>
                                <td class="text-right"><?php echo to_currency($cat['total']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
 
 
 
</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"); ?>
