<?= message_box('success'); ?>
<?= message_box('error'); ?>

<?php $selected_year = !empty($year) ? $year : date('Y'); ?>
<div class="space-y-6">
    <div id="expense_report" class="rounded-2xl border border-border bg-card shadow-sm">
        <div class="flex flex-col gap-4 border-b border-border p-4 lg:flex-row lg:items-start lg:justify-between">
                <div class="min-w-0 flex-1">
                    <div class="flex flex-wrap gap-2">
                        <?php foreach ($report_by_month as $key => $v_month):
                            $month_name = date('F', safe_strtotime($selected_year . '-' . $key));
                            $active_month = ($current_month == $key);
                            ?>
                            <button type="button"
                    class="js-report-month rounded-full px-3 py-1 text-xs font-semibold
					<?= ($current_month == $key) ? 'bg-indigo-600 text-white shadow-sm' : ' text-muted-foreground' ?>"
                    data-month-target="<?= $month_name ?>" data-month-number="<?= sprintf('%02d', $key) ?>">
                    <span><?= $month_name ?></span>
                </button>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="w-full lg:w-auto lg:min-w-[280px]">
                    <form id="existing_customer" action="<?php echo base_url() ?>admin/report/report_by_month" method="post"
                        class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-end">
                        <label for="report-year" class="block w-full space-y-1 text-sm font-medium text-foreground sm:max-w-[180px]">                            
                            <input id="report-year" name="year" type="text" required
                                value="<?= html_escape($selected_year) ?>"
                                class="years w-full rounded-lg border border-border bg-input px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-secondary/30 dark:focus:border-secondary dark:focus:ring-3 dark:focus:ring-secondary/30"
                                data-format="yyyy">
                        </label>

                        <button type="submit" data-toggle="tooltip" data-placement="top" title="<?= lang('search') ?>"
                            class="inline-flex w-full items-center justify-center gap-2 rounded-lg border border-border bg-primary px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted sm:w-auto sm:self-end">
                            <i data-lucide="search" class="h-4 w-4"></i>
                            <?= lang('search') ?>
                        </button>
                    </form>
                </div>
            </div>


        <div class="">
            <?php foreach ($report_by_month as $key => $v_monthly_report):
                $month_name = date('F', safe_strtotime($selected_year . '-' . $key));
                $total_amount = 0;
                $total_debit = 0;
                $total_credit = 0;
                $currency = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
                if (!empty($v_monthly_report)) {
                    foreach ($v_monthly_report as $v_month) {
                        $total_amount += $v_month->amount;
                        $total_debit += $v_month->debit;
                        $total_credit += $v_month->credit;
                    }
                }
                ?>
            <section class="js-report-month-panel <?= ($current_month == $key) ? '' : 'hidden' ?>"
                data-month-panel="<?= $month_name ?>">
                <div class=" border-t border-border bg-card shadow-sm">

                    <div class="grid grid-cols-1 gap-4 p-6 md:grid-cols-3">
                        <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>
                        </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>
                        </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>
                        </div>
                    </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('type') ?></th>
                                    <th class="px-4 py-3"><?= lang('notes') ?></th>
                                    <th class="px-4 py-3 text-right"><?= lang('amount') ?></th>
                                    <th class="px-4 py-3 text-right"><?= lang('credit') ?></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 if (!empty($v_monthly_report)): foreach ($v_monthly_report as $v_month):
                                    $account_info = $this->report_model->check_by(array('account_id' => $v_month->account_id), 'tbl_accounts'); ?>
                                <tr class="hover:bg-muted/30">
                                    <td class="px-4 py-3 text-foreground"><?= display_date($v_month->date); ?></td>
                                    <td class="px-4 py-3 text-foreground"><?= !empty($account_info->account_name) ? $account_info->account_name : '-' ?></td>
                                    <td class="px-4 py-3 text-muted-foreground"><?= lang($v_month->type) ?></td>
                                    <td class="px-4 py-3 text-muted-foreground"><?= $v_month->notes ?></td>
                                    <td class="px-4 py-3 text-right font-medium text-foreground">
                                        <?= display_money($v_month->amount, $currency->symbol) ?></td>
                                    <td
                                        class="px-4 py-3 text-right font-semibold text-emerald-600 dark:text-emerald-300">
                                        <?= display_money($v_month->credit, $currency->symbol) ?></td>
                                    <td class="px-4 py-3 text-right font-semibold text-rose-600 dark:text-rose-300">
                                        <?= display_money($v_month->debit, $currency->symbol) ?></td>
                                    <td class="px-4 py-3 text-right font-medium text-foreground">
                                        <?= display_money($v_month->total_balance, $currency->symbol) ?></td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                            <tfoot class="border-t border-border bg-muted/10">
                                <tr>
                                    <td colspan="4" 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-emerald-600 dark:text-emerald-300">
                                        <?= display_money($total_credit, $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_credit - $total_debit, $currency->symbol) ?></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </section>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php if (!empty($report_by_month_print_html)) : ?>
    <?php foreach ($report_by_month_print_html as $print_month => $print_html) : ?>
        <textarea class="hidden" style="display:none" data-report-by-month-print-html="<?= html_escape($print_month) ?>"><?= html_escape($print_html) ?></textarea>
    <?php endforeach; ?>
<?php endif; ?>
<script type="text/javascript">
function expense_report(expense_report) {
    var activeMonth = document.querySelector('.js-report-month.bg-indigo-600');
    var monthNumber = activeMonth ? activeMonth.getAttribute('data-month-number') : '<?= sprintf('%02d', (int) $current_month) ?>';
    var textarea = document.querySelector('[data-report-by-month-print-html="' + monthNumber + '"]');
    var fallback = document.getElementById(expense_report);
    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;
}

document.addEventListener('click', function(e) {
    var monthButton = e.target.closest('.js-report-month');
    if (!monthButton) return;

    var target = monthButton.getAttribute('data-month-target');
    var monthNumber = monthButton.getAttribute('data-month-number');
    var pdfButton = document.getElementById('report-by-month-pdf');
    if (pdfButton && monthNumber) {
        pdfButton.setAttribute('href', base_url + 'admin/report/report_by_month_pdf/<?= $selected_year ?>/' +
            monthNumber);
    }
    document.querySelectorAll('.js-report-month').forEach(function(button) {
        button.classList.remove('bg-indigo-600', 'text-white', 'shadow-sm');
        button.classList.add('text-foreground');
    });
	// bg-indigo-600 text-white shadow-sm
    monthButton.classList.add('bg-indigo-600', 'text-white', 'shadow-sm');
    monthButton.classList.remove('text-foreground');

    document.querySelectorAll('.js-report-month-panel').forEach(function(panel) {
        panel.classList.toggle('hidden', panel.getAttribute('data-month-panel') !== target);
    });
});
</script>
