<?php
$currency = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$report_summary = isset($report_summary) ? $report_summary : array('all_time' => 0, 'this_month' => 0, 'this_week' => 0, 'last_30_days' => 0);
$all_deposit_info = isset($all_deposit_info) ? $all_deposit_info : array();
$fee_graph = isset($fee_graph) ? $fee_graph : array(
    'range_label' => '',
    'trend_total' => 0,
    'trend_peak' => 0,
    'trend_average' => 0,
    'trend_series' => array(),
    'category_series' => array(),
);

$total_amount = 0;
$total_debit = 0;
$total_balance = 0;

$summary_cards = array(
    array(
        'label' => lang('total_expense'),
        'value' => display_money($report_summary['all_time'], $currency->symbol),
        'meta' => 'Total debits posted to finance ledgers',
        'icon' => 'receipt',
        'tone' => 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
    array(
        'label' => lang('total_expense_this_month'),
        'value' => display_money($report_summary['this_month'], $currency->symbol),
        'meta' => 'Current month operating and discretionary spending',
        'icon' => 'calendar-days',
        'tone' => 'text-violet-600 dark:text-violet-300 bg-violet-500/10',
    ),
    array(
        'label' => lang('total_expense_this_week'),
        'value' => display_money($report_summary['this_week'], $currency->symbol),
        'meta' => 'Weekly burn rate for leadership review',
        'icon' => 'calendar-range',
        'tone' => 'text-amber-600 dark:text-amber-300 bg-amber-500/10',
    ),
    array(
        'label' => lang('total_expense_last_30'),
        'value' => display_money($report_summary['last_30_days'], $currency->symbol),
        'meta' => 'Rolling 30-day expense exposure',
        'icon' => 'history',
        'tone' => 'text-sky-600 dark:text-sky-300 bg-sky-500/10',
    ),
);
?>

<div class="space-y-6 sales-report-page">
    <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4 sales-report-cardgrid">
        <?php foreach ($summary_cards as $card): ?>
            <div class="rounded-xl border border-border bg-card p-4 shadow-sm sales-report-card">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= $card['label'] ?></p>
                        <p class="mt-2 text-xl font-bold text-foreground"><?= $card['value'] ?></p>
                        <p class="mt-1 text-xs text-muted-foreground"><?= $card['meta'] ?></p>
                    </div>
                    <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl <?= $card['tone'] ?>">
                        <i data-lucide="<?= $card['icon'] ?>" class="h-5 w-5"></i>
                    </span>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div id="printReport" class="rounded-2xl border border-border bg-card shadow-sm sales-report-content p-4">
        <div>
        <div class="show_print hidden">
            <div class="report-print-brand">
                <div class="report-print-brand-row">
                    <img class="report-print-brand-logo" src="<?= base_url() . config_item('company_logo') ?>" alt="<?= html_escape(config_item('company_name')) ?>" />
                    <p class="report-print-brand-name"><?= config_item('company_name') ?></p>
                </div>
            </div>
        </div>

        <section class="mb-6 grid grid-cols-1 gap-6 xl:grid-cols-12">
            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-8">
                <div class="flex flex-col gap-3 border-b border-border px-6 py-4 md:flex-row md:items-start md:justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-foreground">Fee Expense Graph</h3>
                        <p class="text-sm text-muted-foreground">Daily debited fee movement for <?= html_escape($fee_graph['range_label']) ?>.</p>
                    </div>
                    <span class="inline-flex w-fit items-center gap-2 rounded-full border border-rose-500/20 bg-rose-500/10 px-3 py-1 text-xs font-semibold text-rose-600 dark:text-rose-300">
                        <i data-lucide="trending-down" class="h-3.5 w-3.5"></i>
                        <?= display_money($fee_graph['trend_total'], $currency->symbol) ?>
                    </span>
                </div>
                <div class="p-6">
                    <div class="sales-report-chart" data-chart="area" data-height="320" data-height-sm="240" data-series='<?= json_encode($fee_graph['trend_series'], JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>

            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-4">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground">Fee Category Mix</h3>
                    <p class="text-sm text-muted-foreground">Top expense categories by debited value.</p>
                </div>
                <div class="space-y-4 p-6">
                    <div class="grid grid-cols-2 gap-3">
                        <div class="rounded-xl border border-border bg-card p-4">
                            <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Peak Day</p>
                            <p class="mt-2 text-lg font-bold text-foreground"><?= display_money($fee_graph['trend_peak'], $currency->symbol) ?></p>
                        </div>
                        <div class="rounded-xl border border-border bg-card p-4">
                            <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Daily Avg</p>
                            <p class="mt-2 text-lg font-bold text-foreground"><?= display_money($fee_graph['trend_average'], $currency->symbol) ?></p>
                        </div>
                    </div>
                    <div class="sales-report-chart" data-chart="bar" data-height="270" data-height-sm="220" data-series='<?= json_encode($fee_graph['category_series'], JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>
        </section>

        <section>
            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= lang('last_deposit_expense') ?></h3>
                    <p class="text-sm text-muted-foreground">Latest twenty outgoing transactions grouped by account, category, and payment source.</p>
                </div>
                <div class="overflow-x-auto">
                    <table class="min-w-full text-left text-sm">
                        <thead class="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                        <tr>
                            <th class="px-4 py-3"><?= lang('date') ?></th>
                            <th class="px-4 py-3"><?= lang('account') ?></th>
                            <th class="px-4 py-3"><?= lang('deposit_category') ?></th>
                            <th class="px-4 py-3"><?= lang('paid_by') ?></th>
                            <th class="px-4 py-3"><?= lang('description') ?></th>
                            <th class="px-4 py-3 text-right"><?= lang('amount') ?></th>
                            <th class="px-4 py-3 text-right"><?= lang('debit') ?></th>
                            <th class="px-4 py-3 text-right"><?= lang('balance') ?></th>
                        </tr>
                        </thead>
                        <tbody class="divide-y divide-border">
                        <?php foreach ($all_deposit_info as $v_deposit):
                            $total_amount += $v_deposit->amount;
                            $total_debit += $v_deposit->debit;
                            $total_balance += $v_deposit->total_balance;
                            ?>
                            <tr class="hover:bg-muted/30">
                                <td class="px-4 py-3 text-foreground"><?= display_date($v_deposit->date); ?></td>
                                <td class="px-4 py-3 text-foreground"><?= !empty($v_deposit->account_name) ? $v_deposit->account_name : '-' ?></td>
                                <td class="px-4 py-3 text-muted-foreground"><?= !empty($v_deposit->expense_category) ? $v_deposit->expense_category : '-' ?></td>
                                <td class="px-4 py-3 text-muted-foreground"><?= !empty($v_deposit->client_name) ? $v_deposit->client_name : '-' ?></td>
                                <td class="px-4 py-3 text-muted-foreground"><?= $v_deposit->notes ?></td>
                                <td class="px-4 py-3 text-right font-medium text-foreground"><?= display_money($v_deposit->amount, $currency->symbol) ?></td>
                                <td class="px-4 py-3 text-right font-semibold text-rose-600 dark:text-rose-300"><?= display_money($v_deposit->debit, $currency->symbol) ?></td>
                                <td class="px-4 py-3 text-right font-medium text-foreground"><?= display_money($v_deposit->total_balance, $currency->symbol) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                        <tfoot class="border-t border-border bg-muted/10">
                        <tr>
                            <td colspan="5" class="px-4 py-3 text-right font-semibold text-foreground"><?= lang('total') ?></td>
                            <td class="px-4 py-3 text-right font-bold text-foreground"><?= display_money($total_amount, $currency->symbol) ?></td>
                            <td class="px-4 py-3 text-right font-bold text-rose-600 dark:text-rose-300"><?= display_money($total_debit, $currency->symbol) ?></td>
                            <td class="px-4 py-3 text-right font-bold text-foreground"><?= display_money($total_balance, $currency->symbol) ?></td>
                        </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </section>
        </div>
    </div>
</div>

<textarea class="hidden" style="display:none" data-expense-report-print-html><?= html_escape(isset($expense_report_print_html) ? $expense_report_print_html : '') ?></textarea>
<script type="text/javascript">
    if (typeof window.erpInitCharts === 'function') {
        window.erpInitCharts(document);
    }

    function print_sales_report(printReport) {
        var textarea = document.querySelector('[data-expense-report-print-html]');
        var fallback = document.getElementById(printReport);
        var printHtml = (textarea ? textarea.value : '') || (fallback ? fallback.outerHTML : '');
        if (!printHtml) return false;

        var printWindow = window.open('', 'PRINT', 'height=900,width=1200');
        if (!printWindow) {
            window.print();
            return false;
        }

        printWindow.document.open();
        printWindow.document.write(printHtml);
        printWindow.document.close();

        var printed = false;
        var doPrint = function() {
            if (printed || printWindow.closed) return;
            printed = true;
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        };
        printWindow.onload = function() {
            printWindow.setTimeout(doPrint, 350);
        };
        printWindow.setTimeout(doPrint, 900);
        return false;
    }
</script>
