@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.PageViewModel>
@using Dynamicweb.Frontend
@using Dynamicweb.Core
@using Dynamicweb.Ecommerce.Frontend
@using Dynamicweb.Ecommerce.ProductCatalog
@using System.Globalization

@functions {
	string? DoubleToString(double? value)
	{
		if (value.HasValue)
		{
			return value.Value.ToString(CultureInfo.InvariantCulture);
		}
		return null;
	}
}

@{
	string iconPath = "/Files/Images/Icons/";
	bool anonymousUser = Pageview.User == null;
	var cartServicePageId = GetPageIdByNavigationTag("CartService");
	var cartSummaryPageId = GetPageIdByNavigationTag("CartSummary");
	var cartType = Dynamicweb.Context.Current?.Request["CartType"];
	var requestPageId = Dynamicweb.Context.Current?.Request["RequestPageID"];
	var orderContext = Dynamicweb.Context.Current?.Request["OrderContext"];
	string? orderContextQueryString = string.IsNullOrEmpty(orderContext) ? string.Empty : $"?OrderContext={orderContext}";
	string? cartUrl = Model.Item?.GetLink("CartPageLink")?.Url;
	string? checkoutUrl = Dynamicweb.Context.Current?.Request["checkoutUrl"];
	checkoutUrl = string.IsNullOrEmpty(checkoutUrl) ? (!anonymousUser ? Model.Item?.GetLink("CheckoutSignedInPageLink")?.Url : Model.Item?.GetLink("CheckoutAnonymousPageLink")?.Url) : checkoutUrl;
	string? quoteCheckoutPageId = Dynamicweb.Context.Current?.Request["quoteCheckoutPageLink"];
	quoteCheckoutPageId = string.IsNullOrEmpty(quoteCheckoutPageId) ? Model.Item?.GetLink("QuoteCheckoutPageLink")?.PageId.ToString() : quoteCheckoutPageId;
	var order = Dynamicweb.Ecommerce.Services.Orders.GetById(Model.Cart?.ID);
	bool isMiniCart = cartType == "minicart";
}

@if (isMiniCart)
{
	<div class="offcanvas-header sticky-top bg-body" style="box-shadow: 0 10px 10px -12px var(--bs-gray-300);">
		<h5 class="offcanvas-title">@Translate("Your cart")</h5>
		<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="@Translate("Close minicart")" id="CloseMiniCart"></button>
	</div>
}

<div class="item_@Model.Item?.SystemName.ToLower() @(isMiniCart ? "offcanvas-body h-100" : null)">
	@if (Model.Cart?.TotalProductsCount > 0)
	{
		if (!isMiniCart)
		{
			<button class="toggle-order-summary btn text-reset w-100 d-block d-lg-none px-0" type="button" data-bs-toggle="collapse" data-bs-target="#CartSummary" aria-expanded="false" aria-controls="CartSummary">
				<div class="d-flex align-items-center justify-content-between">
					<span class="d-flex align-items-center">
						<span class="fs-7 lh-1"><span class="toggle-order-summary-text"></span> @Translate("order summary")</span>
						<span class="icon-2 ms-2">
							@ReadFile(iconPath + "chevron-down.svg")
						</span>
					</span>
					<span class="fw-bold">
						<span class="text-price">@Model.Cart.TotalPrice.Price.Formatted</span>
					</span>
				</div>
			</button>

			<style>
				.toggle-order-summary .toggle-order-summary-text::after {
					content: "@Translate("Show")";
				}
				.toggle-order-summary[aria-expanded="true"] .toggle-order-summary-text::after {
					content: "@Translate("Hide")";
				}
				.toggle-order-summary[ aria-expanded="true" ] svg {
					transform: rotate(-180deg);
				}
			</style>
		}

		<div class="@(!isMiniCart ? "d-lg-block h-lg-auto collapse" : "d-flex flex-column h-100") pt-2 pt-lg-0" id="CartSummary">
			<div class="d-flex flex-column gap-4 pb-4">
				@foreach (var orderline in Model.Cart.CartOrderlines.Reverse())
				{
					var product = orderline?.GetProduct() ?? null;
					string? name = orderline?.ProductName;
					string image = product?.DefaultImage?.Value ?? string.Empty;
					string imagePath = $"/Admin/Public/GetImage.ashx?image={image}&width=80&height=80&crop=5&fillcanvas=true&Background=ffffff&format=webp";
					imagePath = !string.IsNullOrWhiteSpace(image) && !image.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? imagePath : image;
					string? priceTotalWithDiscounts = orderline?.TotalPriceWithProductDiscounts.Price.Formatted;
					string? priceBefore = orderline?.UnitPriceBeforeDiscount.Price.Formatted;
					string? unitPrice = orderline?.UnitPrice.Price.Formatted;
					string? discountPrice = orderline?.UnitPriceWithProductDiscount.Price.Formatted;
					string? discountTotal = orderline?.TotalDiscount.Price.Formatted;
					string? variantText = orderline?.ProductVariantText;
					string? unitName = orderline?.UnitName;
					var orderlineId = orderline?.ID;
					var quantity = Math.Round(orderline.Quantity, 2);
					double? stepQty = product?.PurchaseQuantityStep > 0 ? product.PurchaseQuantityStep : 1;
					double? minQty = product?.PurchaseMinimumQuantity > 0 ? product.PurchaseMinimumQuantity : 1;
					double? maxQty = null;				
					if (product?.ProductType == Dynamicweb.Ecommerce.Products.ProductType.Stock && !product.NeverOutOfstock)
					{
						maxQty = product.StockLevel;
					}
					string link = product?.GetProductLink(GetPageIdByNavigationTag("Shop"), false) ?? string.Empty;
					bool isProductIdOrNumber = !string.IsNullOrEmpty(orderline.ProductID) || !string.IsNullOrEmpty(orderline.ProductNumber);  //Live Cart orderlines may not return ProductId. Manually entered products may not have ProductNumber
					bool isProduct = orderline.IsProduct || (orderline.IsDiscount && isProductIdOrNumber);

					if (isProduct)
					{
						<article class="grid grid-12">

							<div class="g-col-2">
								<a href="@link" class="ratio ratio-1x1 d-block " title="@name" tabindex="-1">
									<img src="@imagePath" style="object-fit: contain;" alt="@name">
								</a>
							</div>

							<div class="g-col-6">

								<div class="d-flex flex-column gap-1">
									@* Title *@
									<h3 class="h6 fs-7 m-0">
										<a href="@link" class="text-decoration-none" title="@name" tabindex="-1">@name</a>
									</h3>

									@* Variants *@
									@if (!string.IsNullOrEmpty(variantText))
									{
										<p class="fs-8 m-0">@variantText</p>
									}

									@if (orderline.IsDiscount)
									{
										@* Free product notice *@
										<p class="fs-8 m-0">@Translate("Free product")</p>
									}
									else
									{
										@* Unit price *@
										<p class="fs-8 m-0">
											@if (!string.IsNullOrEmpty(unitName))
											{
												<span>@unitName: </span>
											}
											@if (discountPrice == unitPrice)

											{
												<span class="text-price">@unitPrice</span>	
											}
											else
											{
												<span class="text-price">@discountPrice</span>
												<span class="text-decoration-line-through">
													<span class="text-price">@unitPrice</span>
												</span>
											}
										</p>
									}

									@* Quantity *@
									@if (isMiniCart && !orderline.IsDiscount)
									{
										<form method="post" autocomplete="off" action="Default.aspx?ID=@cartServicePageId" data-response-target-element="CartSummary">
											<input type="hidden" name="requestPageId" value="@requestPageId">
											<input type="hidden" name="redirect" value="false">
											<input type="hidden" name="OrderContext" value="@orderContext">
											<input type="hidden" name="cartcmd" value="updateorderlines">
											<input type="hidden" name="checkoutUrl" value="@checkoutUrl">
											<input type="hidden" name="key" value="@orderline.ID">
											<input type="hidden" name="CartType" value="@cartType">
											<input type="submit" class="d-none" onclick="event.preventDefault();"> @* Fix for enterKey should not redirect *@

											@{
												var orderlineViewModel = new Dynamicweb.Ecommerce.Frontend.OrderLineViewModel(){
													Id = orderlineId,
													ProductId = orderline.ProductID,
													ProductVariantId = orderline.ProductVariantID,
													UnitId = orderline.UnitId,
													Quantity = quantity
												};

												@RenderPartial("Components/QuantitySelectorOrderline.cshtml", orderlineViewModel)
											}
											
										</form>
									}
									else {
										<span class="fs-8 d-block">@Translate("Qty"): @quantity</span>
									}

								</div>
							</div>

							<div class="g-col-4">

								<div class="d-flex flex-column gap-1 text-end h-100">

									@if (isMiniCart && !orderline.IsDiscount)
									{
										<form class="d-flex justify-content-end" action="/Default.aspx?ID=@cartServicePageId" method="post" data-layout-template="Swift-v2_CartSummary.cshtml" data-response-target-element=@(isMiniCart ? "DynamicOffcanvas" : "CartSummaryContainer") data-preloader="inline">
											<input type="hidden" name="requestPageId" value="@requestPageId">
											<input type="hidden" name="redirect" value="false">
											<input type="hidden" name="OrderContext" value="@orderContext">
											<input type="hidden" name="cartcmd" value="DelOrderLine">
											<input type="hidden" name="checkoutUrl" value="@checkoutUrl">
											<input type="hidden" name="key" value="@orderline.ID">
											<input type="hidden" name="CartType" value="@cartType">
											<button type="button" class="btn btn-link btn-sm lh-1 p-0 m-0 fs-8 opacity-50" onclick="swift.Cart.Update(this);">
												@Translate("Remove")
											</button>
										</form>
									}
									else if (!orderline.IsDiscount)
									{
										<form class="d-flex justify-content-end">
											<input type="hidden" name="requestPageId" value="@requestPageId">
											<input type="hidden" name="redirect" value="false">
											<input type="hidden" name="OrderContext" value="@orderContext">
											<input type="hidden" name="cartcmd" value="DelOrderLine">
											<input type="hidden" name="checkoutUrl" value="@checkoutUrl">
											<input type="hidden" name="key" value="@orderline.ID">
											<input type="hidden" name="CartType" value="@cartType">
											<button type="submit" class="btn btn-link btn-sm lh-1 p-0 m-0 fs-8 opacity-50">
												@Translate("Remove")
											</button>
										</form>
									}

									<div class="d-flex flex-column justify-content-end flex-fill">
										@* Total *@
										<span class="h6 d-block fs-7 m-0">
											<span class="text-price">@priceTotalWithDiscounts</span>
										</span>
										@if (orderline.TotalDiscount.Price.Value != 0)
										{
											<span class="d-block fs-8 opacity-50">
												<span class="text-price">@discountTotal</span>
											</span>
										}
									</div>

								</div>

							</div>

						</article>
					}
				}
			</div>

			<div class="d-flex justify-content-end pb-3">
				<a href="?cartcmd=emptycart" class="btn btn-link p-0 hstack gap-1">
					<span class="icon">@ReadFile(iconPath + "trash-can.svg")</span>
					<span>@Translate("Remove all")</span>
				</a>
			</div>

			@{
				var orderCurrency = Dynamicweb.Ecommerce.Common.Context.Currency;
				string totalPriceWithoutDiscountsFeesAndTaxes = Model.Cart.TotalPriceWithoutDiscountsFeesAndTaxes.Price.Formatted;
				double totalPriceWithoutOrderDiscountsAndFeesValue = Model.Cart.TotalPriceWithoutDiscountsFeesAndTaxes.Price.Value + Model.Cart.TotalDiscount.Price.Value;
				string totalPriceWithoutOrderDiscountsAndFees = Dynamicweb.Ecommerce.Services.Currencies.Format(orderCurrency, totalPriceWithoutOrderDiscountsAndFeesValue);
				bool showPricesWithVat = Dynamicweb.Ecommerce.Common.Context.DisplayPricesWithVat;
				bool renderVatMessage = (Model.Cart.TotalPrice?.PriceWithVat?.Value != Model.Cart.TotalPrice?.PriceWithoutVat?.Value) || Dynamicweb.Ecommerce.Common.Context.Country?.Vat != null;

				<div class="d-flex flex-column mt-auto gap-2 gap-lg-3 position-sticky bottom-0 bg-body" id="cartSummaryFooter" style="box-shadow: 0 -10px 10px -12px var(--bs-gray-300);">

					<div class="fs-8 border-top pt-2 pt-lg-3">
						@* Subtotal *@
						<div class="d-flex justify-content-between fw-bold">
							<span>@Translate("Subtotal")</span>
							<span class="text-end">
								<span class="d-block">
									@if (totalPriceWithoutDiscountsFeesAndTaxes != totalPriceWithoutOrderDiscountsAndFees)
									{
										<span class="text-price fw-normal text-decoration-line-through">@(totalPriceWithoutDiscountsFeesAndTaxes)</span>
									}
									<span class="text-price">@totalPriceWithoutOrderDiscountsAndFees</span>
								</span>
								
								@if (renderVatMessage  && !showPricesWithVat)
								{
									<span class="fs-8 fw-normal d-block">@Translate("Excl. VAT")</span>
								}
								else if (renderVatMessage)
								{
									<span class="fs-8 fw-normal d-block">@Translate("Incl. VAT")</span>
								}
							</span>
						</div>

						@* Discounts (only order discounts) *@
						@foreach (var orderline in Model.Cart.CartOrderlines)
						{
							bool isProductIdOrNumber = !string.IsNullOrEmpty(orderline.ProductID) || !string.IsNullOrEmpty(orderline.ProductNumber);  //Live Cart orderlines may not return ProductId. Manually entered products may not have ProductNumber
							var orderLineViewModel = Dynamicweb.Ecommerce.Services.OrderLines.GetById(orderline.ID);
							bool isDiscount = orderLineViewModel.OrderLineType == Dynamicweb.Ecommerce.Orders.OrderLineType.Discount;
							bool isOrderAmountDiscount = isDiscount && !isProductIdOrNumber;

							if (isOrderAmountDiscount)
							{
								<div class="d-flex justify-content-between"><span>@orderline.ProductName</span><span class="text-price">@orderline.TotalPriceWithProductDiscounts.Price.Formatted</span></div>
							}
						}

						@* Shipping *@
						@if (!string.IsNullOrEmpty(Model.Cart.ShippingMethod))
						{
							if (Model.Cart.ShippingFee.Price.Value != 0.0)
							{
								<div class="d-flex justify-content-between">
									<span>@Translate("Delivery")</span>
									<span>@Model.Cart.ShippingFee.Price.Formatted</span>
								</div>
							}
						}
						else
						{
							<div class="d-flex justify-content-between">
								<span>@Translate("Delivery")</span>
								<span>@Translate("Calculated in next step")</span>
							</div>
						}

						@* Payment *@
						@if (!string.IsNullOrEmpty(Model.Cart.PaymentMethod))
						{
							if (Model.Cart.PaymentFee.Price.Value != 0)
							{
								<div class="d-flex justify-content-between">
									<span>@Translate("Payment")</span>
									<span class="text-price">@Model.Cart.PaymentFee.Price.Formatted</span>
								</div>
							}
						}
						else
						{
							<div class="d-flex justify-content-between">
								<span>@Translate("Payment")</span>
								<span>@Translate("Calculated in next step")</span>
							</div>
						}

						@* Taxes *@
						@if (order is object)
						{
							if (order.TotalTax.Price != 0)
							{
								<div class="d-flex justify-content-between">
									<span>@Translate("Sales tax")</span>
									<span>@order.TotalTax.PriceFormatted</span>
								</div>
							}
						}
					</div>
					<div class="fs-8 border-top pt-2 pt-lg-3">
						<div class="d-flex justify-content-between fs-6 fw-bold">
							<span>@Translate("Total")</span>
							@if (renderVatMessage && !showPricesWithVat)
							{
								<span class="text-price text-end">
									<span class="fs-5 d-block">@Model.Cart.TotalPrice.Price.Formatted</span>
									<span class="fs-8 fw-normal d-block">@Translate("Excl. VAT")</span>
								</span>
							}
							else if (renderVatMessage)
							{
								<span class="text-price text-end">
									<span class="fs-5 d-block">@Model.Cart.TotalPrice.Price.Formatted</span>
									<span class="fs-8 fw-normal d-block">@Translate("Incl. VAT")</span>
								</span>
							}
							else
							{
								<span class="text-price fs-5">@Model.Cart.TotalPrice.Price.Formatted</span>
							}
						</div>

						@if (renderVatMessage)
						{
							<div class="d-flex justify-content-between"><span>@Translate("VAT")</span><span class="text-price">@Model.Cart.TotalPrice.Vat.Formatted</span></div>
							if (!showPricesWithVat)
							{
								<div class="d-flex justify-content-between"><span>@Translate("Total incl. VAT")</span><span class="text-price">@Model.Cart.TotalPrice.PriceWithVat.Formatted</span></div>
							}
						}

						@if (Model.Cart.TotalDiscount.Price.Value != 0)
						{
							<div class="d-flex justify-content-between"><span>@Translate("Discount")</span><span class="text-price">@Model.Cart.TotalDiscount.Price.Formatted</span></div>
						}
					</div>

					<div class="d-flex flex-column justify-content-end gap-3">

						@if (isMiniCart)
						{
							@*Close offcanvas button*@
							<button type="button" class="btn btn-link text-decoration-none order-last" data-dw-button="link" data-bs-dismiss="offcanvas" aria-label="Close" id="ContinueShopping">
								<div class="d-flex align-items-center justify-content-center position-relative">
									<span class="icon-2 me-1 position-absolute position-lg-static start-0">
										@ReadFile(iconPath + "chevron-left.svg")
									</span>
									<span>@Translate("Continue shopping")</span>
								</div>
							</button>

							if (!string.IsNullOrEmpty(cartUrl))
							{
								@*Cart button*@
								<a href="@(cartUrl)@(orderContextQueryString)" class="btn btn-secondary" data-dw-button="secondary" id="GoToCartButton">
									<div class="d-flex align-items-center justify-content-center position-relative">
										<span>@Translate("Cart")</span>
										<span class="icon-2 ms-1 position-absolute position-md-static end-0">
											@ReadFile(iconPath + "chevron-right.svg")
										</span>
									</div>
								</a>
							}
						}


						@*Checkout button*@
						<a href="@(checkoutUrl)@(orderContextQueryString)" class="btn btn-primary order-first" data-dw-button="primary" id="CartSummaryGoToCheckoutButton">
							<div class="d-flex align-items-center justify-content-center position-relative">
								<span>@Translate("Checkout")</span>
								<span class="icon-2 ms-1 position-absolute position-md-static end-0">
									@ReadFile(iconPath + "chevron-right.svg")
								</span>
							</div>
						</a>

						@*Quote Checkout button*@
						@if (!string.IsNullOrEmpty(quoteCheckoutPageId) && Converter.ToInt32(quoteCheckoutPageId) > 0 && !anonymousUser)
						{
							<a href="Default.aspx?ID=@(quoteCheckoutPageId)@(orderContextQueryString)" class="btn btn-secondary" data-dw-button="secondary" id="RequestQuoteButton">
								<div class="d-flex align-items-center justify-content-center position-relative">
									<span>@Translate("Request quote")</span>
									<span class="icon-2 ms-1 position-absolute position-lg-static end-0">
										@ReadFile(iconPath + "chevron-right.svg")
									</span>
								</div>
							</a>
						}
					</div>
				</div>
			}
		</div>
	}
	else
	{
		if (!isMiniCart)
		{
			<button class="toggle-order-summary btn text-reset w-100 d-block d-lg-none px-0" type="button" data-bs-toggle="collapse" data-bs-target="#CartSummary" aria-expanded="false" aria-controls="CartSummary">
				<div class="d-flex align-items-center justify-content-between">
					<span class="d-flex align-items-center">
						<span class="fs-7 lh-1"><span class="toggle-order-summary-text"></span> @Translate("order summary")</span>
					</span>
					<span class="icon-2 ms-2">
						@ReadFile(iconPath + "chevron-down.svg")
					</span>
				</div>
			</button>

			<style>
				.toggle-order-summary .toggle-order-summary-text::after {
					content: "@Translate("Show")";
				}
				.toggle-order-summary[aria-expanded="true"] .toggle-order-summary-text::after {
					content: "@Translate("Hide")";
				}
				.toggle-order-summary[ aria-expanded="true" ] svg {
					transform: rotate(-180deg);
				}
			</style>
		}

		<div class="d-lg-block h-lg-auto @(!isMiniCart ? "collapse" : null)" id="CartSummary">
			<div class="d-flex flex-column align-items-center justify-content-center min-vh-50 text-center opacity-50">
				<span class="icon-5">
					@ReadFile(iconPath + "cart-shopping.svg")
				</span>
				<span>@Translate("Your shopping cart is empty")</span>
				<span>@Translate("Add products to see cart summary")</span>
			</div>
		</div>
	}
</div>
