@inherits ViewModelTemplate<ProductListViewModel>
@using Dynamicweb.Rendering
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Ecommerce.Products
@using System.Globalization

@{
	var orderId = Dynamicweb.Context.Current?.Request.QueryString.Get("OrderID") ?? null;
	var order = !string.IsNullOrEmpty(orderId) ? Dynamicweb.Ecommerce.Services.Orders.GetById(orderId) : null;
	string iconPath = "/Files/Images/Icons/";
	bool defaultQuantityAsZero = Convert.ToBoolean(Dynamicweb.Context.Current?.Request["defaultQuantityAsZero"]);
	var productCounter = 0;
	int productsOutOfStock = 0;
	List<ProductViewModel> orderProducts = new List<ProductViewModel>();
	Dictionary<string, double> productQuantityList = new Dictionary<string, double>();

	if (order != null)
	{
		ProductViewModelSettings productSetting = new ProductViewModelSettings
		{
			LanguageId = Dynamicweb.Ecommerce.Common.Context.LanguageID,
			CurrencyCode = Dynamicweb.Ecommerce.Common.Context.Currency.Code,
			CountryCode = Dynamicweb.Ecommerce.Common.Context.Country.Code2,
			ShopId = Pageview.Area.EcomShopId
		};

		int orderlineCounter = 0;

		foreach (var orderline in order.OrderLines)
		{
			if (!string.IsNullOrEmpty(orderline.ProductId))
			{
				var productViewModel = ViewModelFactory.CreateView(productSetting, orderline.ProductId, orderline.ProductVariantId);

				if (productViewModel != null && productViewModel?.PrimaryOrDefaultGroup?.Id != null)
				{
					orderProducts.Add(productViewModel);

					productQuantityList.Add($"{orderline.ProductId}_{orderlineCounter}", orderline.Quantity);
				}
				else
				{
					var simpelModel = new ProductViewModel()
					{
						Id = orderline.Id,
						Name = orderline.ProductName,
						Number = orderline.ProductNumber,
						VariantName = orderline.ProductVariantText
					};

					orderProducts.Add(simpelModel);
				}
				orderlineCounter++;
			}
		}
	}
	var products = order == null ? Model.Products : orderProducts;
	bool hasDiscontinuedProducts = products.Any(p => p.Discontinued && !string.IsNullOrEmpty(p.ReplacementProduct.ProductId) && p.ReplacementProduct.GetProduct() != null
	&& p.ReplacementProduct.GetProduct().Active && (p.ReplacementProduct.GetProduct().ProductType != ProductType.Stock || p.ReplacementProduct.GetProduct().StockLevel >= 0 || p.ReplacementProduct.GetProduct().NeverOutOfstock));
}

@if (products.Any())
{
	<div class="modal fade" id="outOfStockProductsModal" tabindex="-1" aria-labelledby="outOfStockProductsModal" aria-hidden="true">
		<div class="modal-dialog modal-xl modal-dialog-centered">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="exampleModalLabel">@Translate("Some products can not be ordered")</h5>
					<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
					<table class="table">
						<thead>
							<tr>
								<td></td>
								<td>@Translate("Number")</td>
								<td>@Translate("Product")</td>
								<td>@Translate("Variant")</td>
								<td>@Translate("Stock state")</td>
								<td class="text-end">@Translate("Price")</td>
							</tr>
						</thead>
						<tbody>
							@foreach (var product in products)
							{
								productCounter += 1;
								ProductViewModel replacementProduct = product.Discontinued && product.ReplacementProduct != null && !string.IsNullOrEmpty(product.ReplacementProduct.ProductId) ? product.ReplacementProduct.GetProduct() : null;
								bool showReplacementProduct = product.Discontinued && replacementProduct != null && replacementProduct.Active && (replacementProduct.ProductType != ProductType.Stock || replacementProduct.StockLevel > 0 || replacementProduct.NeverOutOfstock);
								
								if ((product.StockLevel <= 0 && !product.NeverOutOfstock) || product.Discontinued)
								{
									<tr>
										<td class="align-middle">
											<img class="img-fluid" src="/Admin/public/getimage.ashx?image=@Dynamicweb.Context.Current.Server.UrlEncode(product.DefaultImage.Value)&width=60&height=60&format=webp&Crop=5&fillcanvas=true" height="60" width="60" alt="@product.Name">
										</td>
										<td class="align-middle">
											<span class="fs-8 fs-lg-6">@product.Number</span>
										</td>
										<td class="align-middle">
											<span class="fs-8 fs-lg-6">@product.Name</span>
											@if (product.Discontinued && showReplacementProduct)
											{
												<span class="fs-9 fs-lg-7 fst-italic fw-bold d-block js-product-replacements-message" data-product-counter="@productCounter" data-replaced-by-message="@($"{Translate("Replaced by")} {replacementProduct.Name}")" data-replace-refused-message="@Translate("Replacement Refused")">@Translate("Replacement not selected")</span>
											}
										</td>
										<td class="align-middle">
											<span class="fs-8 fs-lg-6">@product.VariantName</span>
										</td>
										<td class="align-middle">
											<span class="fs-8 fs-lg-6 text-end text-lg-start text-danger">
												@Translate(product.Discontinued ? "Discontinued" : "Out of Stock")
											</span>
										</td>
										<td class="align-middle text-end">
											<span class="text-price fs-8 fs-lg-6">@product.Price.PriceFormatted</span>
										</td>
									</tr>
								}
							}
						</tbody>
					</table>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dw-button="secondary" data-bs-dismiss="modal">Cancel</button>
					<button type="submit" class="btn btn-primary" data-dw-button="primary" data-bs-dismiss="modal" id="OutOfStockAddRestToCartButton">
						<div class="d-flex gap-2 align-items-center lh-base">
							<span>@Translate("Confirm")</span>
							<span class="icon-2">
								@ReadFile(iconPath + "cart-shopping.svg")
							</span>
						</div>
					</button>
				</div>
			</div>
		</div>
	</div>

	if (hasDiscontinuedProducts)
	{
		<div class="modal fade" id="replacementProductsModal" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-xl modal-dialog-centered">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">
							@Translate("Replacement Product for")
							<span class="fst-italic js-modal-title-product-name"></span>
						</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body js-replacement-modal-body"></div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-dw-button="secondary" data-bs-dismiss="modal" onclick="swift.ExpressBuy.RefuseReplacementProduct()">
							<div class="d-flex gap-2 align-items-center lh-base">
								<span>@Translate("Refuse Replacement")</span>
								<span class="icon-2">
									@ReadFile(iconPath + "xmark.svg")
								</span>
							</div>
						</button>
						<button type="button" class="btn btn-primary" data-dw-button="primary" data-bs-dismiss="modal" onclick="swift.ExpressBuy.AcceptReplacementProduct()">
							<div class="d-flex gap-2 align-items-center lh-base">
								<span>@Translate("Accept Replacement")</span>
								<span class="icon-2">
									@ReadFile(iconPath + "check.svg")
								</span>
							</div>
						</button>
					</div>
				</div>
			</div>
		</div>
	}

	<header class="g-col-12 py-2 d-none d-lg-block">
		<div class="grid gap-2 lh-1">
			<div class="g-col-1"></div>
			<div class="g-col-1">@Translate("Number")</div>
			<div class="g-col-4">@Translate("Product")</div>
			<div class="g-col-1">@Translate("Variant")</div>
			<div class="g-col-1">@Translate("Stock state")</div>
			<div class="g-col-2 text-end">@Translate("Price")</div>
			<div class="g-col-2 text-end">@Translate("Qty")</div>
		</div>
	</header>

	productCounter = 0;

	foreach (var product in products)
	{
		if (product != null && product?.PrimaryOrDefaultGroup?.Id != null)
		{
			double? stepQty = product.PurchaseQuantityStep > 0 ? product.PurchaseQuantityStep : 1;
			double? minQty = product.PurchaseMinimumQuantity > 0 ? product.PurchaseMinimumQuantity : 1;
			string? disableQuantityField = null;
			double? maxQty = null;
			bool isStockType = product.ProductType == Dynamicweb.Ecommerce.Products.ProductType.Stock;
			if (isStockType && !product.NeverOutOfstock)
			{
				disableQuantityField = (product.StockLevel <= 0) || product.Discontinued ? "disabled" : disableQuantityField;
				maxQty = product.StockLevel;
			}

			double? quantity = null;
			if (productQuantityList.TryGetValue($"{product.Id}_{productCounter}", out double value))
			{
				quantity = value;
			}
			string disableOrderline = isStockType && ((product.StockLevel < 1 && !product.NeverOutOfstock) || product.Discontinued) ? "pe-none user-select-none opacity-50" : "";
			string link = product.GetProductLink(GetPageIdByNavigationTag("Shop"), false);
			productCounter += 1;
			if ((product.StockLevel < 1) && !product.NeverOutOfstock && quantity > 0)
			{
				productsOutOfStock++;
			}
			ProductViewModel replacementProduct = product.Discontinued && product.ReplacementProduct != null && !string.IsNullOrEmpty(product.ReplacementProduct.ProductId) ? product.ReplacementProduct.GetProduct() : null;
			bool showReplacementProduct = product.Discontinued && replacementProduct != null && replacementProduct.Active && (replacementProduct.ProductType != ProductType.Stock || (replacementProduct.StockLevel > 0 || replacementProduct.NeverOutOfstock));
			string replacementProductFeed = Dynamicweb.Frontend.SearchEngineFriendlyURLs.GetFriendlyUrl("Default.aspx?ID=" + GetPageIdByNavigationTag("ReorderReplacement") + "&ProductId=" + product.Id + "&productCounter=" + productCounter + "&quantity=" + quantity + "&getproductinfo=true");
			string defaultImage = Dynamicweb.Context.Current?.Server?.UrlEncode(product?.DefaultImage?.Value) ?? string.Empty;

			<article class="grid grid-12 gap-2 g-col-12 align-items-center align-items-lg-center product js-replacement-product @disableOrderline" data-product-counter="@productCounter" data-replacement-feed="@replacementProductFeed">

				<div class="d-none d-lg-block g-col-12 border-top"></div>

				<input type="hidden" name="ProductLoopCounter@(productCounter)" value="@(productCounter)">
				<input type="hidden" class="productId" name="ProductId@(productCounter)" value="@product.Id">
				<input type="hidden" class="productVariantId" name="VariantId@(productCounter)" value="@product.VariantId">

				<div class="g-col-1">
					<a class="productLink" href="@link" tabindex="-1">
						<img class="img-fluid productImage" src="/Admin/public/getimage.ashx?image=@defaultImage&width=60&height=60&format=webp&Crop=5&fillcanvas=true" height="60" width="60" alt="@product.Name">
					</a>
				</div>

				<div class="g-col-6 g-col-lg-9 grid grid-9 gap-0 gap-lg-2 lh-1">

					<div class="g-col-5 g-col-lg-1 order-1">
						<span class="fs-8 fs-lg-6"><a href="@link" tabindex="-1" class="text-decoration-none text-decoration-underline-hover productNumber">@product.Number</a></span>
					</div>

					<div class="g-col-5 g-col-lg-4 order-3 lh-1">
						<span class="fs-8 fs-lg-6"><a href="@link" tabindex="-1" class="text-decoration-none text-decoration-underline-hover js-product-name">@product.Name</a></span>
						<span class="fs-8 fs-lg-6 fst-italic fw-bold d-block">
							<a href="@link" tabindex="-1" class="text-decoration-none text-decoration-underline-hover js-product-replacements-message" data-product-counter="@productCounter" data-replace-refused-message="@Translate("Replacement Refused")"></a>
						</span>
					</div>

					<div class="g-col-2 g-col-lg-1 order-4">
						<span class="fs-8 fs-lg-6"><a href="@link" tabindex="-1" class="text-decoration-none text-decoration-underline-hover productVariantName">@product.VariantName</a></span>
					</div>

					<div class="g-col-2 g-col-lg-1 order-4">
						@if (product.Discontinued)
						{
							<div class="fs-8 fs-lg-6 text-end text-lg-start text-danger productStockState">@Translate("Discontinued")</div>
						}
						else if (product.NeverOutOfstock || !isStockType)
						{
							<div class="fs-8 fs-lg-6 text-end text-lg-start text-success">@Translate("In stock")</div>
						}
						else if (product.StockLevel > 0)
						{
							<div class="fs-8 fs-lg-6 text-end text-lg-start text-success">@product.StockLevel @Translate("In stock")</div>
						}
						else
						{
							<div class="fs-8 fs-lg-6 text-end text-lg-start text-danger">@Translate("Out of Stock")</div>
						}
					</div>

					<div class="g-col-4 g-col-lg-2 text-end order-2 order-lg-last">
						<span class="text-price fs-8 fs-lg-6 productPrice">@product.Price.PriceFormatted</span>
					</div>
				</div>

				<div class="g-col-4 g-col-lg-2 d-flex justify-content-end">
					@{
						var quantityParams = new Dictionary<string, object>();
						quantityParams.Add("LoopCounter", productCounter);
						quantityParams.Add("Quantity", quantity);
						@RenderPartial("Components/QuantitySelector.cshtml", product, quantityParams)
					}
				</div>

			</article>
			if (product.Discontinued && showReplacementProduct)
			{
				<div class="position-relative start-50 translate-middle d-flex g-start-8 js-product-replacements-button" data-product-counter="@productCounter" data-replacing-message="@($"{Translate("Replacing")} {product.Name}")" data-replace-refused-message="@Translate("Replacement Refused")">
					<a class="btn btn-sm btn-primary" data-dw-button="primary" role="button" data-bs-target="#replacementProductsModal" data-bs-toggle="modal" onclick="swift.ExpressBuy.OpenReplacementModal(@productCounter)" alt="@Translate("View replacement product")">@Translate("Replace")</a>
				</div>
			}
		}
		else
		{
			<article class="g-col-12">
				<div class="alert alert-danger">
					@Translate("The product") "@product.Name @product.VariantName" (@product.Number), @Translate("that was a part of this order, seems to have been removed. Contact the shop for further information.")
				</div>
			</article>
		}
	}

	<div class="d-flex justify-content-between align-items-baseline py-3 g-col-12 position-sticky bottom-0 bg-body" style="box-shadow: 0 -10px 10px -12px var(--bs-gray-300);">
		@Translate("Total results") @products.Count()

		@{
			var buttonProps = string.Empty;
			var buttonType = "button";

			if (productsOutOfStock == 0)
			{
				buttonProps = "id=\"AddAllToCartButton\"";
				buttonType = "submit";
			}
			else if (productsOutOfStock == products.Count())
			{
				buttonProps = "disabled";
			}
			else
			{
				buttonProps = "data-bs-toggle=\"modal\" data-bs-target=\"#outOfStockProductsModal\"";
			}
			<button type="@buttonType" class="btn btn-primary" data-dw-button="primary" @buttonProps>
				<div class="d-flex gap-2 align-items-center lh-base">
					<span>@Translate("Add all to cart")</span>
					<span class="icon-2">
						@ReadFile(iconPath + "cart-shopping.svg")
					</span>
				</div>
			</button>
		}
	</div>
}
