<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 == 'estimate_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) : '';
}

$discount_total = 0;
$estimate_total = 0;
$total_tax = 0;
$estimate_count = !empty($all_estimates) ? count($all_estimates) : 0;
if (!empty($all_estimates)) {
    foreach ($all_estimates as $v_estimates) {
        $estimate_total += $this->estimates_model->estimate_calculation('total', $v_estimates->estimates_id);
        $total_tax += $this->estimates_model->get_estimate_tax_amount($v_estimates->estimates_id);
        $discount_total += $this->estimates_model->get_estimate_discount($v_estimates->estimates_id);
    }
}
?>

<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 == 'estimate_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'),
                    'draft' => lang('draft'),
                    'cancelled' => lang('cancelled'),
                    'expired' => lang('expired'),
                    'declined' => lang('declined'),
                    'accepted' => lang('accepted'),
                ), $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">Estimate pipeline and conversion value overview</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">
                <?= $estimate_count ?> <?= lang('estimates') ?>
            </span>
        </div>

        <div class="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2 xl: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('amount') ?></p>
                <p class="mt-2 text-lg font-bold text-foreground"><?= display_money($estimate_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('discount') ?></p>
                <p class="mt-2 text-lg font-bold text-amber-500"><?= display_money($discount_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($estimate_count ? ($estimate_total / $estimate_count) : 0, $cur->symbol) ?></p>
            </div>
        </div>

        <div class="mt-5 overflow-x-auto rounded-xl border border-border">
            <table class="min-w-[860px] 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('estimate') ?></th>
                    <th class="px-3 py-3"><?= lang('estimate') . ' ' . lang('date') ?></th>
                    <th class="px-3 py-3"><?= lang('expire') . ' ' . lang('date') ?></th>
                    <th class="px-3 py-3"><?= lang('invoice') ?>#</th>
                    <th class="px-3 py-3"><?= lang('client_name') ?></th>
                    <th class="px-3 py-3 text-right"><?= lang('amount') ?></th>
                    <th class="px-3 py-3 text-right"><?= lang('tax') . ' ' . lang('amount') ?></th>
                    <th class="px-3 py-3 text-right"><?= lang('discount') ?></th>
                </tr>
                </thead>
                <tbody class="divide-y divide-border">
                <?php if (!empty($all_estimates)) {
                    foreach ($all_estimates as $v_estimates) { ?>
                        <tr class="hover:bg-muted/30">
                            <td class="px-3 py-3">
                                <a class="hidden-print font-semibold text-primary hover:underline" href="<?= base_url() ?>admin/estimates/create/estimates_details/<?= $v_estimates->estimates_id ?>"><?= $v_estimates->reference_no ?></a>
                                <span class="show_print"><?= $v_estimates->reference_no ?></span>
                            </td>
                            <td class="px-3 py-3 text-foreground"><?= display_date($v_estimates->estimate_date); ?></td>
                            <td class="px-3 py-3 text-foreground"><?= display_date($v_estimates->due_date); ?></td>
                            <td class="px-3 py-3">
                                <?php if ($v_estimates->invoiced == 'Yes') {
                                    $invoice_info = $this->db->where('invoices_id', $v_estimates->invoices_id)->get('tbl_invoices')->row();
                                    if (!empty($invoice_info)) { ?>
                                        <a class="text-emerald-600 hover:underline hidden-print" href="<?= base_url() ?>admin/invoice/manage_invoice/invoice_details/<?= $invoice_info->invoices_id ?>">
                                            <?= $invoice_info->reference_no ?>
                                        </a>
                                        <span class="show_print"><?= $invoice_info->reference_no ?></span>
                                    <?php }
                                } ?>
                            </td>
                            <td class="px-3 py-3">
                                <a class="hidden-print text-foreground hover:text-primary" href="<?= base_url() ?>admin/client/details/<?= $v_estimates->client_id ?>"><?= client_name($v_estimates->client_id) ?></a>
                                <span class="show_print"><?= client_name($v_estimates->client_id) ?></span>
                            </td>
                            <td class="px-3 py-3 text-right font-semibold text-foreground"><?= display_money($this->estimates_model->estimate_calculation('total', $v_estimates->estimates_id), $cur->symbol); ?></td>
                            <td class="px-3 py-3 text-right text-foreground"><?= display_money($this->estimates_model->get_estimate_tax_amount($v_estimates->estimates_id), $cur->symbol); ?></td>
                            <td class="px-3 py-3 text-right font-semibold text-amber-500"><?= display_money($this->estimates_model->get_estimate_discount($v_estimates->estimates_id), $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($estimate_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-amber-500"><?= display_money($discount_total, $cur->symbol) ?></td>
                    </tr>
                <?php } else { ?>
                    <tr>
                        <td colspan="8" class="px-3 py-8 text-center text-sm text-muted-foreground">No estimates found for the selected filters.</td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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

    function positionEstimateDateRangePicker() {
        if (!dateRangePicker || !dateRangePicker.container || !dateRangePicker.container.length) {
            return;
        }
        var wrapNode = dateRangeWrap.get(0);
        if (!wrapNode) {
            return;
        }
        var rect = wrapNode.getBoundingClientRect();
        var pickerNode = dateRangePicker.container.get(0);
        var compactPicker = window.innerWidth < 1400;
        var pickerWidth = compactPicker ? Math.min(560, window.innerWidth - 24) : 720;
        pickerWidth = Math.max(300, pickerWidth);
        var left = Math.min(Math.max(12, rect.left), window.innerWidth - pickerWidth - 12);
        var top = rect.bottom + 8;
        var availableBelow = window.innerHeight - top - 12;
        var maxHeight = Math.max(280, availableBelow);
        if (availableBelow < 360 && rect.top > availableBelow) {
            maxHeight = Math.max(280, rect.top - 12);
            top = Math.max(12, rect.top - maxHeight - 8);
        }

        dateRangePicker.container.addClass('sales-report-range-picker');
        pickerNode.style.setProperty('position', 'fixed', 'important');
        pickerNode.style.setProperty('left', left + 'px', 'important');
        pickerNode.style.setProperty('right', 'auto', 'important');
        pickerNode.style.setProperty('top', top + 'px', 'important');
        pickerNode.style.setProperty('width', pickerWidth + 'px', 'important');
        pickerNode.style.setProperty('max-width', 'calc(100vw - 24px)', 'important');
        pickerNode.style.setProperty('max-height', maxHeight + 'px', 'important');
        pickerNode.style.setProperty('overflow-y', 'auto', 'important');
        pickerNode.style.setProperty('overflow-x', 'hidden', 'important');
        pickerNode.classList.toggle('sales-report-range-picker-compact', compactPicker);
    }

    function initEstimateDateRangePicker() {
        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: "left",
            parentEl: 'body',
            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');
        if (dateRangePicker && dateRangePicker.container) {
            dateRangePicker.container.addClass('sales-report-range-picker');
        }
        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(positionEstimateDateRangePicker, 0);
        });
        dateRangePicker.container.on('click', '.prev, .next, th.available, td.available', function () {
            window.setTimeout(positionEstimateDateRangePicker, 0);
        });
        positionEstimateDateRangePicker();
        return dateRangePicker;
    }

    if (dateRangeWrap.length) {
        dateRangeWrap.on('click', function () {
            var picker = initEstimateDateRangePicker();
            if (picker) {
                positionEstimateDateRangePicker();
                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) {
            positionEstimateDateRangePicker();
            dateRangePicker.updateCalendars();
        }
    });
    $(window).on('resize scroll', function () {
        if (dateRangePicker && dateRangePicker.container && dateRangePicker.container.is(':visible')) {
            positionEstimateDateRangePicker();
        }
    });
    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>
