<?php
$chart_year = ($this->session->userdata('chart_year')) ? $this->session->userdata('chart_year') : date('Y');
$cur = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$this->lang->load('calendar', config_item('language'));

$report_links = array(
    'invoices' => lang('invoices_report'),
    'invoice_by_client' => lang('invoice_by_client'),
    'payments' => lang('payments_report'),
    'estimates' => lang('estimates_report'),
    'estimate_by_client' => lang('estimate_by_client'),
    'proposals' => lang('proposals_report'),
    'proposal_by_client' => lang('proposal_by_client'),
);

$status = !empty($status) ? $status : 'all';
$range = !empty($range) ? $range : array('0', '0');
$id = !empty($filterBy) ? $filterBy : 'sales_report';

$total_sales = $this->invoice_model->total_sales();
$paid_this_year = $this->invoice_model->paid_by_date(date('Y'));
$paid_this_month = $this->invoice_model->paid_by_date(date('Y'), date('m'));
$prevmonth = date('Y-m', safe_strtotime("last month"));
$lyear = date('Y', safe_strtotime($prevmonth));
$lmonth = date('m', safe_strtotime($prevmonth));
$paid_last_month = $this->invoice_model->paid_by_date($lyear, $lmonth);
$total_payments = (int) $this->db->count_all('tbl_payments');

$period_one = array(
    '01' => $this->invoice_model->paid_by_date($chart_year, '01'),
    '02' => $this->invoice_model->paid_by_date($chart_year, '02'),
    '03' => $this->invoice_model->paid_by_date($chart_year, '03'),
    '04' => $this->invoice_model->paid_by_date($chart_year, '04'),
    '05' => $this->invoice_model->paid_by_date($chart_year, '05'),
    '06' => $this->invoice_model->paid_by_date($chart_year, '06'),
);

$period_two = array(
    '07' => $this->invoice_model->paid_by_date($chart_year, '07'),
    '08' => $this->invoice_model->paid_by_date($chart_year, '08'),
    '09' => $this->invoice_model->paid_by_date($chart_year, '09'),
    '10' => $this->invoice_model->paid_by_date($chart_year, '10'),
    '11' => $this->invoice_model->paid_by_date($chart_year, '11'),
    '12' => $this->invoice_model->paid_by_date($chart_year, '12'),
);

$summary_cards = array(
    array(
        'label' => lang('total_sales'),
        'value' => display_money($total_sales, $cur->symbol),
        'meta' => 'All recorded sales value',
        'icon' => 'badge-dollar-sign',
        'tone' => 'text-emerald-600 dark:text-emerald-300 bg-emerald-500/10',
    ),
    array(
        'label' => lang('paid_this_year'),
        'value' => display_money($paid_this_year, $cur->symbol),
        'meta' => 'Collected during ' . date('Y'),
        'icon' => 'calendar-range',
        'tone' => 'text-blue-600 dark:text-blue-300 bg-blue-500/10',
    ),
    array(
        'label' => lang('paid_this_month'),
        'value' => display_money($paid_this_month, $cur->symbol),
        'meta' => date('F Y') . ' collection',
        'icon' => 'calendar-days',
        'tone' => 'text-violet-600 dark:text-violet-300 bg-violet-500/10',
    ),
    array(
        'label' => lang('paid') . ' ' . lang('last_month'),
        'value' => display_money($paid_last_month, $cur->symbol),
        'meta' => date('F Y', safe_strtotime($prevmonth)),
        'icon' => 'history',
        'tone' => 'text-amber-600 dark:text-amber-300 bg-amber-500/10',
    ),
    array(
        'label' => lang('total') . ' ' . lang('payments'),
        'value' => $total_payments,
        'meta' => 'All payment records',
        'icon' => 'wallet-cards',
        'tone' => 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
);

$render_period = function ($period, $title) use ($cur) {
    $month_labels = array(
        '01' => lang('cal_january'),
        '02' => lang('cal_february'),
        '03' => lang('cal_march'),
        '04' => lang('cal_april'),
        '05' => lang('cal_may'),
        '06' => lang('cal_june'),
        '07' => lang('cal_july'),
        '08' => lang('cal_august'),
        '09' => lang('cal_september'),
        '10' => lang('cal_october'),
        '11' => lang('cal_november'),
        '12' => lang('cal_december'),
    );
    ?>
    <div class="rounded-2xl border border-border bg-card p-5 shadow-sm sales-report-period">
        <div class="mb-4 flex items-center justify-between sales-report-period-head">
            <div>
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('sales_report') ?></p>
                <h3 class="text-lg font-semibold text-foreground"><?= $title ?></h3>
            </div>
            <span class="inline-flex rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
                <?= count($period) ?> months
            </span>
        </div>
        <div class="space-y-3 sales-report-period-list">
            <?php foreach ($period as $month_key => $month_value): ?>
                <?php
                $max_value = max($period);
                $bar_width = $max_value > 0 ? ($month_value / $max_value) * 100 : 0;
                ?>
                <div class="rounded-xl border border-border bg-background/70 p-3 sales-report-period-item">
                    <div class="mb-2 flex items-center justify-between gap-3 sales-report-period-head">
                        <p class="text-sm font-medium text-foreground"><?= $month_labels[$month_key] ?></p>
                        <p class="text-sm font-semibold text-foreground"><?= display_money($month_value, $cur->symbol) ?></p>
                    </div>
                    <progress class="report-meter report-meter-primary sales-report-bar" max="100" value="<?= min(100, max(0, $bar_width)) ?>"></progress>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="mt-4 flex items-center justify-between rounded-xl border border-primary/15 bg-primary/5 px-4 py-3 sales-report-period-total">
            <p class="text-sm font-semibold text-foreground"><?= lang('total') ?></p>
            <p class="text-base font-bold text-primary"><?= display_money(array_sum($period), $cur->symbol) ?></p>
        </div>
    </div>
    <?php
};
?>

<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-card p-4 shadow-sm md:p-6 sales-report-content">
        <div id="<?= $id ?>" class="">
            <div class="show_print hidden">
                <div class="flex items-center gap-3 border-b border-border pb-3 sales-report-print-head">
                    <img src="<?= base_url() . config_item('company_logo') ?>" alt="" class="h-12 w-12 rounded-xl object-cover">
                    <div>
                        <p class="text-sm font-semibold text-foreground"><?= config_item('company_name') ?></p>
                        <p class="text-xs text-muted-foreground"><?= lang('sales_report') ?></p>
                    </div>
                </div>
                <div class="h-3"></div>
            </div>

            <?php if (!empty($filterBy)): ?>
                <div class="overflow-x-auto">
                    <?php
                    if ($filterBy == 'invoices' || $filterBy == 'invoice_by_client') {
                        $this->load->view('admin/report/invoice_reports');
                    } elseif ($filterBy == 'payments') {
                        $this->load->view('admin/report/payment_reports');
                    } elseif ($filterBy == 'estimates' || $filterBy == 'estimate_by_client') {
                        $this->load->view('admin/report/estimates_reports');
                    } elseif ($filterBy == 'proposals' || $filterBy == 'proposal_by_client') {
                        $this->load->view('admin/report/proposals_reports');
                    }
                    ?>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 gap-6 xl:grid-cols-3 sales-report-layout">
                    <div class="rounded-2xl border border-border bg-background/60 p-5 xl:col-span-1 sales-report-module">
                        <div class="mb-4">
                            <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('report') ?></p>
                            <h3 class="text-lg font-semibold text-foreground">Sales Report Modules</h3>
                        </div>
                        <div class="space-y-3 sales-report-module-list">
                            <?php foreach ($report_links as $key => $label): ?>
                                <a href="<?= base_url('admin/report/sales_report/' . $key) ?>"
                                   class="group flex items-center justify-between rounded-xl border border-border bg-card px-4 py-3 transition hover:border-primary/30 hover:bg-primary/5 sales-report-module-link">
                                    <div>
                                        <p class="text-sm font-semibold text-foreground"><?= $label ?></p>
                                        <p class="text-xs text-muted-foreground">Open detailed report view</p>
                                    </div>
                                    <i data-lucide="arrow-right" class="h-4 w-4 text-muted-foreground transition group-hover:text-primary"></i>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 gap-6 xl:col-span-2 md:grid-cols-2 sales-report-period-grid">
                        <?php $render_period($period_one, '1st ' . lang('six_of') . ', ' . $chart_year); ?>
                        <?php $render_period($period_two, '2nd ' . lang('six_of') . ', ' . $chart_year); ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div id="sales-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-primary/30 border-t-primary"></div>
            <div>
                <p class="text-sm font-semibold text-foreground">Loading sales report...</p>
                <p class="text-xs text-muted-foreground">Preparing the selected module.</p>
            </div>
        </div>
    </div>
</div>

<script>
    function print_sales_report(printReport) {
        var printEl = document.getElementById(printReport);
        if (!printEl) return;
        var reportEl = printReport === 'sales_report' ? (printEl.closest('.sales-report-page') || printEl) : printEl;
        var printClone = reportEl.cloneNode(true);

        printClone.querySelectorAll('script, .hidden-print, .sales-report-filter-shell, #sales-report-preloader').forEach(function(node) {
            node.remove();
        });
        printClone.querySelectorAll('.show_print, .hidden').forEach(function(node) {
            if (node.classList.contains('show_print')) {
                node.classList.remove('hidden');
                node.style.display = '';
            }
        });
        printClone.querySelectorAll('a').forEach(function(node) {
            var text = node.textContent || '';
            var span = document.createElement('span');
            span.textContent = text;
            span.className = node.className;
            node.parentNode.replaceChild(span, node);
        });

        var styles = '';
        document.querySelectorAll('link[rel="stylesheet"]').forEach(function (node) {
            styles += node.outerHTML;
        });

        var printWindow = window.open('', '_blank', 'width=1200,height=800');
        if (!printWindow) return;

        printWindow.document.open();
        printWindow.document.write(
            '<!doctype html><html><head><title><?= lang('sales_report') ?></title>' +
            styles +
            '<style>' +
            'body{background:#fff;color:#111827;margin:0;padding:18px;font:12px/1.45 Arial,Helvetica,sans-serif}' +
            '.sales-report-page{display:block}.grid{display:block}.rounded-2xl,.rounded-xl{border:1px solid #d7deea;border-radius:0;margin-bottom:14px;padding:12px;background:#fff}' +
            '.sales-report-cardgrid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.sales-report-period-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}.sales-report-layout{display:block}' +
            'table{width:100%;border-collapse:collapse;margin-top:10px}th,td{border:1px solid #d7deea;padding:8px;text-align:left;vertical-align:top}th{background:#f1f5f9;font-weight:700;text-transform:uppercase;font-size:10px}.text-right{text-align:right}' +
            '.show_print{display:inline!important}.hidden-print,.sales-report-filter-shell{display:none!important}progress{width:100%;height:8px}.shadow-sm,.shadow-lg{box-shadow:none!important}' +
            '@page{margin:12mm}' +
            '</style>' +
            '</head><body>' +
            printClone.innerHTML +
            '</body></html>'
        );
        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);
    }

    document.addEventListener('DOMContentLoaded', function () {
        var preloader = document.getElementById('sales-report-preloader');
        if (!preloader) return;

        function showSalesReportPreloader() {
            preloader.classList.remove('hidden');
            preloader.classList.add('flex');
        }

        document.querySelectorAll('.sales-report-dropdown-menu a, .sales-report-module-link').forEach(function (link) {
            link.addEventListener('click', function () {
                showSalesReportPreloader();
            });
        });
    });
</script>
