<?php
$client_id = $this->session->userdata('client_id');
$client_outstanding = $this->invoice_model->client_outstanding($client_id);
$currency = $this->db->where(array('code' => config_item('default_currency')))->get('tbl_currencies')->row();
?>

<div class="invoice-modern">
    <?php echo message_box('success'); ?>
    <?php echo message_box('error'); ?>

    <div class="space-y-4">
        <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('total') . ' ' . lang('outstanding') . ' ' . lang('invoice') ?></p>
                <p class="mt-2 text-2xl font-bold text-foreground">
                    <?php
                    if ($client_outstanding > 0) {
                        echo display_money($client_outstanding, $currency->symbol);
                    } else {
                        echo '0.00';
                    }
                    ?>
                </p>
            </div>
            <?php
            $past_overdue = 0;
            $all_paid_amount = 0;
            $not_paid = 0;
            $fully_paid = 0;
            $draft = 0;
            $partially_paid = 0;
            $overdue = 0;
            $all_invoices = $this->db->where(array('client_id' => $client_id, 'status !=' => 'draft'))->get('tbl_invoices')->result();

            if (!empty($all_invoices)) {
                $all_invoices = array_reverse($all_invoices);
                foreach ($all_invoices as $v_invoice) {
                    $payment_status = $this->invoice_model->get_payment_status($v_invoice->invoices_id);
                    if (safe_strtotime($v_invoice->due_date) < safe_strtotime(date('Y-m-d')) && $payment_status != lang('fully_paid')) {
                        $past_overdue += $this->invoice_model->calculate_to('invoice_due', $v_invoice->invoices_id);
                    }
                    $all_paid_amount += $this->invoice_model->calculate_to('paid_amount', $v_invoice->invoices_id);

                    if ($this->invoice_model->get_payment_status($v_invoice->invoices_id) == lang('not_paid')) {
                        $not_paid += count(array($v_invoice->invoices_id));
                    }
                    if ($this->invoice_model->get_payment_status($v_invoice->invoices_id) == lang('fully_paid')) {
                        $fully_paid += count(array($v_invoice->invoices_id));
                    }
                    if ($this->invoice_model->get_payment_status($v_invoice->invoices_id) == lang('draft')) {
                        $draft += count(array($v_invoice->invoices_id));
                    }
                    if ($this->invoice_model->get_payment_status($v_invoice->invoices_id) == lang('partially_paid')) {
                        $partially_paid += count(array($v_invoice->invoices_id));
                    }
                    if (safe_strtotime($v_invoice->due_date) < safe_strtotime(date('Y-m-d')) && $payment_status != lang('fully_paid')) {
                        $overdue += count(array($v_invoice->invoices_id));
                    }
                }
            }
            $invoice_total_count = !empty($all_invoices) ? count($all_invoices) : 0;
            ?>
            <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('total') . ' ' . lang('invoice_amount') ?></p>
                <p class="mt-2 text-2xl font-bold text-foreground"><?= display_money($all_paid_amount + $client_outstanding, $currency->symbol) ?></p>
            </div>
            <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('past') . ' ' . lang('overdue') . ' ' . lang('invoice') ?></p>
                <p class="mt-2 text-2xl font-bold text-foreground"><?= display_money($past_overdue, $currency->symbol) ?></p>
            </div>
            <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('paid') . ' ' . lang('invoice') ?></p>
                <p class="mt-2 text-2xl font-bold text-foreground"><?= display_money($all_paid_amount, $currency->symbol) ?></p>
            </div>
        </div>

        <?php if (!empty($all_invoices)) { ?>
            <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                    <div class="flex items-center justify-between">
                        <a class="text-sm font-semibold text-foreground filter_by" search-type="<?= lang('not_paid') ?>" id="not_paid" href="#"><?= lang('unpaid') ?></a>
                        <span class="text-xs text-muted-foreground"><?= $not_paid ?> / <?= $invoice_total_count ?></span>
                    </div>
                    <div class="mt-3 h-2 rounded-full bg-slate-100">
                        <div class="h-2 rounded-full bg-rose-500" data-toggle="tooltip"
                             data-original-title="<?= round(($not_paid / $invoice_total_count) * 100) ?>%"
                             style="width: <?= ($not_paid / $invoice_total_count) * 100 ?>%"></div>
                    </div>
                </div>

                <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                    <div class="flex items-center justify-between">
                        <a class="text-sm font-semibold text-foreground filter_by" search-type="<?= lang('paid') ?>" id="paid" href="#"><?= lang('paid') ?></a>
                        <span class="text-xs text-muted-foreground"><?= $fully_paid ?> / <?= $invoice_total_count ?></span>
                    </div>
                    <div class="mt-3 h-2 rounded-full bg-slate-100">
                        <div class="h-2 rounded-full bg-emerald-500" data-toggle="tooltip"
                             data-original-title="<?= round(($fully_paid / $invoice_total_count) * 100) ?>%"
                             style="width: <?= ($fully_paid / $invoice_total_count) * 100 ?>%"></div>
                    </div>
                </div>

                <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                    <div class="flex items-center justify-between">
                        <a class="text-sm font-semibold text-foreground filter_by" search-type="<?= lang('partially_paid') ?>" id="partially_paid" href="#"><?= lang('partially_paid') ?></a>
                        <span class="text-xs text-muted-foreground"><?= $partially_paid ?> / <?= $invoice_total_count ?></span>
                    </div>
                    <div class="mt-3 h-2 rounded-full bg-slate-100">
                        <div class="h-2 rounded-full bg-indigo-500" data-toggle="tooltip"
                             data-original-title="<?= round(($partially_paid / $invoice_total_count) * 100) ?>%"
                             style="width: <?= ($partially_paid / $invoice_total_count) * 100 ?>%"></div>
                    </div>
                </div>

                <div class="rounded-2xl border border-border bg-card p-4 shadow-sm">
                    <div class="flex items-center justify-between">
                        <a class="text-sm font-semibold text-foreground filter_by" search-type="<?= lang('overdue') ?>" id="overdue" href="#"><?= lang('overdue') ?></a>
                        <span class="text-xs text-muted-foreground"><?= $overdue ?> / <?= $invoice_total_count ?></span>
                    </div>
                    <div class="mt-3 h-2 rounded-full bg-slate-100">
                        <div class="h-2 rounded-full bg-amber-500" data-toggle="tooltip"
                             data-original-title="<?= round(($overdue / $invoice_total_count) * 100) ?>%"
                             style="width: <?= round(($overdue / $invoice_total_count) * 100) ?>%"></div>
                    </div>
                </div>
            </div>
        <?php } ?>

        <?php
        $invoice_status_filters = array(
            '' => 'all',
            'not_paid' => 'unpaid',
            'paid' => 'paid',
            'partially_paid' => 'partially_paid',
            'overdue' => 'overdue',
            'cancelled' => 'cancelled',
            'recurring' => 'recurring',
        );
        ?>
        <div class="rounded-2xl border border-border bg-card shadow-sm">
            <div class="flex flex-wrap items-center gap-2 border-b border-border py-3 px-4">
                <?php foreach ($invoice_status_filters as $filter_key => $filter_label) { ?>
                    <button type="button"
                            class="invoice-status-filter rounded-full border border-border px-3 py-1.5 text-xs font-semibold text-foreground hover:border-primary <?= $filter_key === '' ? 'bg-primary text-white border-primary' : ''; ?>"
                            data-client-invoice-filter-action="1"
                            data-client-invoice-filter="<?= $filter_key ?>"
                            data-client-invoice-filter-label="<?= html_escape(lang($filter_label)); ?>">
                        <?= lang($filter_label); ?>
                    </button>
                <?php } ?>
            </div>

            <div class="p-4">
                <table class="min-w-full text-sm DataTables" id="DataTables" cellspacing="0" width="100%">
                    <thead class="bg-slate-50 text-slate-500 dark:bg-slate-800 dark:text-slate-300">
                    <tr>
                        <th class="px-4 py-3 text-left"><?= lang('invoice') ?></th>
                        <th class="col-date px-4 py-3 text-left"><?= lang('due_date') ?></th>
                        <th class="col-currency px-4 py-3 text-left"><?= lang('amount') ?></th>
                        <th class="col-currency px-4 py-3 text-left"><?= lang('due_amount') ?></th>
                        <th class="px-4 py-3 text-left"><?= lang('status') ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    list = base_url + "client/invoice/invoiceList";

    (function () {
        function invoiceFilterUrl(filterBy) {
            return base_url + "client/invoice/invoiceList" + (filterBy ? "/" + encodeURIComponent(filterBy) : "");
        }

        function reloadClientInvoiceTable(filterBy) {
            var url = invoiceFilterUrl(filterBy || "");
            list = url;
            if (typeof fire_datatable === "function") {
                fire_datatable(url, "DataTables");
            } else if (typeof table_url === "function") {
                table_url(url);
            }
        }

        function setHeaderFilterActive(filterBy, label) {
            document.querySelectorAll('.invoice-status-filter').forEach(function (item) {
                var isActive = (item.getAttribute('data-client-invoice-filter') || '') === (filterBy || '');
                item.classList.toggle('bg-primary', isActive);
                item.classList.toggle('text-white', isActive);
                item.classList.toggle('border-primary', isActive);
            });

            var dropdown = document.getElementById('client-invoice-header-filter');
            if (!dropdown) {
                return;
            }
            dropdown.querySelectorAll('[data-header-filter-item]').forEach(function (item) {
                item.classList.remove('bg-indigo-50', 'text-indigo-700', 'dark:bg-indigo-900/30', 'dark:text-indigo-300');
                item.classList.add('text-slate-700', 'hover:bg-slate-50', 'dark:text-slate-200', 'dark:hover:bg-slate-800');
                if ((item.getAttribute('data-client-invoice-filter') || '') === (filterBy || '')) {
                    item.classList.add('bg-indigo-50', 'text-indigo-700', 'dark:bg-indigo-900/30', 'dark:text-indigo-300');
                    item.classList.remove('text-slate-700', 'hover:bg-slate-50', 'dark:text-slate-200', 'dark:hover:bg-slate-800');
                }
            });
            var selected = dropdown.querySelector('[data-header-filter-selected]');
            if (selected) {
                selected.textContent = label || '<?= html_escape(lang('all')); ?>';
            }
            dropdown.open = false;
        }

        document.addEventListener('click', function (event) {
            var headerItem = event.target.closest('[data-client-invoice-filter-action]');
            if (headerItem) {
                event.preventDefault();
                var filterBy = headerItem.getAttribute('data-client-invoice-filter') || '';
                var label = headerItem.getAttribute('data-client-invoice-filter-label') || '<?= html_escape(lang('all')); ?>';
                setHeaderFilterActive(filterBy, label);
                document.querySelectorAll('.filter_by').forEach(function (item) {
                    item.classList.toggle('active', (item.getAttribute('id') || '') === filterBy);
                });
                reloadClientInvoiceTable(filterBy);
                return;
            }

            var cardLink = event.target.closest('.filter_by');
            if (!cardLink) {
                return;
            }
            event.preventDefault();
            var cardFilter = cardLink.getAttribute('id') || '';
            var cardLabel = cardLink.getAttribute('search-type') || cardLink.textContent.trim() || '<?= html_escape(lang('all')); ?>';
            document.querySelectorAll('.filter_by').forEach(function (item) {
                item.classList.remove('active');
            });
            cardLink.classList.add('active');
            setHeaderFilterActive(cardFilter, cardLabel);
            reloadClientInvoiceTable(cardFilter);
        });
    })();
</script>
