@inherits ViewModelTemplate<FavoriteListViewModel>
@using Dynamicweb.Rendering
@using Dynamicweb.Ecommerce.Frontend
@using Dynamicweb.Ecommerce.ProductCatalog
@using Dynamicweb.Ecommerce.CustomerExperienceCenter.Favorites
@using System.Globalization


@functions {
	public string GetRepositoryName()
	{
		return GetIndexValue();
	}

	public string GetQueryName()
	{
		return GetIndexValue(true);
	}

	public string GetIndexValue(bool isQuery = false, string defaultValue = "Products")
	{
		int pageId = GetPageIdByNavigationTag("Shop");
		if (pageId == 0) return defaultValue;

		var productCatalogParagraph = Dynamicweb.Content.Services.Paragraphs.GetParagraphsByPageId(pageId).OrderBy(p => p.Sort).FirstOrDefault(p => p.ModuleSystemName == "eCom_ProductCatalog" && Dynamicweb.Content.Services.Grids.GetGridRowById(p.GridRowId).Active);
		if (productCatalogParagraph == null) return defaultValue;

		var indexQuery = productCatalogParagraph.ModuleProperties["IndexQuery"].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
		if (indexQuery.Length <= 1) return defaultValue;

		var result = isQuery ? indexQuery[indexQuery.Length - 1].Replace(".query", "") : indexQuery[indexQuery.Length - 2];

		return string.IsNullOrEmpty(result) ? defaultValue : result;
	}

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

@{
	int favoriteListId = Model.Id;
	string currentPageUrl = "/Default.aspx?ID=" + Pageview.Page.ID + "&FavoriteListId=" + favoriteListId;
	int listItemsCount = Model?.ProductList?.TotalProductsCount != null ? Model.ProductList.TotalProductsCount : 0;
	string productCountLabel = listItemsCount > 1 ? Translate("products") : Translate("product");
	int pageSize = Model?.ProductList?.PageSize != null ? Model.ProductList.PageSize : 0;
	int userId = Pageview.User.ID;
	string listName = !string.IsNullOrEmpty(Model.Name) ? Model.Name : Translate("Favorites");
	string iconPath = "/Files/Images/Icons/";

	string url = "/Default.aspx?ID=" + (GetPageIdByNavigationTag("CartService"));
	if (!url.Contains("LayoutTemplate"))
	{
		url += url.Contains("?") ? "&LayoutTemplate=Swift-v2_MiniCart.cshtml" : "?LayoutTemplate=Swift-v2_MiniCart.cshtml";
	}

	var favoriteParameters = new Dictionary<string, object>();
	int defaultFavoriteListId = 0;

	IEnumerable<FavoriteList> favoriteLists = Pageview.User.GetFavoriteLists();
	if (favoriteLists.Count() == 1)
	{
		foreach (FavoriteList list in favoriteLists)
		{
			defaultFavoriteListId = list.ListId;
		}
	}

	favoriteParameters.Add("ListId", defaultFavoriteListId);
}

<div data-dw-colorscheme="@Pageview.CurrentParagraph?.ColorSchemeId">
	<header class="p-3 border-bottom">
		<div class="d-flex flex-row align-items-center gap-3">
			<h1 class="h6 m-0 flex-fill opacity-75">
				@listName
			</h1>
			<span class="small text-end">@listItemsCount @productCountLabel <span class="d-none d-sm-inline">@Translate("in this list")</span></span>
		</div>
	</header>

	@if (Model?.ProductList != null)
	{
		<div class="grid grid-2 grid-lg-3 grid-xxl-4 p-3">
			<script>
				window.dataLayer = window.dataLayer || [];
				window.dataLayer.push({
					event: "view_item_list",
					ecommerce: {
						item_list_id: "favourite_detail",
						item_list_name: "Favourite List",
						items: [
							@foreach (var product in Model.ProductList.Products)
							{
								<text>{
									item_id: "@product.Number",
									item_name: "@Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(product.Name)",
									currency: "@product.Price.CurrencyCode",
									price: @product.Price.ToStringInvariant(),
									discount: @product.Discount.ToStringInvariant()
								},</text>
							}
						]
					}
				});
			</script>

			@foreach (var product in Model.ProductList.Products)
			{
				string link = product.GetProductLink(GetPageIdByNavigationTag("Shop"), false);

				string priceId = "ProductPrice_" + product.Id + product.VariantId.Replace(".", "_");

				double? stepQty = product.PurchaseQuantityStep > 0 ? product.PurchaseQuantityStep : 1;
				double? minQty = product.PurchaseMinimumQuantity > 0 ? product.PurchaseMinimumQuantity : 1;
				double? valueQty = minQty > stepQty ? minQty : stepQty;

				string? priceMin = product?.VariantInfo?.PriceMin?.PriceFormatted;
				string? priceMax = product?.VariantInfo?.PriceMax?.PriceFormatted;
				string? price = !string.IsNullOrEmpty(priceMin) ? (priceMin != priceMax ? priceMin + " - " + priceMax : priceMin) : product?.Price.PriceFormatted;

				string productImage = "/Admin/Public/GetImage.ashx?Image=" + @product.DefaultImage.Value + "&Format=webp&Width=450&Height=450";
				productImage = !product.DefaultImage.Value.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? product.DefaultImage.Value : productImage;
				string productName = product.Name;
				productName += !string.IsNullOrEmpty(product.VariantName) ? " - " + product.VariantName : string.Empty;

				bool isDiscontinued = product.Discontinued;
				bool isNeverOutOfStock = product.NeverOutOfstock;
				string disableAddToCart = (product.StockLevel <= 0) ? "disabled" : string.Empty;
				disableAddToCart = isDiscontinued ? "disabled" : disableAddToCart;
				disableAddToCart = isNeverOutOfStock ? string.Empty : disableAddToCart;

				<article class="position-relative d-flex flex-column gap-3" data-product-id="@product.Id" data-variant-id="@product.VariantId">
					<div class="image">
						<div class="ratio ratio-1x1">
							@if (product.DefaultImage.Value != "")
							{
								string clickProductLink = "onclick=\"return clickProductLink('" + @product.Id + "', '" + @Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(product.Name) + "', '" + @Dynamicweb.Core.Encoders.HtmlEncoder.JavaScriptStringEncode(product.VariantName) + "', '" + @product.Price.CurrencyCode + "', '" + @product.Price.ToStringInvariant() + "', '" + @product.Discount.ToStringInvariant() + "')\"";

								<a href="@link" class="d-flex justify-content-center align-items-center" @clickProductLink>
									<script>
										function clickProductLink(productId, productName, productVariant, productCurrency, productPrice, productDiscount) {
											window.dataLayer = window.dataLayer || [];
											window.dataLayer.push({
												event: "select_item",
												ecommerce: {
													item_list_id: "favourite_detail",
													item_list_name: "Favourite List",
													items: [
														{
															item_id: productId,
															item_name: productName,
															currency: productCurrency,
															item_list_id: "favourite_detail",
															item_list_name: "Favourite List",
															item_variant: productVariant,
															price: productPrice,
															discount: productDiscount
														}
													]
												}
											});
										}
									</script>
									<img src="@productImage"
										 loading="lazy"
										 decoding="async"
										 class="mw-100 mh-100 p-2 p-lg-3"
										 alt="@product.Name">
								</a>
							}
							else
							{
								<a href="@link" class="d-block h-100 w-100">
									<div class="d-block h-100 w-100" style="background-color: var(--bs-gray-200);"></div>
								</a>
							}
						</div>
					</div>

					<div class="name flex-fill">@productName</div>

					<div>
						<div class="h4" itemprop="offers" itemscope itemtype="https://schema.org/Offer">
							<span itemprop="priceCurrency" content="@product.Price.CurrencyCode" class="d-none"></span>
							<span itemprop="price" content="@product.Price.Price" class="d-none"></span>

							@if (product.HasDiscount())
							{
								<span class="text-decoration-line-through opacity-75 me-3">@product.PriceBeforeDiscount.PriceFormatted</span>
							}
							<span class="text-price">@price</span>
							@if (product.Price.TryGetVatLabel(out string vatLabel)) {
								<small class="opacity-85 fst-normal">@Translate(vatLabel)</small>
							}
						</div>
					</div>

					<div class="d-flex align-items-center gap-3 gap-md-2">
						<form method="post" action="@url" class="flex-sm-fill">
							<template class="js-step-quantity-warning">
								<div class="modal-header">
									<h5 class="modal-title">@Translate("The quantity is not valid")</h5>
								</div>
								<div class="modal-body">
									<p class="text-muted">@Translate("Please select a quantity that is dividable by") @stepQty</p>
								</div>
							</template>

							<template class="js-min-quantity-warning">
								<div class="modal-header">
									<h5 class="modal-title">@Translate("The product could not be added to the cart")</h5>
								</div>
								<div class="modal-body">
									<p class="text-muted">@Translate("The quantity is not valid. You must buy at least") @product.PurchaseMinimumQuantity</p>
								</div>
							</template>

							<div class="d-flex flex-row">
								<input type="hidden" name="redirect" value="false">
								<input type="hidden" name="ProductId" value="@product.Id">
								<input type="hidden" name="cartcmd" value="add">

								<div class="js-input-group flex-sm-fill">
									@if (!string.IsNullOrEmpty(product.VariantId))
									{
										<input type="hidden" name="VariantId" value="@product.VariantId">
									}
									<input id="Quantity_@product.Id" name="Quantity" value="@DoubleToString(valueQty)" step="@DoubleToString(stepQty)" min="@DoubleToString(minQty)" type="hidden">
									<button type="button"
											onclick="swift.Cart.Update(event)"
											class="d-none d-sm-block btn btn-primary w-100 js-add-to-cart-button @disableAddToCart"
											data-dw-button="primary"
											title="@Translate("Add to cart")"
											id="AddToCartButton@(product.Id)"
											@disableAddToCart
											data-referer="favourite_detail"
											data-product-id="@product.Id"
											data-variant-id="@product.VariantId"
											data-product-name="@product.Name"
											data-product-price="@product.Price.Price"
											data-product-currency="@product.Price.CurrencyCode">
										@Translate("Add to cart")
									</button>
									<button type="button"
											onclick="swift.Cart.Update(event)"
											class="d-sm-none btn btn-primary js-add-to-cart-button p-0 @disableAddToCart"
											data-dw-button="primary"
											title="@Translate("Add to cart")"
											id="AddToCartButton@(product.Id)"
											@disableAddToCart
											data-referer="favourite_detail"
											data-product-id="@product.Id"
											data-variant-id="@product.VariantId"
											data-product-name="@product.Name"
											data-product-price="@product.Price.Price"
											data-product-currency="@product.Price.CurrencyCode">
										<span class="icon-2 p-3">
											@ReadFile(iconPath + "cart-shopping.svg")
										</span>
									</button>
								</div>
							</div>
						</form>
						<div>
							@RenderPartial("Components/ToggleFavorite.cshtml", product, favoriteParameters)
						</div>
					</div>
				</article>
			}
		</div>

		if (listItemsCount > pageSize)
		{
			string pageHrefTemplate = string.Format("<a class=\"page-link\" href=\"{0}&PageNum={{0}}&PageSize={{1}}\">{{0}}</a>", currentPageUrl);

			<div class="p-3">
				<ul class="pagination m-0">
					@for (int i = 1; i <= Model.ProductList.PageCount; i++)
					{
						var css = i == Model.ProductList.CurrentPage
							? "page-item active"
							: "page-item";

						<li class="@css">
							@string.Format(pageHrefTemplate, i, Model.ProductList.PageSize)
						</li>
					}
				</ul>
			</div>
		}
	}
</div>
