@inherits ViewModelTemplate<OrderListViewModel>
@using Dynamicweb.Frontend
@using Dynamicweb.Rendering
@using Dynamicweb.Ecommerce.Frontend
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Ecommerce.Orders

@{
    string baseUrl = SearchEngineFriendlyURLs.GetFriendlyUrl($"default.aspx?ID={Pageview.Page.ID}");
    string pageSize = Dynamicweb.Context.Current?.Request.QueryString.Get("PageSize") ?? Pageview.CurrentParagraph?.ModuleProperties?.GetValue("PageSize") ?? string.Empty;
    string currentSortBy = Dynamicweb.Context.Current?.Request.QueryString.Get("SortBy") ?? Pageview.CurrentParagraph?.ModuleProperties?.GetValue("SortByField") ?? string.Empty;
    string currentSortOrder = Dynamicweb.Context.Current?.Request.QueryString.Get("SortOrder") ?? Pageview.CurrentParagraph?.ModuleProperties?.GetValue("SortOrder") ?? string.Empty;
    string nextSortOrder = currentSortOrder == "asc" ? "desc" : "asc";
    string arrow = currentSortOrder == "asc" ? @ReadFile("/Files/Images/Icons/arrow-up.svg") : @ReadFile("/Files/Images/Icons/arrow-down.svg");

    string statusFilter = Dynamicweb.Context.Current?.Request.QueryString.Get("Status") ?? string.Empty;
    string clientFilter = Dynamicweb.Context.Current?.Request.QueryString.Get("Client") ?? string.Empty;
    string dueDateFrom = Dynamicweb.Context.Current?.Request.QueryString.Get("DueDateFrom") ?? string.Empty;
    string dueDateTo = Dynamicweb.Context.Current?.Request.QueryString.Get("DueDateTo") ?? string.Empty;
    string minAmountStr = Dynamicweb.Context.Current?.Request.QueryString.Get("MinAmount") ?? string.Empty;
    string maxAmountStr = Dynamicweb.Context.Current?.Request.QueryString.Get("MaxAmount") ?? string.Empty;

    string invoiceIdsString = Dynamicweb.Context.Current?.Request.QueryString.Get("Ids") ?? string.Empty;
    string[] invoiceIds = invoiceIdsString.Split(',');

    string currentPageNum = Dynamicweb.Context.Current?.Request.QueryString.Get("PageNum") ?? (Model.CurrentPage > 1 ? Model.CurrentPage.ToString() : string.Empty);

    DateTime? dueDateFromDate = DateTime.TryParse(dueDateFrom, out var tempFromDate) ? tempFromDate : null;
    DateTime? dueDateToDate = DateTime.TryParse(dueDateTo, out var tempToDate) ? tempToDate : null;
    double? minAmount = double.TryParse(minAmountStr, out var min) ? min : null;
    double? maxAmount = double.TryParse(maxAmountStr, out var max) ? max : null;

    var remainingTotal = Model.Orders
        .Where(order => invoiceIds.Contains(order.Id))
        .Select(order => order.TryGetLedger(out var entry) ? entry?.RemainingBalance.PriceWithoutVat ?? 0 : 0)
        .Sum();
}

<header class="hstack justify-content-between gap-3 mb-4">
    <div>
        <h1 class="h4 mb-0">@(Pageview.Page.GetDisplayName())</h1>
    </div>

    <div class="text-end" data-swift-invoice-list-total hx-swap-oob="true outerHTML:[data-swift-invoice-list-total]">
        @if (!string.IsNullOrEmpty(invoiceIdsString)) {            
            <h2 class="h6 mb-0 fw-bold">@Translate("Selected total"): <span>@Dynamicweb.Ecommerce.Services.Currencies.Format(Dynamicweb.Ecommerce.Common.Context.Currency, remainingTotal)</span></h2>
        }
    </div>
</header>

<form hx-get="@(baseUrl)"
    hx-trigger="change delay:100ms,
                submit,
                input from:input[name='FilterText'] changed delay:500ms queue:last, 
                click from:button[type='reset'], 
                change from:input[name='FilterOrderStateId'], 
                change from:input[name='SortBy']"
    hx-sync="this:abort"
    hx-swap="outerHTML"
    hx-disinherit="*"
    hx-target="[data-swift-invoice-list]"
    hx-select="[data-swift-invoice-list]"
    hx-replace-url="true"
    hx-include="[name='Ids']:checked"
    hx-on:click="const sortInput = event.target.closest('label')?.querySelector('input[name=SortBy]');
                 if (!sortInput) return;
                 const sortOrderField = this.querySelector('[name=SortOrder]');
                 if (!sortOrderField) return;
                 if (sortInput.checked) {
                     sortOrderField.value = sortOrderField.value === 'asc' ? 'desc' : 'asc';
                     this.requestSubmit();
                 } else {
                     sortOrderField.value = 'asc';
                 }">

    <nav class="hstack gap-2 mb-3">
        <div class="flex-fill">
            <div class="input-group" x-data="{ searchQuery: '' }" x-init="searchQuery = $refs.searchInput.value">
                <span class="input-group-text px-3 border-0 bg-transparent position-absolute top-0 bottom-0 start-0 z-2">
                    <span class="htmx-indicator spinner-border spinner-border-sm" aria-hidden="true"></span>
                    <span class="icon-2" data-swift-indicator-origin>@ReadFile("/Files/Images/Icons/magnifying-glass.svg")</span>
                </span>
                <input class="form-control rounded z-1 ps-5"
                    type="search"
                    placeholder="@Translate("Search invoices or PO numbers")"
                    autocomplete="off"
                    maxlength="255"
                    name="FilterText" 
                    value="@Dynamicweb.Context.Current?.Request.QueryString.Get("FilterText")"
                    aria-label="@Translate("Search invoices or PO numbers")"
                    onkeyup="this.closest('form').querySelectorAll('input[name=Ids]').forEach(checkbox => checkbox.checked = false);"
                    x-ref="searchInput"
                    x-model="searchQuery"
                >
                <button x-show="searchQuery.length > 0" @@click.prevent="searchQuery = ''" type="reset" class="btn btn-link btn-sm px-3 position-absolute top-0 bottom-0 end-0 z-2" aria-label="@Translate("Clear search")">
                    <span>@Translate("Clear")</span>
                </button>
            </div>
        </div>
    </nav>

    <div data-swift-invoice-list>
        <input type="hidden" name="SortOrder" value="@(currentSortOrder)">
        @if (!string.IsNullOrEmpty(currentPageNum))
        {
            <input type="hidden" name="PageNum" value="@(currentPageNum)">
        }

        @if (!string.IsNullOrEmpty(invoiceIdsString)) {
            <div class="card mb-3">
                <div class="card-body p-3">
                    <div class="hstack gap-2 justify-content-between">
                        <div>@(invoiceIds.Count()) @Translate(invoiceIds.Count() > 1 ? "Invoices selected" : "Invoice selected")</div>
                        <button type="button" class="btn btn-sm btn-primary hstack gap-2" data-dw-button
                            hx-trigger="click"
                            hx-get="@(baseUrl)"
                            hx-include="[name=Ids]:checked"
                            hx-vals='{"LayoutTemplate": "/Designs/Swift-v2/eCom/CustomerExperienceCenter/Orders/Modals/ContinueToPaymentModal.cshtml"}'
                            hx-target="main"
                            hx-swap="beforeend"
                        >
                            <span class="icon-2">
                                @ReadFile("/Files/Images/Icons/credit-card.svg")
                            </span>
                            @Translate("Continue to payment")
                        </button>
                    </div>
                </div>
            </div>
        }
        
        <div class="card overflow-hidden">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>&nbsp;</th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Id" class="visually-hidden" checked="@(currentSortBy=="Id")" />
                                    @Translate("Invoice number") 
                                    @if(currentSortBy=="Id") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="PurchaseOrderNumber" class="visually-hidden" checked="@(currentSortBy=="PurchaseOrderNumber")" />
                                    @Translate("PO number") 
                                    @if(currentSortBy=="PurchaseOrderNumber") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="StateId" class="visually-hidden" checked="@(currentSortBy=="StateId")" />
                                    @Translate("Status") 
                                    @if(currentSortBy=="StateId") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="PriceBeforeFees" class="visually-hidden" checked="@(currentSortBy=="PriceBeforeFees")" />
                                    @Translate("Amount") 
                                    @if(currentSortBy=="PriceBeforeFees") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="TotalDiscount" class="visually-hidden" checked="@(currentSortBy=="TotalDiscount")" />
                                    @Translate("Discount") 
                                    @if(currentSortBy=="TotalDiscount") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Paid")</th>
                            <th>@Translate("Balance")</th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="DueDate" class="visually-hidden" checked="@(currentSortBy=="DueDate")" />
                                    @Translate("Due date") 
                                    @if(currentSortBy=="DueDate") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Actions")</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ( var invoice in Model.Orders )
                        {
                            string invoiceReference = !string.IsNullOrEmpty(invoice.Reference) ? invoice.Reference : invoice.Id;
                            var ledger = invoice.GetLedger();

                            <tr class="position-relative">
                                <td>
                                    <label class="form-check-label position-relative z-2 p-2" role="button">
                                        <input type="checkbox" class="form-check-input" name="Ids" value="@(invoice.Id)" role="button" checked="@(invoiceIds.Contains(invoice.Id))">
                                    </label>
                                </td>
                                <td>
                                    <a class="stretched-link text-decoration-none text-decoration-underline-hover" href="@(baseUrl)?OrderId=@(invoice.Id)">@(invoiceReference)</a>
                                </td>
                                <td>@(invoice.PurchaseOrderNumber)</td>
                                <td>
                                    @if (invoice.TryGetOrderState(out var state))
                                    {
                                        <span class="badge lh-sm badge-neutral-light" style="@(state.StateColor is not null ? $"background-color: color-mix(in srgb, {state.StateColor?.Hex} 20%, transparent) !important; color: {state.StateColor?.Hex} !important" : null)">
                                            @(state.Name)
                                        </span>
                                    }
                                </td>
                                <td>@(invoice.TotalPriceWithoutOrderDiscountsAndFeesAndTaxes.PriceFormatted)</td>
                                <td>@(invoice.TotalOrderDiscount.PriceFormatted)</td>
                                <td>@(ledger?.TotalPaid.PriceWithoutVatFormatted)</td>
                                <td>@(ledger?.RemainingBalance.PriceWithoutVatFormatted)</td>
                                <td>@(invoice.DueDate?.ToShortDateString() ?? "")</td>
                                <td>
                                    <button class="btn btn-icon position-relative z-2" data-dw-button type="button" data-bs-toggle="dropdown" aria-expanded="false" data-bs-popper-config='{"strategy":"fixed", "placement":"bottom-end"}'>
                                        <span class="icon-2">
                                            @ReadFile("/Files/Images/Icons/ellipsis.svg")
                                        </span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a class="dropdown-item hstack gap-2 ps-2 pe-3 rounded-1" href="@(baseUrl)?OrderId=@(invoice.Id)">
                                                <span class="icon-2">
                                                    @ReadFile("/Files/Images/Icons/eye.svg")
                                                </span>
                                                @Translate("View")
                                            </a>
                                        </li>
                                    </ul>
                                </td>
                            </tr>
                        }

                        @if( Model.Orders.Count() < 1 )
                        {
                            <tr class="position-relative">
                                <td class="text-center py-5" colspan="10">
                                    <div data-swift-empty-state>
                                        <div data-swift-empty-state-icon>
                                            <span class="icon">
                                                @ReadFile("/Files/Images/Icons/file-contract.svg")
                                            </span>
                                        </div>
                                        <div>@Translate("No invoices found")</div>
                                    </div>
                                </td>
                            </tr>
                        }

                    </tbody>

                </table>

            </div>
        </div>

        @if (Model.PageCount > 1)
        {
            <div class="hstack justify-content-between mt-3">
                <div class="text-muted fs-7">
                    @Translate("Showing page") @(Model.CurrentPage) @Translate("of") @(Model.PageCount)
                </div>

                <div class="hstack gap-2">
                    <button type="submit" class="btn btn-outline-secondary text-body hstack p-2" name="PageNum" value="@(Model.CurrentPage - 1)" data-dw-button disabled="@(Model.CurrentPage == 1)" onclick="this.closest('form').querySelectorAll('input[name=Ids]').forEach(checkbox => checkbox.checked = false);">
                        <span class="icon-2">
                            @ReadFile("/Files/Images/Icons/chevron-left.svg")
                        </span>
                    </button>
                    <button type="submit" class="btn btn-outline-secondary text-body hstack p-2" name="PageNum" value="@(Model.CurrentPage + 1)" data-dw-button disabled="@(Model.CurrentPage == Model.PageCount)" onclick="this.closest('form').querySelectorAll('input[name=Ids]').forEach(checkbox => checkbox.checked = false);">
                        <span class="icon-2">
                            @ReadFile("/Files/Images/Icons/chevron-right.svg")
                        </span>
                    </button>
                </div>
            </div>
        }
    </div>
</form>