<?php
$currency_symbol = default_currency();
$transaction_summary = $this->db
    ->select('COUNT(*) AS entry_count, COALESCE(SUM(amount), 0) AS total_amount, COALESCE(SUM(debit), 0) AS total_debit, COALESCE(SUM(credit), 0) AS total_credit', false)
    ->get('tbl_transactions')
    ->row();
$total_amount = !empty($transaction_summary->total_amount) ? (float) $transaction_summary->total_amount : 0;
$total_debit = !empty($transaction_summary->total_debit) ? (float) $transaction_summary->total_debit : 0;
$total_credit = !empty($transaction_summary->total_credit) ? (float) $transaction_summary->total_credit : 0;
$balance_total = $total_credit - $total_debit;
$report_entries = !empty($transaction_summary->entry_count) ? (int) $transaction_summary->entry_count : 0;

$chart_categories = array();
$chart_income = array();
$chart_expense = array();
$chart_transfer = array();
foreach ($transactions_report as $days => $v_report) {
    $daily_income = 0;
    $daily_expense = 0;
    $daily_transfer = 0;
    foreach ($v_report as $transaction) {
        if ($transaction->type == 'Expense') {
            $daily_expense += (float) $transaction->amount;
        }
        if ($transaction->type == 'Income') {
            $daily_income += (float) $transaction->amount;
        }
        if ($transaction->type == 'Transfer') {
            $daily_transfer += ((float) $transaction->amount) / 2;
        }
    }
    $chart_categories[] = str_pad((string) $days, 2, '0', STR_PAD_LEFT);
    $chart_income[] = round($daily_income, 2);
    $chart_expense[] = round($daily_expense, 2);
    $chart_transfer[] = round($daily_transfer, 2);
}
$transactions_chart_series = array(
    array('name' => lang('Income'), 'data' => $chart_income, 'categories' => $chart_categories),
    array('name' => lang('expense'), 'data' => $chart_expense),
    array('name' => lang('transfer'), 'data' => $chart_transfer),
);
?>

<div class="space-y-6">
    <div id="printReport" class="space-y-6">
        <div class="show_print hidden">
            <div style="width: 100%; border-bottom: 2px solid black;">
                <table style="width: 100%; vertical-align: middle;">
                    <tr>
                        <td style="width: 50px; border: 0;">
                            <img style="width: 50px;height: 50px;margin-bottom: 5px;" src="<?= base_url() . config_item('company_logo') ?>" alt="" class="img-circle"/>
                        </td>
                        <td style="border: 0;">
                            <p style="margin-left: 10px; font: 14px lighter;"><?= config_item('company_name') ?></p>
                        </td>
                    </tr>
                </table>
            </div>
            <br/>
        </div>

        <section class="rounded-3xl border border-border bg-card shadow-sm">
            <div class="flex flex-col gap-4 border-b border-border px-6 py-5 xl:flex-row xl:items-start xl:justify-between">
                <div class="space-y-2">
                    <div class="inline-flex items-center gap-2 rounded-full border border-sky-500/20 bg-sky-500/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-sky-600 dark:text-sky-300">
                        <i data-lucide="arrow-left-right" class="h-3.5 w-3.5"></i>
                        <?= lang('transactions_report') ?>
                    </div>
                    <div>
                        <h2 class="text-2xl font-semibold text-foreground"><?= lang('transactions_report') ?></h2>
                        <p class="text-sm text-muted-foreground">Monitor posted finance movement with account-focused filtering, ledger totals, and daily income versus expense trends.</p>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 gap-4 p-6 sm:grid-cols-2 xl:grid-cols-4">
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('total_amount') ?></p>
                    <p class="mt-3 text-2xl font-bold text-foreground"><?= display_money($total_amount, $currency_symbol) ?></p>
                    <p class="mt-1 text-xs text-muted-foreground"><?= $report_entries ?> ledger entries in current report scope</p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('credit') ?></p>
                    <p class="mt-3 text-2xl font-bold text-emerald-600 dark:text-emerald-300"><?= display_money($total_credit, $currency_symbol) ?></p>
                    <p class="mt-1 text-xs text-muted-foreground">Total incoming value posted to accounts</p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('debit') ?></p>
                    <p class="mt-3 text-2xl font-bold text-rose-600 dark:text-rose-300"><?= display_money($total_debit, $currency_symbol) ?></p>
                    <p class="mt-1 text-xs text-muted-foreground">Total outgoing value across recorded movements</p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('balance') ?></p>
                    <p class="mt-3 text-2xl font-bold <?= $balance_total >= 0 ? 'text-sky-600 dark:text-sky-300' : 'text-rose-600 dark:text-rose-300' ?>"><?= display_money($balance_total, $currency_symbol) ?></p>
                    <p class="mt-1 text-xs text-muted-foreground">Net movement based on credits minus debits</p>
                </div>
            </div>
        </section>

        <section class="grid grid-cols-1 gap-6 2xl:grid-cols-[minmax(0,1.5fr)_minmax(0,0.85fr)]">
            <div class="rounded-3xl border border-border bg-card shadow-sm">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= lang('transactions_report') ?></h3>
                    <p class="text-sm text-muted-foreground">Filter by account using lookup search while keeping the existing DataTables listing and export behavior.</p>
                </div>
                <div class="overflow-x-auto p-6 pt-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 style="width: 14%"><?= lang('date') ?></th>
                            <th style="width: 16%"><?= lang('account') ?></th>
                            <th style="width: 12%"><?= lang('type') ?></th>
                            <th><?= lang('name') . '/' . lang('title') ?></th>
                            <th><?= lang('amount') ?></th>
                            <th><?= lang('credit') ?></th>
                            <th><?= lang('debit') ?></th>
                            <th><?= lang('balance') ?></th>
                        </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>

            <div class="rounded-3xl border border-border bg-card shadow-sm">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= lang('transactions_report') . ' ' . lang('graph') . ' ' . date('F-Y') ?></h3>
                    <p class="text-sm text-muted-foreground">Daily comparison of income, expense, and transfer activity for the current month.</p>
                </div>
                <div class="space-y-4 p-6">
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Entries</p>
                            <p class="mt-2 text-lg font-bold text-foreground"><?= $report_entries ?></p>
                        </div>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('credit') ?></p>
                            <p class="mt-2 text-lg font-bold text-emerald-600 dark:text-emerald-300"><?= display_money($total_credit, $currency_symbol) ?></p>
                        </div>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('debit') ?></p>
                            <p class="mt-2 text-lg font-bold text-rose-600 dark:text-rose-300"><?= display_money($total_debit, $currency_symbol) ?></p>
                        </div>
                    </div>
                    <div data-chart="line" data-height="320" data-height-sm="240" data-series='<?= json_encode($transactions_chart_series, JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>
        </section>
    </div>
</div>

<div id="transactions-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-sky-500/30 border-t-sky-500"></div>
            <div>
                <p class="text-sm font-semibold text-foreground">Loading transactions report...</p>
                <p class="text-xs text-muted-foreground">Refreshing ledger data.</p>
            </div>
        </div>
    </div>
</div>

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

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

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

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

        function reloadTransactionReport(filterBy) {
            var url = list;
            if (filterBy) {
                url += "/" + filterBy;
            }
            showTransactionsPreloader();
            table_url(url);
        }

        window.transactionReportAccountFilter = function (id) {
            reloadTransactionReport(id);
        };

        $(document).on('click', '[data-transactions-report-filter-action]', function () {
            var filterBy = $(this).data('transactions-report-filter') || '';
            reloadTransactionReport(filterBy);
        });
        if (typeof window.erpInitCharts === 'function') {
            window.erpInitCharts(document);
        }
    });

    window.transactionsReportPrintHtml = <?= json_encode(isset($transactions_report_print_html) ? $transactions_report_print_html : '', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    function print_sales_report(printReport) {
        var fallback = document.getElementById(printReport);
        var printHtml = window.transactionsReportPrintHtml || (fallback ? fallback.outerHTML : '');
        if (!printHtml) return false;

        var printWindow = window.open('', 'PRINT', 'height=900,width=1200');
        if (!printWindow) {
            if (typeof window.erpNativePrint === 'function') {
                window.erpNativePrint();
            } else if (typeof window.print === 'function') {
                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();
            if (typeof printWindow.print === 'function') {
                printWindow.print();
            }
            printWindow.close();
        };
        printWindow.onload = function() {
            printWindow.setTimeout(doPrint, 350);
        };
        printWindow.setTimeout(doPrint, 1000);
        return false;
    }
</script>
