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

@{
	var order = Dynamicweb.Ecommerce.Services.Orders.GetById(GetString("Ecom:Order.ID")) ?? null;
	var invoice = order?.TryGetOrderViewModel(out var orderViewModel) is true ? orderViewModel : null;
	var invoiceLines = invoice?.OrderLines?
		.Where(orderLine => orderLine.OrderLineType != OrderLineType.ProductDiscount && (!string.IsNullOrEmpty(orderLine.ProductId) || !string.IsNullOrEmpty(orderLine.ProductNumber)))
		.ToList() ?? new List<Dynamicweb.Ecommerce.Frontend.OrderLineViewModel>();
	var selectedInvoicesCount = invoiceLines.Count;
	string selectedInvoicesCountText = selectedInvoicesCount == 1 ? Translate("Invoice") : Translate("Invoices");
	var totalPaymentAmount = invoiceLines.Sum(orderLine => orderLine.Price.Price);
	var savedCards = GetLoop("SavedCards");
	var outstandingInvoicesPageId = GetPageIdByNavigationTag("OutstandingInvoices");
	var backLink = outstandingInvoicesPageId is not 0 ? SearchEngineFriendlyURLs.GetFriendlyUrl(outstandingInvoicesPageId) : null;
	var currentPageUrl = SearchEngineFriendlyURLs.GetFriendlyUrl($"Default.aspx?ID={Pageview?.Page?.ID ?? 0}");
}

@if (outstandingInvoicesPageId is not 0)
{
	<nav class="mb-4">
		<a href="@(backLink)" class="btn btn-outline-secondary border-0 hstack gap-2 px-3 d-inline-flex text-body" data-dw-button aria-label="@Translate("Back")">
			<span class="icon">
				@ReadFile("/Files/Images/Icons/arrow-left.svg")
			</span>
			<span>@Translate("Back")</span>
		</a>
	</nav>
}

<header class="mb-4">
	<h1 class="h4 mb-0">@(Pageview?.Page?.GetDisplayName() ?? string.Empty)</h1>
</header>


<h6 class="mb-3 fw-bold">@Translate("Selected transactions") - @selectedInvoicesCount @selectedInvoicesCountText</h6>

<div data-swift-invoices-payment>
	<form 
		hx-post="@(currentPageUrl)"
		hx-trigger="input from:input[name^='AmountWithoutVAT_'] changed delay:1200ms queue:last"
		hx-sync="this:abort"
		hx-swap="outerHTML"
		hx-disinherit="*"
		hx-target="[data-swift-invoices-payment]"
		hx-select="[data-swift-invoices-payment]">

		<input type="hidden" name="CartCmd" value="UpdateCombinedPayments" />

		<div class="card overflow-hidden mb-4">
			<div class="table-responsive">
				<table class="table table-md table-hover mb-0 align-middle fs-7"
					style="--bs-table-color: var(--bs-body-color);">
					<thead
						style="--bs-table-bg: rgba(var(--bs-body-color-rgb), .0275); --bs-table-color: rgba(var(--bs-body-color-rgb), 0.5);">
						<tr>
							<th>@Translate("Number")</th>
							<th>@Translate("Balance")</th>
							<th>@Translate("Payment")</th>
						</tr>
					</thead>
					<tbody>
						@foreach (var orderLine in invoiceLines)
						{
							string orderLineId = !string.IsNullOrEmpty(orderLine.ProductNumber) ? orderLine.ProductNumber : orderLine.Id;
							string displayNumber = !string.IsNullOrEmpty(orderLine.Reference) ? orderLine.Reference : orderLine.ProductName;
							string amountFieldId = "AmountWithoutVAT_" + orderLineId;
							var ledger = orderLine.GetLedger();
							bool isDisabled = orderLine.Price.PriceWithoutVat == ledger?.RemainingBalance.PriceWithoutVat;
							string disabledAttribute = isDisabled ? "disabled" : string.Empty;
							string paymentAmount = orderLine.Price.PriceWithoutVat.ToString("0.00", CultureInfo.InvariantCulture);
							string maxPaymentAmount = ledger is not null
								? ledger.RemainingBalance.PriceWithoutVat.ToString("0.00", CultureInfo.InvariantCulture)
								: string.Empty;

							<tr class="position-relative">
								<td>@displayNumber</td>
								<td class="fw-bold text-price">@ledger?.RemainingBalance.PriceWithoutVatFormatted</td>
								<td>
									<div class="position-relative" style="max-inline-size: 15rem;">
										<input type="hidden" name="Ids" value="@orderLineId" />
										<div class="hstack">
											<input id="@(amountFieldId)" type="number" min="0" max="@maxPaymentAmount" class="form-control"
												name="@(amountFieldId)"
												value="@paymentAmount"
												step="0.01"
												oninput="this.classList.toggle('text-danger', Number(this.value) > Number(this.max))"
												onchange="this.classList.toggle('text-danger', Number(this.value) > Number(this.max))"
												@disabledAttribute
												aria-label="@Translate("Amount to pay")" />
											<button type="button" class="btn btn-outline-secondary text-reset p-2 border-0" style="background-color: transparent;" data-dw-button
												onclick="const amountInput = document.getElementById('@amountFieldId'); if (amountInput) { amountInput.disabled = false; amountInput.focus(); amountInput.select(); }"
												aria-label="@Translate("Edit amount to pay")">
												<span class="icon">
													@ReadFile("/Files/Images/Icons/pen.svg")
												</span>
											</button>
										</div>
										<span class="position-absolute top-50 end-0 translate-middle-y pe-5 text-body-tertiary">
											<span class="htmx-indicator spinner-border spinner-border-sm" aria-hidden="true"></span>
										</span>
									</div>
								</td>
							</tr>
						}
					</tbody>
				</table>
			</div>
		</div>

		<div class="card border-0 mb-4" style="--bs-card-bg: rgba(var(--bs-body-color-rgb), .0275);">
			<div class="card-body p-3">
				<div class="hstack justify-content-between">
					<h6 class="mb-0">@Translate("Total payment amount")</h6>
					<span class="text-price fw-bold">@Dynamicweb.Ecommerce.Services.Currencies.Format(Dynamicweb.Ecommerce.Common.Context.Currency, totalPaymentAmount)</span>
				</div>
			</div>
		</div>
	</form>
</div>

<div class="d-flex justify-content-between align-items-center mb-3">
	<h6 class="m-0 fw-bold">@Translate("Payment options")</h6>
	<a href="/Default.aspx?ID=@GetPageIdByNavigationTag("SavedCardsPage")">@Translate("Manage your wallet")</a>
</div>

<form method="post">
	<div class="card overflow-hidden mb-4">
		<div class="table-responsive">
			<table class="table table-md table-hover mb-0 align-middle fs-7"
				style="--bs-table-color: var(--bs-body-color);">
				<thead
					style="--bs-table-bg: rgba(var(--bs-body-color-rgb), .0275); --bs-table-color: rgba(var(--bs-body-color-rgb), 0.5);">
					<tr>
						@if (savedCards.Count > 0)
						{
							<th class="pe-0" style="width:3rem;">&nbsp;</th>
						}
						<th>@Translate("Card")</th>
						<th>@Translate("Name")</th>
					</tr>
				</thead>
				<tbody>
					@{
						string selectedCardId = GetString("Ecom:Order.SavedCardID");

						foreach (LoopItem card in savedCards)
						{
							bool isChecked = card.GetBoolean("Ecom:SavedCard.IsSelected");
							isChecked = string.IsNullOrEmpty(selectedCardId) && card.GetBoolean("Ecom:SavedCard.IsDefault") ? true : isChecked;

							<tr>
								<td class="pe-0">
									<div class="form-check mb-0">
										<input class="form-check-input" type="radio" name="EcomCartSavedCardID"
											id="EcomSavedCardID_@card.GetString("Ecom:SavedCard.ID")"
											value="@card.GetString("Ecom:SavedCard.ID")" checked="@isChecked"
											data-card-name="@card.GetString("Ecom:SavedCard.Name")">
									</div>
								</td>
								<td>
									<label for="EcomSavedCardID_@card.GetString("Ecom:SavedCard.ID")" class="form-check-label">
										@if (!string.IsNullOrEmpty(card.GetString("Ecom:SavedCard.Payment.Icon")))
										{
											if (card.GetString("Ecom:SavedCard.Payment.Icon.Clean").EndsWith(".svg",
											StringComparison.OrdinalIgnoreCase))
											{
												<span class="icon-2">
													@ReadFile(card.GetString("Ecom:SavedCard.Payment.Icon.Clean"))
												</span>
											}
											else
											{
												<img src="@card.GetString("Ecom:SavedCard.Payment.Icon.Clean")" class="me-2"
													style="max-width: 1.5rem; max-height: 1.5rem;"
													alt="@card.GetString("Ecom:SavedCard.CardType")">
											}
										}
										@card.GetString("Ecom:SavedCard.CardType") •••• •••• ••••
										@card.GetString("Ecom:SavedCard.Identifier").Substring(card.GetString("Ecom:SavedCard.Identifier").Length - 4)
									</label>
								</td>
								<td>@(card.GetString("Ecom:SavedCard.Name"))</td>
							</tr>
						}

						if (savedCards.Count < 1)
						{
							<tr class="position-relative">
								<td colspan="2">
									<div class="d-grid py-4">
										<span class="m-auto">
											<div class="d-grid rounded-circle m-auto" style="width:4rem;aspect-ratio:1;background-color:rgba(var(--bs-body-color-rgb), .0275);">
												<span class="icon-4 text-body text-muted">
													@ReadFile("/Files/Images/Icons/credit-card.svg")
												</span>
											</div>
											<div class="mt-3">@Translate("No cards found")</div>
										</span>
									</div>
								</td>
							</tr>
						}
					}

				</tbody>
			</table>
		</div>
	</div>

	<h6 class="mb-3 fw-bold">@Translate("Comment")</h6>

	<textarea class="form-control mb-4" name="EcomOrderCustomerComment" id="EcomOrderCustomerComment"
		style="min-height: 100px"
		placeholder="@Translate("Add any additional information here")">@GetString("Ecom:Order.Customer.Comment.Clean")</textarea>

	<div class="hstack gap-2 justify-content-end border-top pt-3 w-100 mb-6">
		<button class="btn btn-primary" type="submit" name="@GetString("CartV2.NextStepButtonName")"
			id="@GetString("CartV2.NextStepButtonName")" data-dw-button>@Translate("Complete payment")</button>
	</div>
</form>