{include file="$template/includes/tablelist.tpl" tableName="InvoicesList" filterColumn="4"}
{assign var="paidInvoicesCount" value=0}
{assign var="unpaidInvoicesCount" value=0}
{assign var="overdueInvoicesCount" value=0}
{foreach $invoices as $invoice}
    {if $invoice.statusClass == 'paid'}
        {assign var="paidInvoicesCount" value=$paidInvoicesCount+1}
    {elseif $invoice.statusClass == 'unpaid'}
        {assign var="unpaidInvoicesCount" value=$unpaidInvoicesCount+1}
    {elseif $invoice.statusClass == 'overdue'}
        {assign var="overdueInvoicesCount" value=$overdueInvoicesCount+1}
    {/if}
{/foreach}

<script>
    jQuery(document).ready(function() {
        var table = jQuery('#tableInvoicesList').show().DataTable();
        var searchInput = jQuery('#invoicesPageSearch');
        var statusInput = jQuery('#invoicesPageStatus');
        var dashboardSearchInput = jQuery('#dashboardSearch');
        var sortButton = jQuery('[data-invoices-sort]');
        var exportButton = jQuery('[data-invoices-export]');
        var dueDateDescending = true;
        var dataTableState = table.state && typeof table.state === 'function' ? table.state() : null;

        function applyResponsiveInvoiceTitleWidths() {
            jQuery('#tableInvoicesList tbody tr.child span.dtr-title').each(function(index) {
                if (index === 0 || jQuery(this).text().trim() === '{lang key='invoicestitle'}') {
                    this.style.setProperty('display', 'inline-block', 'important');
                    this.style.setProperty('width', '180px', 'important');
                    this.style.setProperty('min-width', '180px', 'important');
                    this.style.setProperty('max-width', '180px', 'important');
                    this.style.setProperty('white-space', 'nowrap', 'important');
                }
            });
        }

        function escapeRegex(value) {
            return String(value || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }

        function applyInvoiceFilters() {
            var searchValue = jQuery.trim(searchInput.val() || '');
            var statusValue = jQuery.trim(statusInput.val() || '').toLowerCase();

            table.search(searchValue);

            if (statusValue) {
                table.column(4).search('^' + escapeRegex(statusValue) + '$', true, false, false);
            } else {
                table.column(4).search('');
            }

            table.draw();
        }

        {if $orderby == 'default'}
            table.order([2, 'desc'], [1, 'asc']);
        {elseif $orderby == 'invoicenum'}
            table.order(0, '{$sort}');
        {elseif $orderby == 'date'}
            table.order(1, '{$sort}');
        {elseif $orderby == 'duedate'}
            table.order(2, '{$sort}');
        {elseif $orderby == 'total'}
            table.order(3, '{$sort}');
        {elseif $orderby == 'status'}
            table.order(4, '{$sort}');
        {/if}

        if (dataTableState) {
            var rememberedGlobalSearch = jQuery.trim((dataTableState.search && dataTableState.search.search) || '');
            var rememberedStatusSearch = jQuery.trim((((dataTableState.columns || [])[4] || {}).search || {}).search || '');
            var normalizedRememberedStatus = rememberedStatusSearch
                .replace(/^\^/, '')
                .replace(/\$$/, '')
                .replace(/\\([\\^$.*+?()[\]{}|])/g, '$1');
            var shouldResetSavedFilters = !jQuery.trim(searchInput.val() || '')
                && !jQuery.trim(statusInput.val() || '')
                && !jQuery.trim(dashboardSearchInput.val() || '');

            if (shouldResetSavedFilters && (rememberedGlobalSearch || rememberedStatusSearch)) {
                table.search('');
                table.columns().search('');

                if (table.state && typeof table.state.clear === 'function') {
                    table.state.clear();
                }
            } else {
                if (rememberedGlobalSearch && !searchInput.val()) {
                    searchInput.val(rememberedGlobalSearch);
                }

                if (normalizedRememberedStatus && !statusInput.val()) {
                    statusInput.val(normalizedRememberedStatus);
                }
            }
        }

        applyInvoiceFilters();
        applyResponsiveInvoiceTitleWidths();
        jQuery('#tableLoading').hide();

        searchInput.on('input change', function() {
            applyInvoiceFilters();
        });

        statusInput.on('change', function() {
            applyInvoiceFilters();
        });

        sortButton.on('click', function() {
            dueDateDescending = !dueDateDescending;
            table.order(2, dueDateDescending ? 'desc' : 'asc').draw();
            sortButton.toggleClass('is-active', !dueDateDescending);
        });

        exportButton.on('click', function() {
            var rows = [];

            table.rows({ search: 'applied' }).every(function() {
                var row = jQuery(this.node());
                rows.push([
                    row.find('.dashboard-item-title').first().text().trim(),
                    row.find('td').eq(1).text().trim(),
                    row.find('td').eq(2).text().trim(),
                    row.find('.dashboard-table-money').first().text().trim(),
                    row.find('.status-pill').first().text().trim()
                ]);
            });

            if (!rows.length) {
                return;
            }

            var csv = [['{lang key='invoicestitle'}', '{lang key='invoicesdatecreated'}', '{lang key='invoicesdatedue'}', '{lang key='invoicestotal'}', '{lang key='invoicesstatus'}']].concat(rows).map(function(cols) {
                return cols.map(function(value) {
                    return '"' + String(value || '').replace(/"/g, '""') + '"';
                }).join(',');
            }).join('\n');

            var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            var link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'invoices-export.csv';
            link.click();

            setTimeout(function() {
                URL.revokeObjectURL(link.href);
            }, 1000);
        });

        table.on('draw.dt responsive-display responsive-resize', function() {
            applyResponsiveInvoiceTitleWidths();
        });
    });
</script>

<section class="dashboard-page-section">
    <section class="dashboard-analytics-grid dashboard-analytics-grid--three">
        <article class="dashboard-analytics-card dashboard-analytics-card--green dashboard-analytics-card--spark">
            <span class="dashboard-analytics-card__icon"><i class="fas fa-file-invoice-dollar"></i></span>
            <div class="dashboard-analytics-card__copy">
                <span class="dashboard-analytics-card__label">{lang key='invoices'}</span>
                <strong class="dashboard-analytics-card__value">{$invoices|@count}</strong>
                <span class="dashboard-analytics-card__meta">{lang key='invoices'}</span>
            </div>
            <span class="dashboard-analytics-card__line dashboard-analytics-card__line--green"></span>
        </article>
        <article class="dashboard-analytics-card dashboard-analytics-card--amber dashboard-analytics-card--spark">
            <span class="dashboard-analytics-card__icon"><i class="far fa-clock"></i></span>
            <div class="dashboard-analytics-card__copy">
                <span class="dashboard-analytics-card__label">{lang key='invoicesunpaid'}</span>
                <strong class="dashboard-analytics-card__value">{$unpaidInvoicesCount}</strong>
                <span class="dashboard-analytics-card__meta">{lang key='invoicesunpaid'}</span>
            </div>
            <span class="dashboard-analytics-card__line dashboard-analytics-card__line--amber"></span>
        </article>
        <article class="dashboard-analytics-card dashboard-analytics-card--mint dashboard-analytics-card--spark">
            <span class="dashboard-analytics-card__icon"><i class="fas fa-check-circle"></i></span>
            <div class="dashboard-analytics-card__copy">
                <span class="dashboard-analytics-card__label">{lang key='invoicespaid'}</span>
                <strong class="dashboard-analytics-card__value">{$paidInvoicesCount}</strong>
                <span class="dashboard-analytics-card__meta">{lang key='invoicespaid'}</span>
            </div>
            <span class="dashboard-analytics-card__line dashboard-analytics-card__line--mint"></span>
        </article>
    </section>

    <section class="dashboard-panel dashboard-page-table-panel">
        <div class="dashboard-page-heading dashboard-page-heading--inline">
            <div class="dashboard-page-heading__title">
                <span class="dashboard-page-heading__icon"><i class="fas fa-file-invoice"></i></span>
                <div>
                    <h1 class="dashboard-page-title">{lang key='invoices'}</h1>
                    <p class="dashboard-panel__copy">{$LANG.invoices}</p>
                </div>
            </div>
            <div class="dashboard-page-heading__actions dashboard-page-heading__actions--invoices">
                <a href="cart.php" class="dashboard-link dashboard-link--hero">
                    <i class="far fa-plus"></i>
                    {lang key='ordernowbutton'}
                </a>
                <a href="clientarea.php?action=addfunds" class="dashboard-action-ghost">
                    <i class="far fa-credit-card"></i>
                    {lang key='addfunds'}
                </a>
            </div>
        </div>

        <div class="dashboard-page-table-toolbar">
            <div class="dashboard-page-table-toolbar__actions dashboard-page-table-toolbar__actions--invoices">
                <div class="dashboard-toolbar-search">
                    <i class="far fa-search"></i>
                    <input type="search" id="invoicesPageSearch" class="form-control" placeholder="{lang key='search'}..." />
                </div>
                <div class="dashboard-select-wrap">
                    <i class="far fa-filter"></i>
                    <select id="invoicesPageStatus" class="form-control custom-select">
                        <option value="">{lang key='all'} {$LANG.invoicesstatus|default:'Statuses'}</option>
                        <option value="paid">{lang key='invoicespaid'}</option>
                        <option value="unpaid">{lang key='invoicesunpaid'}</option>
                        <option value="overdue">{lang key='clientHomePanels.overdueInvoices'}</option>
                        <option value="draft">{lang key='invoicesdraft'}</option>
                        <option value="refunded">{lang key='invoicesrefunded'}</option>
                        <option value="collections">{lang key='invoicescollections'}</option>
                        <option value="cancelled">{lang key='invoicescancelled'}</option>
                    </select>
                </div>
                <button type="button" class="dashboard-icon-btn" data-invoices-sort aria-label="{lang key='invoicesdatedue'}">
                    <i class="far fa-calendar"></i>
                </button>
                <button type="button" class="dashboard-icon-btn" data-invoices-export aria-label="{lang key='download'} {lang key='invoices'}">
                    <i class="far fa-download"></i>
                </button>
            </div>
        </div>

        <div class="table-container clearfix">
            <table id="tableInvoicesList" class="table dashboard-table dashboard-table--rich dashboard-data-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>{lang key='invoicesdatecreated'}</th>
                        <th>{lang key='invoicesdatedue'}</th>
                        <th>{lang key='invoicestotal'}</th>
                        <th>{lang key='invoicesstatus'}</th>
                        <th class="text-right">{lang key='actions'}</th>
                    </tr>
                </thead>
                <tbody>
                    {foreach $invoices as $invoice}
                        <tr onclick="clickableSafeRedirect(event, 'viewinvoice.php?id={$invoice.id}', false)">
                            <td>
                                <div class="dashboard-table-service dashboard-table-service--compact">
                                    <span class="dashboard-table-service__icon is-active">
                                        <i class="fas fa-file-alt"></i>
                                    </span>
                                    <div class="dashboard-table-service__copy">
                                        <strong class="dashboard-item-title">{$invoice.invoicenum}</strong>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="w-hidden">{$invoice.normalisedDateCreated}</span>
                                <div class="dashboard-table-inline">
                                    <i class="far fa-calendar"></i>
                                    <span>{$invoice.datecreated}</span>
                                </div>
                            </td>
                            <td>
                                <span class="w-hidden">{$invoice.normalisedDateDue}</span>
                                <div class="dashboard-table-inline">
                                    <i class="far fa-calendar"></i>
                                    <span>{$invoice.datedue}</span>
                                </div>
                            </td>
                            <td data-order="{$invoice.totalnum}">
                                <strong class="dashboard-table-money">{$invoice.total}</strong>
                            </td>
                            <td data-search="{$invoice.statusClass|lower}">
                                <span class="status-pill {if $invoice.statusClass == 'paid'}success{elseif $invoice.statusClass == 'unpaid'}warning{elseif $invoice.statusClass == 'overdue'}danger{else}muted{/if}">
                                    {$invoice.status}
                                </span>
                            </td>
                            <td class="text-right">
                                <div class="dashboard-row-actions">
                                    <a href="viewinvoice.php?id={$invoice.id}" class="dashboard-row-action stopEventBubble" aria-label="{lang key='view'} {lang key='invoices'}">
                                        <i class="far fa-eye"></i>
                                    </a>
                                    <a href="dl.php?type=i&amp;id={$invoice.id}" class="dashboard-row-action stopEventBubble" aria-label="{lang key='download'} {lang key='invoices'}">
                                        <i class="far fa-download"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    {/foreach}
                </tbody>
            </table>
            <div class="text-center" id="tableLoading">
                <p><i class="fas fa-spinner fa-spin"></i> {lang key='loading'}</p>
            </div>
        </div>
    </section>
</section>
