@inherits Dynamicweb.Rendering.RazorTemplateBase<Dynamicweb.Rendering.RazorTemplateModel<Dynamicweb.Rendering.Template>>
@using Dynamicweb

@functions {

	string GetCurrentCountry()
	{

		string currentCountry = Pageview.Area?.EcomCountryCode != null ? Pageview.Area.EcomCountryCode : "dk";
		foreach (LoopItem country in GetLoop("Countries"))
		{
			if (country.GetString("Ecom:Country.IsDeliveryCountryOrDefault") == "true")
			{
				currentCountry = country.GetString("Ecom:Country.Code2");
			}
		}
		return currentCountry;
	}

	string SetCountrySelectorColumnSize(string currentCountry)
	{
		string countrySelectorColumnSize = "g-col-6";
		if (currentCountry == "US" || currentCountry == "CA" || currentCountry == "GB")
		{
			if (GetLoop("CustomerRegions").Count > 0)
			{
				countrySelectorColumnSize = "g-col-3";
			}
		}
		return countrySelectorColumnSize;
	}

}

@{
	string billingAddressStringTrimmed = (GetString("Ecom:Order.Customer.Company") + GetString("Ecom:Order.Customer.Name") + GetString("Ecom:Order.Customer.Address") + GetString("Ecom:Order.Customer.Address2") + GetString("Ecom:Order.Customer.Zip") + GetString("Ecom:Order.Customer.City") + GetString("Ecom:Order.Customer.Phone")).Trim(',');
	string deliveryAddressStringTrimmed = (GetString("Ecom:Order.Delivery.Company") + GetString("Ecom:Order.Delivery.Name") + GetString("Ecom:Order.Delivery.Address") + GetString("Ecom:Order.Delivery.Address2") + GetString("Ecom:Order.Delivery.Zip") + GetString("Ecom:Order.Delivery.City") + GetString("Ecom:Order.Delivery.Phone")).Trim(',');
	bool deliveryAddressSpecifiedAndDifferent = !string.IsNullOrWhiteSpace(deliveryAddressStringTrimmed) && !billingAddressStringTrimmed.Equals(deliveryAddressStringTrimmed, StringComparison.OrdinalIgnoreCase);
}

<div class="grid gap-0 h-100" id="DeliveryAnonymous">
	<div class="g-col-12 g-col-lg-8 p-3 p-lg-4 pe-xl-5 ps-xl-6 ps-xxl-8 order-last order-lg-first" data-dw-colorscheme="@Pageview.CurrentParagraph?.ColorSchemeId">
		<form name="ordersubmit" id="ordersubmit" method="post" autocomplete="off" style="max-width: 65rem; margin-left: auto;">

			@Include("Helpers/Logo.cshtml")

			@Include("Helpers/StepsBreadcrumbs.cshtml")

			@Include("Helpers/Errors.cshtml")

			@Include("Helpers/StepSummary.cshtml")

			@Include("Helpers/ShippingMethods.cshtml")

			@if (GetBoolean("Ecom:Order.Delivery.isPickupPoint") || Dynamicweb.Context.Current.Items.Contains("DroppointsRendered"))
			{
				<input type="hidden" name="EcomOrderDeliveryCompany" value="">
				<input type="hidden" name="EcomOrderDeliveryName" value="">
				<input type="hidden" name="EcomOrderDeliveryAddress" value="">
				<input type="hidden" name="EcomOrderDeliveryAddress2" value="">
				<input type="hidden" name="EcomOrderDeliveryZip" value="">
				<input type="hidden" name="EcomOrderDeliveryCity" value="">
				<input type="hidden" name="EcomOrderDeliveryRegion" value="">
				<input type="hidden" name="EcomOrderDeliveryCountry" value="">
				<input type="hidden" name="EcomOrderDeliveryPhone" value="">
			}
			else
			{
				<div class="mt-4">

					<h3 class="fs-6 fw-normal mb-3">@Translate("Delivery address")</h3>

					<div class="list-group">

						<label class="list-group-item list-group-item-action d-flex justify-content-between" role="button">
							<span class="d-flex justify-content-between">
								<input class="form-check-input me-3" type="radio" name="DeliveryAddress" value="False" checked="@(!deliveryAddressSpecifiedAndDifferent)" onchange="window.swiftCart.toggleDeliveryAddressContainer(false)" id="SameAsDeliveryAddressRadio">
								<div>@Translate("Same address as billing address")</div>
							</span>
						</label>

						<label class="list-group-item list-group-item-action d-flex justify-content-between" role="button">
							<span class="d-flex justify-content-between">
								<input class="form-check-input me-3" type="radio" name="DeliveryAddress" value="True" checked="@(deliveryAddressSpecifiedAndDifferent)" onchange="window.swiftCart.toggleDeliveryAddressContainer(true)" id="UseAnotherBillingAddressRadio">
								<div>@Translate("Use another delivery address")</div>
							</span>
						</label>

						<div class="collapse @(deliveryAddressSpecifiedAndDifferent ? "show": "")" id="DeliveryAddressContainer">
							<div class="list-group-item border-top-0 py-3 bg-light">
								@* RenderDeliveryAddressAnonymous *@
								@{
									string currentCountry = GetCurrentCountry();
									string countrySelectorColumnSize = SetCountrySelectorColumnSize(currentCountry);
									string customerRegionLabel = "State";
								}

								<div class="mt-0 checkout_swift_billing-anonymous">

									<div class="grid">

										<div class="g-col-12">
											<div class="form-floating">
												<input type="text" class="form-control" name="EcomOrderDeliveryCompany" id="EcomOrderDeliveryCompany" value="@GetString("Ecom:Order.Delivery.Company").Trim(',')" placeholder="@Translate("Company")">
												<label for="EcomOrderDeliveryCompany">@Translate("Company (Optional)")</label>
											</div>
										</div>

										<div class="g-col-12">
											<div class="form-floating">
												<input type="text" class="form-control" name="EcomOrderDeliveryName" id="EcomOrderDeliveryName" value="@GetString("Ecom:Order.Delivery.Name").Trim(',')" placeholder="@Translate("Name")">
												<label for="EcomOrderDeliveryName">@Translate("Name")</label>
											</div>
										</div>

										<div class="g-col-12">
											<div class="form-floating">
												<input type="text" class="form-control" name="EcomOrderDeliveryAddress" id="EcomOrderDeliveryAddress" value="@GetString("Ecom:Order.Delivery.Address").Trim(',')" placeholder="@Translate("Street & Number")">
												<label for="EcomOrderDeliveryAddress">@Translate("Street & Number")</label>
											</div>
										</div>

										<div class="g-col-12">
											<div class="form-floating">
												<input type="text" class="form-control" name="EcomOrderDeliveryAddress2" id="EcomOrderDeliveryAddress2" value="@GetString("Ecom:Order.Delivery.Address2").Trim(',')" placeholder="@Translate("Additional address")">
												<label for="EcomOrderDeliveryAddress2">@Translate("Additional address")</label>
											</div>
										</div>

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

											<div class="grid">

												<div class="g-col-3">
													<div class="form-floating">
														<input type="text" class="form-control" name="EcomOrderDeliveryZip" id="EcomOrderDeliveryZip" value="@GetString("Ecom:Order.Delivery.Zip").Trim(',')" placeholder="@Translate("Zip code")">
														<label for="EcomOrderDeliveryZip">@Translate("Zip code")</label>
													</div>
												</div>



												<div class="@countrySelectorColumnSize">
													<div class="form-floating">
														<input type="text" class="form-control" name="EcomOrderDeliveryCity" id="EcomOrderDeliveryCity" value="@GetString("Ecom:Order.Delivery.City").Trim(',')" placeholder="@Translate("Town / City")">
														<label for="EcomOrderDeliveryCity">@Translate("Town / City")</label>
													</div>
												</div>

												@if (currentCountry == "US" || currentCountry == "CA" || currentCountry == "GB")
												{
													if (GetLoop("CustomerRegions").Count > 0)
													{
														if (currentCountry == "CA")
														{
															customerRegionLabel = Translate("Province");
														}
														else if (currentCountry == "GB")
														{
															customerRegionLabel = Translate("Region");
														}
														else if (currentCountry == "US")
														{
															customerRegionLabel = Translate("State");
														}

														<div class="g-col-3">
															<div class="form-floating">
																<select class="form-select" name="EcomOrderCustomerRegion" id="EcomOrderCustomerRegion" onchange="submitForm()">
																	@foreach (LoopItem region in GetLoop("CustomerRegions"))
																	{
																		if (region.GetString("Ecom:CustomerRegion.IsCustomerRegion") == "true")
																		{
																			<option value="@region.GetString("Ecom:CustomerRegion.RegionCode")" selected>@region.GetString("Ecom:CustomerRegion.Name")</option>
																		}
																		else
																		{
																			<option value="@region.GetString("Ecom:CustomerRegion.RegionCode")">@region.GetString("Ecom:CustomerRegion.Name")</option>
																		}
																	}
																</select>
																<label for="EcomOrderCustomerRegion">@customerRegionLabel</label>
															</div>
														</div>
													}
												}

												<div class="g-col-12 g-col-md-3">
													<div class="form-floating">
														<select class="form-control" name="EcomOrderDeliveryCountry" id="EcomOrderDeliveryCountry">
															@foreach (LoopItem country in GetLoop("Countries"))
															{
																if (country.GetString("Ecom:Country.IsCustomerCountryOrDefault") == "true" || country.GetString("Ecom:Country.Code2") == GetString("Ecom:Order.Delivery.Country.Code"))
																{
																	<option value="@country.GetString("Ecom:Country.Code2")" selected>@country.GetString("Ecom:Country.Name")</option>
																}
																else
																{
																	@*<option value="@country.GetString("Ecom:Country.Code2")">@country.GetString("Ecom:Country.Name")</option>*@
																}
															}
														</select>
														<label for="EcomOrderDeliveryCountry">@Translate("Country")</label>
													</div>
												</div>

											</div>

										</div>

										<div class="g-col-12">
											<div class="form-floating">
												<input type="tel" class="form-control" name="EcomOrderDeliveryPhone" id="EcomOrderDeliveryPhone" value="@GetString("Ecom:Order.Delivery.Phone").Trim(',')" placeholder="@Translate("Phone number")">
												<label for="EcomOrderDeliveryPhone">@Translate("Phone number")</label>
											</div>
										</div>
									</div>

								</div>

							</div>
						</div>
						<div id="DeliveryAddressContainerHiddenFields">
							@*These fields are submitted when no pickup point is selected or no alternative delivery has been chosen*@
							<input type="hidden" name="EcomOrderDeliveryCompany" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryName" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryAddress" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryAddress2" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryZip" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryCity" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryRegion" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryCountry" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
							<input type="hidden" name="EcomOrderDeliveryPhone" value="" disabled="@(deliveryAddressSpecifiedAndDifferent)">
						</div>

					</div>
				</div>
			}

			@Include("Helpers/OrderDeliveryDate.cshtml")

			@Include("Helpers/StepsNavigation.cshtml")

			<input type="hidden" id="CurrentStep">
		</form>
	</div>

	@Include("Helpers/SummarySidebar.cshtml")

</div>

<script>
	function submitForm() {
		document.querySelector("#CurrentStep").name = "@GetString("CartV2.CurrentStepButtonName")";
		swift.PageUpdater.Update(document.querySelector("#ordersubmit"));
	}
</script>

<script>
	if (!window.swiftCart) window.swiftCart = {};
	window.swiftCart.toggleDeliveryAddressContainer = function (showContainer) {
		const address = document.getElementById("DeliveryAddressContainer");
		const hidden = document.getElementById("DeliveryAddressContainerHiddenFields");

		address?.querySelectorAll(".form-control, .form-select").forEach(f => f.disabled = !showContainer);
		hidden?.querySelectorAll("input").forEach(f => f.disabled = showContainer);

		if (address && window.bootstrap?.Collapse) {
			try {
				let c = window.swiftCart._collapse;
				if (!c || c._element !== address)
					c = window.swiftCart._collapse = new bootstrap.Collapse(address, { toggle: false });
				showContainer ? c.show() : c.hide();
			} catch (e) {}
		}
	};
</script>

<script>
	// Prevent multiple declarations, e.g., when htmx swaps/reloads this content
	if (!window.swiftCart) window.swiftCart = {};
	if (!window.swiftCart.initDeliveryAddressToggle) {
		window.swiftCart.initDeliveryAddressToggle = true;
		let showContainer = @(deliveryAddressSpecifiedAndDifferent.ToString().ToLower());
		window.swiftCart.toggleDeliveryAddressContainer(showContainer);
	}
</script>

@{
	string apiKey = Pageview.AreaSettings.GetString("Google_APIKey", "");
	bool enableFindLocation = Pageview.CurrentParagraph.Item["EnableFindLocation"] != null ? (Boolean)Pageview.CurrentParagraph.Item["EnableFindLocation"] : false;

	if (enableFindLocation && !string.IsNullOrEmpty(apiKey))
	{
		string currentCountry = Pageview.Area?.EcomCountryCode != null ? Pageview.Area.EcomCountryCode : "dk";
		foreach (LoopItem country in GetLoop("Countries"))
		{
			if (country.GetString("Ecom:Country.IsDeliveryCountryOrDefault") == "true")
			{
				currentCountry = country.GetString("Ecom:Country.Code2");
			}
		}
		<script type="module">
			const assetLink = 'https://maps.googleapis.com/maps/api/js?key=@(apiKey)&libraries=places';

			let assetFound = false;
			document.head.querySelectorAll('script').forEach(element => {
				if (assetLink == element.src) {
					assetFound = true;
				}
			});

			swift.AssetLoader.Load(assetLink, 'js');

			if (!assetFound) {
				document.addEventListener('load.swift.assetloader', function() {
					var mapSettings = { currentCountry: "@currentCountry" };
					swift.Places.init(mapSettings);
				});
			} else if (typeof google !== 'undefined') {
				var mapSettings = { currentCountry: "@currentCountry" };
				swift.Places.init(mapSettings);
			}
		</script>
	}
}

<script>
	window.dataLayer = window.dataLayer || [];
	window.dataLayer.push({
		event: "add_shipping_info",
		ecommerce: {
			currency: "@GetString("Ecom:Order.CurrencyCode")",
			value: @GetDouble("Ecom:Order.Price.Price.Value").ToString("0.00", System.Globalization.CultureInfo.InvariantCulture),
			items: [
				@foreach (LoopItem orderline in GetLoop("OrderLines")) {
					<text>
					{
						item_id: "@orderline.GetString("Ecom:Order:OrderLine.ProductID")",
						item_name: "@orderline.GetString("Ecom:Order:OrderLine.ProductName")",
						currency: "@orderline.GetString("Ecom:Order:OrderLine.UnitPrice.CurrencyCode")",
						price: @orderline.GetDouble("Ecom:Order:OrderLine.UnitPriceWithProductDiscount.Price.Value").ToString("0.00", System.Globalization.CultureInfo.InvariantCulture),
						discount: @Math.Abs(orderline.GetDouble("Ecom:Order:OrderLine.UnitDiscount.Price.Value")).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture),
						quantity: @orderline.GetDouble("Ecom:Order:OrderLine.Quantity").ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
					},
					</text>
				}
			]
		}
	});
</script>
