<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css"/>

<?php
$cur = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
if (!empty($range[0])) {
    $start_date = date('F d, Y', safe_strtotime($range[0]));
    $end_date = date('F d, Y', safe_strtotime($range[1]));
}
$status = (isset($status)) ? $status : 'all';
$selected_client_id = ($filterBy == 'invoice_by_client' && !empty($status) && $status !== 'all') ? $status : '';
$selected_client_label = '';
if (!empty($selected_client_id)) {
    $selected_client_info = $this->report_model->check_by(array('client_id' => $selected_client_id), 'tbl_client');
    $selected_client_label = !empty($selected_client_info->name) ? ucfirst($selected_client_info->name) : '';
}

$invoice_count = isset($invoice_count) ? (int) $invoice_count : (!empty($all_invoices) ? count($all_invoices) : 0);
$invoice_total = isset($invoice_total) ? (float) $invoice_total : 0;
$total_tax = isset($total_tax) ? (float) $total_tax : 0;
$due_total = isset($due_total) ? (float) $due_total : 0;
if (empty($invoice_total) && empty($total_tax) && empty($due_total) && !empty($all_invoices)) {
    foreach ($all_invoices as $invoice) {
        $invoice_payable = !empty($invoice->invoice_total) ? (float) $invoice->invoice_total : $this->invoice_model->invoice_payable($invoice->invoices_id);
        $invoice_due = !empty($invoice->due_amount) ? (float) $invoice->due_amount : $this->invoice_model->calculate_to('invoice_due', $invoice->invoices_id);
        $tax_amount = !empty($invoice->tax_amount) ? (float) $invoice->tax_amount : $this->invoice_model->get_invoice_tax_amount($invoice->invoices_id);
        $invoice_total += $invoice_payable;
        $due_total += $invoice_due;
        $total_tax += $tax_amount;
    }
}
$average_total = isset($average_total) ? (float) $average_total : ($invoice_count ? ($invoice_total / $invoice_count) : 0);
$current_page = isset($current_page) ? (int) $current_page : 1;
$total_pages = isset($total_pages) ? (int) $total_pages : 1;
$pagination_base_url = !empty($pagination_base_url) ? $pagination_base_url : '';
?>

<div class="space-y-5">
    <div class="sales-report-filter-shell relative overflow-visible hidden-print rounded-2xl border border-border bg-background/60 p-4">
        <?= form_open(base_url() . 'admin/report/sales_report/' . $filterBy, array('method' => 'get', 'class' => 'grid grid-cols-1 gap-4 md:grid-cols-12 md:items-end')) ?>
        <?php if ($filterBy == 'invoice_by_client') { ?>
            <div class="md:col-span-4">
                <?= form_lookup_group('status', lang('select_client'), $selected_client_id, $selected_client_label, false, array(), '', array('type' => 'client', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('client'))); ?>
            </div>
        <?php } else { ?>
            <div class="md:col-span-3">
                <?= form_select_group('status', lang('status'), array(
                    'all' => lang('all'),
                    'paid' => lang('paid'),
                    'not_paid' => lang('not_paid'),
                    'partially_paid' => lang('partially_paid'),
                    'cancelled' => lang('cancelled'),
                    'draft' => lang('draft'),
                    'overdue' => lang('overdue'),
                    'recurring' => lang('recurring'),
                ), $status, false, array(), '', '', 'stacked'); ?>
            </div>
        <?php } ?>

        <div class="md:col-span-5">
            <label class="mb-1 block text-sm font-medium text-foreground"><?= lang('date_range') ?></label>
            <div class="sales-report-date-range relative flex w-full items-center gap-2 overflow-visible rounded-xl border border-border bg-card px-3 py-2 shadow-sm focus-within:border-primary">
                <i data-lucide="calendar-range" class="h-4 w-4 text-muted-foreground"></i>
                <input type="text" name="range" id="reportrange" value="<?= !empty($start_date) ? html_escape($start_date . ' - ' . $end_date) : '' ?>" placeholder="Select a date range" readonly class="w-full border-0 bg-transparent p-0 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none">
            </div>
        </div>
        <div class="md:col-span-2">
            <button class="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90" type="submit">
                <i data-lucide="play" class="h-4 w-4"></i>
                <?= lang('run_report') ?>
            </button>
        </div>
        </form>
    </div>

    <div class="rounded-2xl border border-border bg-card p-5 shadow-sm">
        <div class="flex flex-col gap-2 border-b border-border pb-4 md:flex-row md:items-center md:justify-between">
            <div>
                <h3 class="text-lg font-semibold text-foreground"><?= lang($filterBy) ?></h3>
                <?php if (!empty($start_date)) { ?>
                    <p class="text-sm text-muted-foreground"><?= lang('from') ?> <?= $start_date ?> - <?= lang('to') ?> <?= $end_date ?></p>
                <?php } else { ?>
                    <p class="text-sm text-muted-foreground">Filtered invoice performance summary</p>
                <?php } ?>
            </div>
            <span class="inline-flex rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
                <?= $invoice_count ?> <?= lang('invoices') ?>
            </span>
        </div>

        <div class="mt-4 grid grid-cols-1 gap-3 md:grid-cols-4">
            <div class="rounded-xl border border-border bg-background/70 p-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('invoice_amount') ?></p>
                <p class="mt-2 text-lg font-bold text-foreground"><?= display_money($invoice_total, $cur->symbol) ?></p>
            </div>
            <div class="rounded-xl border border-border bg-background/70 p-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('tax') . ' ' . lang('amount') ?></p>
                <p class="mt-2 text-lg font-bold text-foreground"><?= display_money($total_tax, $cur->symbol) ?></p>
            </div>
            <div class="rounded-xl border border-border bg-background/70 p-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('balance_due') ?></p>
                <p class="mt-2 text-lg font-bold text-rose-500"><?= display_money($due_total, $cur->symbol) ?></p>
            </div>
            <div class="rounded-xl border border-border bg-background/70 p-4">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('average') ?></p>
                <p class="mt-2 text-lg font-bold text-foreground"><?= display_money($average_total, $cur->symbol) ?></p>
            </div>
        </div>

        <div class="mt-5 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-3 py-3"><?= lang('status') ?></th>
                    <th class="px-3 py-3"><?= lang('invoice_date') ?></th>
                    <th class="px-3 py-3"><?= lang('due_date') ?></th>
                    <th class="px-3 py-3"><?= lang('reference_no') ?></th>
                    <th class="px-3 py-3"><?= lang('client_name') ?></th>
                    <th class="px-3 py-3 text-right"><?= lang('invoice_amount') ?></th>
                    <th class="px-3 py-3 text-right"><?= lang('tax') . ' ' . lang('amount') ?></th>
                    <th class="px-3 py-3 text-right"><?= lang('balance_due') ?></th>
                </tr>
                </thead>
                <tbody class="divide-y divide-border">
                <?php
                if (!empty($all_invoices)) {
                    foreach ($all_invoices as $invoice) {
                        $status_label = !empty($invoice->payment_status_key) ? lang($invoice->payment_status_key) : $this->invoice_model->get_payment_status($invoice->invoices_id);
                        $text_color = 'text-blue-600 dark:text-blue-300 bg-blue-500/10';
                        switch ($status_label) {
                            case lang('fully_paid'):
                                $text_color = 'text-emerald-600 dark:text-emerald-300 bg-emerald-500/10';
                                break;
                            case lang('partially_paid'):
                                $text_color = 'text-amber-600 dark:text-amber-300 bg-amber-500/10';
                                break;
                            case lang('not_paid'):
                                $text_color = 'text-rose-600 dark:text-rose-300 bg-rose-500/10';
                                break;
                        }
                        $invoice_payable = !empty($invoice->invoice_total) ? $invoice->invoice_total : $this->invoice_model->invoice_payable($invoice->invoices_id);
                        $invoice_due = !empty($invoice->due_amount) ? $invoice->due_amount : $this->invoice_model->calculate_to('invoice_due', $invoice->invoices_id);
                        $tax_amount = !empty($invoice->tax_amount) ? $invoice->tax_amount : $this->invoice_model->get_invoice_tax_amount($invoice->invoices_id);
                        ?>
                        <tr class="hover:bg-muted/30">
                            <td class="px-3 py-3">
                                <span class="inline-flex rounded-full px-2 py-1 text-[11px] font-semibold <?= $text_color ?>"><?= $status_label ?></span>
                            </td>
                            <td class="px-3 py-3 text-foreground"><?= display_date($invoice->invoice_date); ?></td>
                            <td class="px-3 py-3 text-foreground"><?= display_date($invoice->due_date); ?></td>
                            <td class="px-3 py-3">
                                <a class="hidden-print font-semibold text-primary hover:underline" href="<?= base_url() ?>admin/invoice/manage_invoice/invoice_details/<?= $invoice->invoices_id ?>"><?= $invoice->reference_no ?></a>
                                <span class="show_print"><?= $invoice->reference_no ?></span>
                            </td>
                            <td class="px-3 py-3">
                                <a class="hidden-print text-foreground hover:text-primary" href="<?= base_url() ?>admin/client/details/<?= $invoice->client_id ?>"><?= client_name($invoice->client_id) ?></a>
                                <span class="show_print"><?= client_name($invoice->client_id) ?></span>
                            </td>
                            <td class="px-3 py-3 text-right font-semibold text-foreground"><?= display_money($invoice_payable, $cur->symbol); ?></td>
                            <td class="px-3 py-3 text-right text-foreground"><?= display_money($tax_amount, $cur->symbol); ?></td>
                            <td class="px-3 py-3 text-right font-semibold text-rose-500"><?= display_money($invoice_due, $cur->symbol); ?></td>
                        </tr>
                    <?php } ?>
                    <tr class="bg-muted/20">
                        <td colspan="5" class="px-3 py-3 font-semibold text-foreground"><?= lang('total') ?></td>
                        <td class="px-3 py-3 text-right font-bold text-foreground"><?= display_money($invoice_total, $cur->symbol) ?></td>
                        <td class="px-3 py-3 text-right font-bold text-foreground"><?= display_money($total_tax, $cur->symbol) ?></td>
                        <td class="px-3 py-3 text-right font-bold text-rose-500"><?= display_money($due_total, $cur->symbol) ?></td>
                    </tr>
                <?php } else { ?>
                    <tr>
                        <td colspan="8" class="px-3 py-8 text-center text-sm text-muted-foreground">No invoices found for the selected filters.</td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>

        <?php if (!empty($total_pages) && $total_pages > 1) { ?>
            <div class="mt-5 flex flex-col gap-3 border-t border-border pt-4 md:flex-row md:items-center md:justify-between">
                <p class="text-sm text-muted-foreground">Showing page <?= $current_page ?> of <?= $total_pages ?> · <?= $invoice_count ?> total invoices</p>
                <div class="flex flex-wrap items-center gap-2">
                    <?php
                    $build_page_url = function ($page_number) use ($pagination_base_url) {
                        return $pagination_base_url . 'page=' . (int) $page_number;
                    };
                    ?>
                    <a href="<?= $current_page > 1 ? html_escape($build_page_url($current_page - 1)) : '#' ?>" class="inline-flex items-center gap-1 rounded-lg border border-border bg-background px-3 py-2 text-xs font-semibold text-foreground <?= $current_page <= 1 ? 'pointer-events-none opacity-40' : 'hover:bg-muted' ?>">
                        <i data-lucide="chevron-left" class="h-4 w-4"></i>
                        <?= lang('previous_page') ?: 'Previous' ?>
                    </a>
                    <?php
                    $start_page = max(1, $current_page - 2);
                    $end_page = min($total_pages, $current_page + 2);
                    for ($page_no = $start_page; $page_no <= $end_page; $page_no++) {
                        $is_active = $page_no === $current_page;
                        ?>
                        <a href="<?= html_escape($build_page_url($page_no)) ?>" class="inline-flex min-w-10 items-center justify-center rounded-lg border px-3 py-2 text-xs font-semibold <?= $is_active ? 'border-primary bg-primary text-primary-foreground' : 'border-border bg-background text-foreground hover:bg-muted' ?>">
                            <?= $page_no ?>
                        </a>
                    <?php } ?>
                    <a href="<?= $current_page < $total_pages ? html_escape($build_page_url($current_page + 1)) : '#' ?>" class="inline-flex items-center gap-1 rounded-lg border border-border bg-background px-3 py-2 text-xs font-semibold text-foreground <?= $current_page >= $total_pages ? 'pointer-events-none opacity-40' : 'hover:bg-muted' ?>">
                        <?= lang('next_page') ?: 'Next' ?>
                        <i data-lucide="chevron-right" class="h-4 w-4"></i>
                    </a>
                </div>
            </div>
        <?php } ?>
    </div>
</div>

<script type="text/javascript">
    var reportRangeInput = $('#reportrange');
    var reportRangeValue = reportRangeInput.val();
    var dateRangeWrap = $('.sales-report-date-range');
    var dateRangePicker = null;

    function positionInvoiceDateRangePicker() {
        if (!dateRangePicker || !dateRangePicker.container || !dateRangePicker.container.length) {
            return;
        }
        var offset = dateRangeWrap.offset();
        if (!offset) {
            return;
        }
        var pickerNode = dateRangePicker.container.get(0);
        pickerNode.style.setProperty('position', 'absolute', 'important');
        pickerNode.style.setProperty('left', offset.left + 'px', 'important');
        pickerNode.style.setProperty('right', 'auto', 'important');
        pickerNode.style.setProperty('top', (offset.top + dateRangeWrap.outerHeight() + 10) + 'px', 'important');
        pickerNode.style.setProperty('min-width', dateRangePicker.container.hasClass('show-calendar') ? '680px' : '220px', 'important');
        pickerNode.style.setProperty('max-width', 'calc(100vw - ' + (offset.left + 24) + 'px)', 'important');
    }

    function initInvoiceDateRangePicker() {
        if (dateRangePicker) {
            return dateRangePicker;
        }
        reportRangeInput.daterangepicker({
            autoUpdateInput: <?= !empty($start_date) ? 'true' : 'false'?>,
            locale: { format: 'MMMM D, YYYY' },
            <?php if(!empty($start_date)){?>
            startDate: '<?=$start_date?>',
            endDate: '<?=$end_date?>',
            <?php }?>
            drops: 'down',
            opens: "right",
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        });
        dateRangePicker = reportRangeInput.data('daterangepicker');
        reportRangeInput.off('click.daterangepicker focus.daterangepicker keyup.daterangepicker');
        if (dateRangePicker && reportRangeValue) {
            var reportRangeParts = reportRangeValue.split(' - ');
            if (reportRangeParts.length === 2) {
                var parsedStartDate = moment(reportRangeParts[0], 'MMMM D, YYYY', true);
                var parsedEndDate = moment(reportRangeParts[1], 'MMMM D, YYYY', true);
                if (parsedStartDate.isValid() && parsedEndDate.isValid()) {
                    dateRangePicker.setStartDate(parsedStartDate);
                    dateRangePicker.setEndDate(parsedEndDate);
                    dateRangePicker.updateView();
                    dateRangePicker.updateCalendars();
                }
            }
        }
        dateRangePicker.hide();
        dateRangePicker.container.hide();
        dateRangePicker.container.on('click', '.ranges li', function () {
            window.setTimeout(positionInvoiceDateRangePicker, 0);
        });
        positionInvoiceDateRangePicker();
        return dateRangePicker;
    }

    if (dateRangeWrap.length) {
        dateRangeWrap.on('click', function () {
            var picker = initInvoiceDateRangePicker();
            if (picker) {
                positionInvoiceDateRangePicker();
                picker.show();
            }
        });
        $(document).on('mousedown', function (event) {
            if ($(event.target).closest('.daterangepicker').length) {
                return;
            }
            if (dateRangePicker && !dateRangeWrap.is(event.target) && dateRangeWrap.has(event.target).length === 0) {
                dateRangePicker.hide();
            }
        });
    }
    reportRangeInput.on('show.daterangepicker', function () {
        if (dateRangePicker) {
            positionInvoiceDateRangePicker();
            dateRangePicker.updateCalendars();
        }
    });
    reportRangeInput.on('apply.daterangepicker', function (ev, picker) {
        reportRangeValue = picker.startDate.format('MMMM D, YYYY') + ' - ' + picker.endDate.format('MMMM D, YYYY');
        $(this).val(reportRangeValue);
    });
    reportRangeInput.on('cancel.daterangepicker', function () {
        $(this).val(reportRangeValue || '');
        if (dateRangePicker && reportRangeValue) {
            var restoredRangeParts = reportRangeValue.split(' - ');
            if (restoredRangeParts.length === 2) {
                var restoredStartDate = moment(restoredRangeParts[0], 'MMMM D, YYYY', true);
                var restoredEndDate = moment(restoredRangeParts[1], 'MMMM D, YYYY', true);
                if (restoredStartDate.isValid() && restoredEndDate.isValid()) {
                    dateRangePicker.setStartDate(restoredStartDate);
                    dateRangePicker.setEndDate(restoredEndDate);
                }
            }
            dateRangePicker.updateView();
            dateRangePicker.updateCalendars();
        }
    });
</script>
