@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 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");
}

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

<form hx-get="@(baseUrl)"
    hx-trigger="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-target="[data-swift-order-list]"
    hx-select="[data-swift-order-list]"
    hx-replace-url="true"
    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">
                <span class="input-group-text border-end-0 bg-body">
                    <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 type="search" class="form-control border-start-0 border-end-0" name="FilterText" value="@Dynamicweb.Context.Current?.Request.QueryString.Get("FilterText")" placeholder="@Translate("Search orders")...">
                <button type="reset" class="input-group-text border-start-0 bg-body" onclick="this.closest('form').querySelector('[name=FilterText]').value = ''; this.closest('form').dispatchEvent(new Event('change', { bubbles: true }))">
                    <span class="icon-2">@ReadFile("/Files/Images/Icons/xmark.svg")</span>
                    <span class="visually-hidden">@Translate("Clear search")</span>
                </button>
            </div>
        </div>
        <div class="dropdown hstack">
            <button class="btn btn-sm btn-outline-secondary hstack gap-2 ms-auto py-2 px-3 text-body" data-dw-button type="button" data-bs-toggle="dropdown" aria-expanded="false">
                <span class="icon-2">
                    @ReadFile("/Files/Images/Icons/filter.svg")
                </span>
                @Translate("Filter")
            </button>
            <div class="dropdown-menu p-3">
                <div class="fw-bold mb-1">@Translate("Status")</div>
                <div class="d-flex flex-wrap gap-2" role="group" aria-label="@Translate("Filter by status")">
                    <input class="btn-check" type="radio" name="FilterOrderStateId" value="" id="state_all" autocomplete="off" checked="@((Dynamicweb.Context.Current?.Request.QueryString.Get("FilterOrderStateId") ?? string.Empty) == string.Empty)">
                    <label for="state_all" class="fs-8 py-1 px-2 btn btn-outline-secondary text-body lh-1" data-dw-button>@Translate("All")</label>
                    @if(Model.TryGetOrderStates(out var orderStates) is true)
                    {
                        foreach (var state in orderStates)
                        {
                            var isChecked = (Dynamicweb.Context.Current?.Request.QueryString.Get("FilterOrderStateId")) == state.Id;
                            <input class="btn-check" type="radio" name="FilterOrderStateId" value="@(state.Id)" id="state_@(state.Id)" autocomplete="off" checked="@isChecked">
                            <label for="state_@(state.Id)" class="fs-8 py-1 px-2 btn btn-outline-secondary text-body lh-1" data-dw-button>@(state.Name)</label>
                        }
                    }
                </div>
            </div>
        </div>
    </nav>

    <div data-swift-order-list>
        <input type="hidden" name="SortOrder" value="@(currentSortOrder)">
        
        <div class="card overflow-hidden">            
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Id" class="visually-hidden" checked="@(currentSortBy=="Id")" />
                                    @Translate("Order 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="CustomerName" class="visually-hidden" checked="@(currentSortBy=="CustomerName")" />
                                    @Translate("Customer") 
                                    @if(currentSortBy=="CustomerName") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="CompletedDate" class="visually-hidden" checked="@(currentSortBy=="CompletedDate")" />
                                    @Translate("Placed") 
                                    @if(currentSortBy=="CompletedDate") {
                                        <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>@Translate("Qty")</th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="PriceBeforeFees" class="visually-hidden" checked="@(currentSortBy=="PriceBeforeFees")" />
                                    @Translate("Total") 
                                    @if(currentSortBy=="PriceBeforeFees") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Actions")</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ( var order in Model.Orders )
                        {
                            var orderlines = order.OrderLines.Where(x => x.OrderLineType != OrderLineType.ProductDiscount && (!string.IsNullOrEmpty(x.ProductId) || !string.IsNullOrEmpty(x.ProductNumber)));

                            <tr class="position-relative">
                                <td>
                                    <a class="position-relative z-2 text-decoration-none text-decoration-underline-hover" href="@(baseUrl)?OrderId=@(order.Id)">@(order.Id)</a>
                                </td>
                                <td>@(order.CustomerName)</td>
                                <td>
                                    <div class="vstack">
                                        @(order.CompletedDate?.ToShortDateString())
                                        <span class="fs-8 text-muted">@(order.CompletedDate?.ToShortTimeString())</span>
                                    </div>
                                </td>
                                <td>
                                    @if (order.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>@(order.SumProductQuantities())</td>
                                <td>
                                    <div class="text-price">@(order.Price.PriceFormatted)</div>
                                </td>
                                <td>
                                    <div class="hstack gap-3">
                                        <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" href="@(baseUrl)?OrderId=@(order.Id)">
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/eye.svg")
                                                    </span>
                                                    @Translate("View")
                                                </a>
                                            </li>
                                        </ul>
                                        <button type="button" class="btn btn-icon stretched-link ms-auto" data-dw-button data-bs-toggle="collapse"  data-bs-target="#order_@(order.Id)" aria-expanded="false" aria-controls="order_@(order.Id)">
                                            <span class="icon">
                                                @ReadFile("/Files/Images/Icons/chevron-down.svg")
                                            </span>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <tr class="collapse" id="order_@(order.Id)">
                                <td colspan="10" class="text-muted fs-8">
                                    <div class="grid grid-3 gap-3">
                                        @* Customer *@
                                        <div class="vstack">
                                            <div class="fw-bold mb-0">@Translate("Billing")</div>
                                            <div>@(order.CustomerName)</div>
                                            <div>@(order.CustomerEmail)</div>
                                            <div>@(order.CustomerPhone)</div>
                                        </div>
                                        @* Shipping *@
                                        <div class="vstack">
                                            <div class="fw-bold mb-0">@Translate("Shipping")</div>
                                            <div>@(order.DeliveryCompany)</div>
                                            <div>@(order.DeliveryAddress)</div>
                                            <div>@(order.DeliveryAddress2)</div>
                                            <div>@(order.DeliveryZip) @(order.DeliveryCity)</div>
                                            <div>@(order.DeliveryCountry.ToUpperInvariant())</div>
                                        </div>
                                        @* Summary *@
                                        <div class="vstack">
                                            <div class="fw-bold mb-0">@Translate("Order summary")</div>
                                            <div class="hstack">
                                                <div>@Translate("Subtotal"):</div>
                                                <div class="text-price ms-auto">@(order.TotalPriceWithoutOrderDiscountsAndFeesAndTaxes.PriceFormatted)</div>
                                            </div>
                                            @if (order.ShippingFee.Price != 0.0) {
                                                <div class="hstack">
                                                    <div>@Translate("Shipping"):</div>
                                                    <div class="text-price ms-auto">@(order.ShippingFee.PriceFormatted)</div>
                                                </div>
                                            }
                                            @if (order.PaymentFee.Price != 0.0) {
                                                <div class="hstack">
                                                    <div>@Translate("Payment"):</div>
                                                    <div class="text-price ms-auto">@(order.PaymentFee.PriceFormatted)</div>
                                                </div>
                                            }
                                            @if (order.TotalTaxes.Price != 0.0) {
                                                <div class="hstack">
                                                    <div>@Translate("Taxes"):</div>
                                                    <div class="text-price ms-auto">@(order.TotalTaxes.PriceFormatted)</div>
                                                </div>
                                            }
                                            @if (order.Price.Vat != 0.0) {
                                                <div class="hstack">
                                                    <div>@Translate("VAT") @(order.Price.VATPercent)%:</div>
                                                    <div class="text-price ms-auto">@(order.Price.VatFormatted)</div>
                                                </div>
                                            }
                                            @if (order.TotalDiscount.Price != 0.0) {
                                                <div class="hstack">
                                                    <div>@Translate("Discount"):</div>
                                                    <div class="text-price ms-auto">@(order.TotalDiscount.PriceFormatted)</div>
                                                </div>
                                            }
                                            <div class="hstack align-items-start">
                                                <div>@Translate("Total"):</div>
                                                <div class="text-end ms-auto">
                                                    <div class="vstack">
                                                        <div class="text-price">@(order.Price.PriceFormatted)</div>
                                                        @if (order.Price.TryGetVatLabel(out string vatLabel)) {
                                                            <small class="opacity-85">@Translate(vatLabel)</small>
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        @* Orderlines *@
                                        <div style="grid-column:1/-1;">
                                            <div class="list-group gap-2">
                                                <div class="list-group-item d-grid gap-3 py-0 bg-transparent">
                                                    <div></div>
                                                    <div>@Translate("Items") (@(orderlines.Count()))</div>
                                                    <div class="text-center">@Translate("Unit")</div>
                                                    <div class="text-center">@Translate("Qty")</div>
                                                    <div class="text-end">@Translate("Price")</div>
                                                    <div class="text-end">@Translate("Total")</div>
                                                </div>
                                                @foreach( var orderline in orderlines.Reverse().Take(7) )
                                                {
                                                    <div class="list-group-item d-grid align-items-center gap-3">
                                                        @if(orderline.GetProduct()?.DefaultImage.TryGetImageFileViewModel(out var image) is true)
                                                        {
                                                            <div class="img-thumbnail">
                                                                <img src="@(image?.ToGetImage(new(){Height = 30, Width = 30, Ratio = "1/1", Crop = Dynamicweb.Imaging.ImageHandling.CropMode.KeepAspectRatio }))" alt="@(orderline.ProductName)">
                                                            </div>
                                                        }
                                                        else 
                                                        {
                                                            <div></div>
                                                        }
                                                        
                                                        <div class="vstack align-self-auto">
                                                            <div>@(orderline.ProductName)</div>
                                                            <div class="text-muted">
                                                                <span>@orderline.ProductNumber</span>
                                                                @if (!string.IsNullOrEmpty(orderline.ProductVariantName))
                                                                {
                                                                    <span>- @orderline.ProductVariantName</span>
                                                                }
                                                            </div>
                                                        </div>
                                                        <div class="vstack align-self-auto text-center">
                                                            <div>@(orderline.UnitName)</div>
                                                        </div>
                                                        <div class="vstack align-self-auto text-center">
                                                            <div>@(orderline.Quantity)</div>
                                                        </div>
                                                        <div class="vstack align-self-auto text-end">
                                                            @if(orderline.OrderLineType == OrderLineType.Discount)
                                                            {
                                                                <div class="text-price">@Translate("Free")</div>
                                                            }
                                                            else if(orderline.HasProductDiscount())
                                                            {
                                                                <div class="text-price text-decoration-line-through text-muted">@(orderline.UnitPrice.PriceFormatted)</div>
                                                                <div class="text-price">@(orderline.UnitPriceWithProductDiscount.PriceFormatted)</div>
                                                            }
                                                            else
                                                            {
                                                                <div class="text-price">@(orderline.UnitPrice.PriceFormatted)</div>
                                                            }
                                                        </div>
                                                        <div class="vstack align-self-auto text-end">
                                                            @if(orderline.HasProductDiscount())
                                                            {
                                                                <div class="text-price text-decoration-line-through text-muted">@(orderline.Price.PriceFormatted)</div>
                                                                <div class="text-price">@(orderline.TotalPriceWithProductDiscounts.PriceFormatted)</div>
                                                            }
                                                            else
                                                            {
                                                                <div class="text-price">@(orderline.Price.PriceFormatted)</div>
                                                            }
                                                        </div>
                                                    </div>
                                                }
                                                @if( orderlines.Count() > 7 )
                                                {
                                                    <div class="list-group-item hstack">
                                                        <a class="mx-auto" href="@(baseUrl)?OrderId=@(order.Id)">@Translate("View all orderlines") (@(orderlines.Count()))</a>
                                                    </div>
                                                }
                                                
                                            </div>
                                        
                                        </div>
                                    </td>
                                </tr>
                            }

                            @if( Model.Orders.Count() < 1 )
                            {
                                <tr class="position-relative">
                                    <td class="text-center py-5" colspan="8">
                                        <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 orders 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)">
                        <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)">
                        <span class="icon-2">
                            @ReadFile("/Files/Images/Icons/chevron-right.svg")
                        </span>
                    </button>
                </div>
            </div>
        }
    </div>
</form>