@inherits Dynamicweb.Rendering.RazorTemplateBase<Dynamicweb.Rendering.RazorTemplateModel<Dynamicweb.Rendering.Template>>
@using Dynamicweb.Frontend
@using Dynamicweb.Rendering
@using System.Globalization
@using System

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

@{
	var orderlines = GetLoop("OrderLines");
}

@for (int i = orderlines.Count - 1; i >= 0; i--)
{
	var orderline = orderlines[i];
	bool neverOutOfStock = orderline.GetBoolean("Ecom:Product.NeverOutOfStock");
	string name = orderline.GetString("Ecom:Order:OrderLine.ProductName");
	string number = orderline.GetString("Ecom:Order:OrderLine.ProductNumber");
	string primaryImage = orderline.GetString("Ecom:Product.PrimaryImage");
    string image = $"/Admin/Public/GetImage.ashx?width=180&height=180&image={primaryImage}&format=webp";
	string removeFromBasketLink = orderline.GetString("Ecom:Order:OrderLine.DeleteLink");
	string priceTotalWithDiscounts = orderline.GetString("Ecom:Order:OrderLine.TotalPriceWithProductDiscounts.PriceFormatted");
	string priceTotalWithDiscountsClean = orderline.GetString("Ecom:Order:OrderLine.TotalPriceWithProductDiscounts.Price");
	string unitPrice = orderline.GetString("Ecom:Order:OrderLine.UnitPrice.PriceFormatted");
	string unitPriceWithDiscount = orderline.GetDouble("Ecom:Order:OrderLine.UnitPriceWithProductDiscount.Price.Value").ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
	string discountAmount = Math.Abs(orderline.GetDouble("Ecom:Order:OrderLine.UnitDiscount.Price.Value")).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
	string unitPriceCurrency = orderline.GetString("Ecom:Order:OrderLine.Price.CurrencyCode");
	string discountPrice = orderline.GetString("Ecom:Order:OrderLine.UnitPriceWithProductDiscount.PriceFormatted");
	string discountTotal = orderline.GetString("Ecom:Order:OrderLine.TotalDiscount.PriceFormatted");
	string variantText = orderline.GetString("Ecom:Order:OrderLine.ProductVariantText");
	var orderlineId = orderline.GetValue("Ecom:Order:OrderLine.Id");
	double? stepQty = orderline.GetDouble("Ecom:Product.PurchaseQuantityStep") > 0 ? orderline.GetDouble("Ecom:Product.PurchaseQuantityStep") : 1;
	var quantity = orderline.GetDouble("Ecom:Order:OrderLine.Quantity");
	var unitName = orderline.GetString("Ecom:Order:OrderLine.UnitName");
	string primaryGroupId = orderline.GetString("Ecom:Order:OrderLine.PrimaryOrDefaultGroupId");
	string productId = orderline.GetString("Ecom:Order:OrderLine.ProductID");
	string variantId = orderline.GetString("Ecom:Order:OrderLine.ProductVariantID");
	string unitId = orderline.GetString("Ecom:Order:OrderLine.UnitID");
	string productType = orderline.GetString("Ecom.Product.Type");
	double? stockQuantity = orderline.GetDouble("Ecom:Product.Stock");
	double? minQty = orderline.GetDouble("Ecom:Product.PurchaseMinimumQuantity") > 0 ? orderline.GetDouble("Ecom:Product.PurchaseMinimumQuantity") : 1;
	bool isStockType = orderline.GetInteger("Ecom.Product.Type") == 0;
	bool setMaxQty = isStockType && !neverOutOfStock;
	double? maxQty = setMaxQty ? stockQuantity : null;

	string link = "Default.aspx?ID=" + GetPageIdByNavigationTag("Shop");
	link += $"&GroupID={System.Net.WebUtility.UrlEncode(primaryGroupId)}";
	link += $"&ProductID={System.Net.WebUtility.UrlEncode(productId)}";
	link += !string.IsNullOrEmpty(variantId) ? $"&VariantID={System.Net.WebUtility.UrlEncode(variantId)}" : "";

	bool isProductIdOrNumber = !string.IsNullOrEmpty(orderline.GetString("Ecom:Order:OrderLine.ProductID")) || !string.IsNullOrEmpty(orderline.GetString("Ecom:Order:OrderLine.ProductNumber"));  //Live Cart orderlines may not return ProductId. Manually entered products may not have ProductNumber
	bool isProduct = orderline.GetBoolean("Ecom:Order:OrderLine.IsProduct") || (orderline.GetBoolean("Ecom:Order:OrderLine.IsDiscount") && isProductIdOrNumber);
	bool orderIsQuote = Dynamicweb.Ecommerce.Services.Orders.GetById(GetString("Ecom:Order.ID")).IsQuote;

	if (isProduct)
	{
		var bomItems = orderline.GetLoop("BOMItems");
		<article class="grid pt-3" style="row-gap: 0;" data-product-id="@productId" data-variant-id="@variantId" data-unit-id="@unitId" data-orderline-total-price="@priceTotalWithDiscountsClean" data-orderline-unit-price="@unitPriceWithDiscount">
			<div class="g-col-3 g-col-lg-2">
				<a href="@link" class="ratio ratio-1x1 d-block" title="@name">
					<img class="cart-item-img" src="@image" style="object-fit: contain;" alt="@name">
				</a>
			</div>

			<div class="g-col-9 g-col-lg-10">

				<div class="grid" style="row-gap: 0.5rem;--bs-gap:0;">

					<div class="g-col-12 g-col-md-8 grid grid-7 grid-md-9" style="row-gap: 0.5rem;">
						<div class="g-col-7 g-col-md-6">
							@* Title *@
							<h3 class="fs-7 fs-md-6 mb-0">
								<a href="@link" class="text-decoration-none" title="@name">@name</a>
							</h3>

							@* Variants *@
							@if (!string.IsNullOrEmpty(variantText))
							{
								<p class="mt-2 mb-0 fs-7 fs-md-6">@variantText</p>
							}

							@* Number *@
							@if (!string.IsNullOrEmpty(number))
							{
								<p class="mt-2 mb-0 fs-8 fs-md-7 text-muted">@(number)</p>
							}

							@if (orderline.GetBoolean("Ecom:Order:OrderLine.IsDiscount"))
							{
								@* Free product notice *@
								<p class="mt-2 mb-0 fs-7 fs-md-6 opacity-75">@Translate("Free product")</p>
							}
							else
							{
								@* Unit price *@
								<p class="fs-7 fs-md-6 mt-2 mb-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 fs-7">
											<span class="text-price">@unitPrice</span>
										</span>
									}
								</p>
							}
						</div>

						<div class="g-col-7 g-col-md-3">
							@if (!orderline.GetBoolean("Ecom:Order:OrderLine.IsDiscount") && !orderIsQuote)
							{
								@* Quantity *@
								<div class="input-group js-input-group">

									@{
										var orderlineViewModel = new Dynamicweb.Ecommerce.Frontend.OrderLineViewModel(){
											Id = orderlineId.ToString(),
											ProductId = productId,
											ProductVariantId = variantId,
											UnitId = unitId,
											Quantity = quantity
										};
									}

									@RenderPartial("Components/QuantitySelectorOrderline.cshtml", orderlineViewModel)

								</div>
							}
							else
							{
								<div class="text-center" style="max-width: 140px;">@quantity</div>
							}
						</div>
					</div>

					<div class="g-col-12 g-col-md-4 text-end">
						@* Total *@
						<div class="fs-7 fs-md-6">
							<span class="text-price">@priceTotalWithDiscounts</span>
						</div>
						@if (orderline.GetDouble("Ecom:Order:OrderLine.TotalDiscount.Price.Value") != 0)
						{
							<div class="fs-8">
								<span class="text-price">@discountTotal</span>
							</div>
						}
					</div>

					<div class="g-col-12">
						@if (!orderIsQuote)
						{
							string clickProductLink = "onclick=\"return removeProductLink('" + @productId + "', '" + @Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(name) + "', '" + @Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(variantText) + "', '" + @unitPriceCurrency + "', '" + @unitPriceWithDiscount + "', '" + @discountAmount + "', '" + @quantity.ToString().Replace(",", ".") + "')\"";

							<a href="@removeFromBasketLink" class="btn btn-link btn-sm p-0 m-0 fs-8" title="@Translate("Remove")" @clickProductLink>@Translate("Remove")</a>
						}

						<script>
							function removeProductLink(productId, productName, productVariant, productCurrency, productPrice, productDiscount, productQuantity) {
								window.dataLayer = window.dataLayer || [];
								window.dataLayer.push({
									event: "remove_from_cart",
									ecommerce: {
										currency: productCurrency,
										value: (parseFloat(productPrice) * parseFloat(productQuantity)),
										items: [
											{
												item_id: productId,
												item_name: productName,
												item_variant: productVariant,
												currency: productCurrency,
												price: productPrice,
												discount: productDiscount,
												item_list_id: "cart",
												item_list_name: "Cart",
												quantity: productQuantity
											}
										]
									}
								});
							}
						</script>

					</div>
				</div>
			</div>

			@* Bottom border *@
			<div class="g-col-12 mt-3">
				<span class="d-none d-lg-block border-bottom"></span>
			</div>

			@if (bomItems.Count > 0) {
				<div class="g-col-12 mt-3">
					@* BOM items *@
					@foreach (var bomItem in bomItems) {
						string bomImage = bomItem.GetString("Ecom:Product.PrimaryImage");
						bomImage = !bomImage.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? bomImage : $"/Admin/Public/GetImage.ashx?width=200&height=200&image={bomImage}&format=webp";

						string bomPriceTotalWithDiscounts = bomItem.GetString("Ecom:Order:OrderLine.TotalPriceWithProductDiscounts.PriceFormatted");
						string bomDiscountTotal = bomItem.GetString("Ecom:Order:OrderLine.TotalDiscount.PriceFormatted");

						var bomVariantName = string.Join(" ", bomItem.GetLoop("VariantGroups")
						.SelectMany(g => g.GetLoop("VariantOptions"))
						.Where(o => o.GetBoolean("Ecom:VariantOption.Selected"))
						.Select(o => $"<span>{o.GetString("Ecom:VariantOption.Name")} </span>"));


						<div class="grid">
							<div class="g-col-3 g-col-lg-2 d-flex align-items-center gap-2">
								<div class="icon-2 p-0 p-lg-3 opacity-25">
									@ReadFile("/Files/Images/Icons/arrow-turn-down-right.svg")
								</div>
								@if (!string.IsNullOrEmpty(bomImage)) {
									<div class="ratio ratio-1x1 d-block" title="@name">
										<img class="cart-item-img" src="@bomImage" style="object-fit: contain;" alt="@name">
									</div>
								}
							</div>
							<div class="g-col-9 g-col-lg-10 grid" style="row-gap: 0.5rem; --bs-gap:0;">
								<div class="g-col-12 g-col-md-8 grid grid-7 grid-md-9">
									<div class="g-col-7 g-col-md-6">
										<h3 class="fs-7 fs-md-6 m-0">@bomItem.GetString("Ecom:Product.Name") </h3>
										<div class="fs-7 fs-md-6">@bomVariantName</div>
									</div>
									<div class="g-col-7 g-col-md-3">
										<p class="fs-7 fs-md-6 mb-0 text-center" style="max-width: 140px;">@bomItem.GetDouble("Ecom:Order:OrderLine.Quantity")</p>
									</div>
								</div>
								<div class="g-col-12 g-col-md-4 text-end">
									@* Total - Hide when PriceType = Fixed *@
									@if (orderline.GetInteger("Ecom:Product.PriceType") != 1) { 
										<div class="fs-7 fs-md-6">
											<span class="text-price">@bomPriceTotalWithDiscounts</span>
										</div>
										if (bomItem.GetDouble("Ecom:Order:OrderLine.TotalDiscount.Price.Value") != 0)
										{
											<div class="fs-8">
												<span class="text-price">@bomDiscountTotal</span>
											</div>
										}
									}
								</div>
							</div>
						</div>

						@* Bottom border *@
						<div class="w-100 my-3">
							<span class="d-none d-lg-block border-bottom"></span>
						</div>
					}
				</div>
			}
		</article>
	}
}
