<?php
$currency = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$expense_summary = $this->db
    ->select('COUNT(*) AS entry_count, COALESCE(SUM(amount), 0) AS total_amount, COALESCE(SUM(credit), 0) AS total_credit, COALESCE(SUM(debit), 0) AS total_debit', false)
    ->where('type', 'Expense')
    ->get('tbl_transactions')
    ->row();
$total_amount = !empty($expense_summary->total_amount) ? (float) $expense_summary->total_amount : 0;
$total_credit = !empty($expense_summary->total_credit) ? (float) $expense_summary->total_credit : 0;
$total_debit = !empty($expense_summary->total_debit) ? (float) $expense_summary->total_debit : 0;
$expense_entries = !empty($expense_summary->entry_count) ? (int) $expense_summary->entry_count : 0;
$net_balance = $total_credit - $total_debit;

$summary_cards = array(
    array(
        'label' => lang('total_amount'),
        'value' => display_money($total_amount, $currency->symbol),
        'meta' => 'Total posted expense transaction amount',
        'icon' => 'credit-card',
        'tone' => 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
    array(
        'label' => lang('credit'),
        'value' => display_money($total_credit, $currency->symbol),
        'meta' => 'Credit adjustments attached to expense records',
        'icon' => 'arrow-down-left',
        'tone' => 'text-sky-600 dark:text-sky-300 bg-sky-500/10',
    ),
    array(
        'label' => lang('debit'),
        'value' => display_money($total_debit, $currency->symbol),
        'meta' => 'Total debited value across expense entries',
        'icon' => 'arrow-up-right',
        'tone' => 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
    array(
        'label' => lang('balance'),
        'value' => display_money($net_balance, $currency->symbol),
        'meta' => $expense_entries . ' posted expense entries',
        'icon' => 'scale',
        'tone' => $net_balance >= 0
            ? 'text-violet-600 dark:text-violet-300 bg-violet-500/10'
            : 'text-rose-600 dark:text-rose-300 bg-rose-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 class="rounded-2xl border border-border bg-background/60 sales-report-module p-4">
        <table class="table DataTables min-w-full text-sm" id="DataTables" cellspacing="0" width="100%">
            <thead class="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
            <tr>
                <th><?= lang('date') ?></th>
                <th><?= lang('account_name') ?></th>
                <th><?= lang('notes') ?></th>
                <th><?= lang('amount') ?></th>
                <th><?= lang('credit') ?></th>
                <th><?= lang('debit') ?></th>
                <th><?= lang('balance') ?></th>
                <th class="col-options no-sort text-right"><?= lang('action') ?></th>
            </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<div id="expense-report-preloader" class="fixed inset-0 z-[70] hidden items-center justify-center bg-slate-950/30 backdrop-blur-sm">
    <div class="rounded-2xl border border-border bg-card px-6 py-5 shadow-2xl">
        <div class="flex items-center gap-3">
            <div class="h-5 w-5 animate-spin rounded-full border-2 border-rose-500/30 border-t-rose-500"></div>
            <div>
                <p class="text-sm font-semibold text-foreground">Loading expense report...</p>
                <p class="text-xs text-muted-foreground">Refreshing the transaction list.</p>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        list = base_url + "admin/report/expenseList";
        var preloader = document.getElementById('expense-report-preloader');

        function showExpensePreloader() {
            if (!preloader) return;
            preloader.classList.remove('hidden');
            preloader.classList.add('flex');
        }

        function hideExpensePreloader() {
            if (!preloader) return;
            preloader.classList.add('hidden');
            preloader.classList.remove('flex');
        }

        $('#DataTables').on('preXhr.dt', function () {
            showExpensePreloader();
        }).on('draw.dt xhr.dt', function () {
            hideExpensePreloader();
        });

        function reloadExpense(filter, searchType) {
            var url = list;
            if (filter) {
                url += "/" + filter;
                if (searchType) {
                    url += "/" + searchType;
                }
            }
            showExpensePreloader();
            table_url(url);
        }

        window.expenseAccountFilter = function (id) {
            reloadExpense(id, 'by_account');
        };

        window.expenseCategoryFilter = function (id) {
            reloadExpense(id, 'by_category');
        };

        $('#clear_expense_filters').on('click', function () {
            document.querySelectorAll('[data-lookup-onchange="expenseAccountFilter"], [data-lookup-onchange="expenseCategoryFilter"]').forEach(function (wrap) {
                var hidden = wrap.querySelector('[data-lookup-hidden]');
                var input = wrap.querySelector('[data-lookup-input]');
                var results = wrap.querySelector('[data-lookup-results]');
                var status = wrap.querySelector('[data-lookup-status]');
                if (hidden) hidden.value = '';
                if (input) input.value = '';
                if (results) results.classList.add('hidden');
                if (status) {
                    status.textContent = '';
                    status.classList.add('hidden');
                }
            });
            reloadExpense();
        });
    });
</script>
