@extends('layouts.app')
@section('content')
<style>
	.debt-card {
		border: 1px solid #dee2e6;
		border-radius: 0.6rem;
		padding: 0.75rem;
		background: #fff;
	}

	.debt-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 0.5rem;
		margin-top: 0.4rem;
	}

	.debt-chip {
		display: inline-flex;
		align-items: center;
		gap: 0.35rem;
		padding: 0.25rem 0.55rem;
		border-radius: 999px;
		font-size: 0.8rem;
		background: #f8f9fa;
		border: 1px solid #e9ecef;
	}

	.debt-detail-list {
		display: flex;
		flex-wrap: wrap;
		gap: 0.4rem;
		padding-left: 0;
		list-style: none;
		margin-bottom: 0;
	}

	.debt-detail-list li {
		background: #f8f9fa;
		border: 1px solid #e9ecef;
		border-radius: 0.4rem;
		padding: 0.3rem 0.5rem;
		font-size: 0.8rem;
	}

	.debt-summary-totals {
		text-align: right;
		font-size: 1.2rem;
		line-height: 1.3;
	}

	@media (max-width: 767.98px) {
		.debt-card {
			padding: 0.65rem;
		}

		.debt-chip {
			font-size: 0.75rem;
		}

		.debt-summary-totals {
			text-align: left;
			margin-top: 0.5rem;
		}
	}
</style>
<div class="container">
	<div class="row justify-content-center">
		<div class="col-md-8">
			@if ($errors->any())
				<div class="alert alert-danger">
					<ul class="mb-0">
						@foreach ($errors->all() as $error)
							<li>{{ $error }}</li>
						@endforeach
					</ul>
				</div>
			@endif
			@if (session('success'))
				<div class="alert alert-success">{{ session('success') }}</div>
			@endif
			<form method="POST" action="{{ route('user_fit.pay.store') }}" enctype="multipart/form-data" id="payForm">
				@csrf
				<div class="card  shadow-sm">
					<div class="card-header bg-dark text-white">Registrar Pago</div>
					<div class="card-body bg-white">


						<div class="mb-3">
							<label class="form-label">Tipo de Pago</label>
							<select name="pay_type_id" id="payTypeField" class="form-select" required>
								<option value="">Seleccione tipo de pago</option>
								@foreach($pay_typeSeeder as $type)
									@php
										$normalizedPayTypeName = mb_strtolower(trim((string) $type->name));
										$isCashPayType = str_contains($normalizedPayTypeName, 'efectivo') || str_contains($normalizedPayTypeName, 'efctivo');
									@endphp
									<option
										value="{{ $type->id }}"
										data-is-cash="{{ $isCashPayType ? '1' : '0' }}"
										{{ old('pay_type_id') == $type->id ? 'selected' : '' }}
									>
										{{ $type->name }}
									</option>
								@endforeach
							</select>
						</div>
						<div class="mb-3">
							<label class="form-label">Fecha de Pago</label>
							<input type="date" name="pay_date" class="form-control" value="{{ old('pay_date') }}" required>
						</div>
						<div class="mb-3">
							<label class="form-label">Monto</label>
							<input type="text" name="amount" class="form-control mountFormat" value="{{ old('amount') }}" required>
						</div>
						<div class="mb-3">
							<label class="form-label">Banco</label>
							<select name="bank_id" id="bankField" class="form-select">
								<option value="">Seleccione un banco</option>
								@foreach($banks as $bank)
									<option value="{{ $bank->id }}" {{ old('bank_id') == $bank->id ? 'selected' : '' }}>{{ $bank->name }}</option>
								@endforeach
							</select>
						</div>
						<div class="mb-3">
							<label class="form-label">Referencia</label>
							<input type="text" name="reference" id="referenceField" class="form-control" value="{{ old('reference') }}">
						</div>
						<div class="mb-3">
							<label class="form-label">Cédula/Tarjeta</label>
							<input type="text" name="id_card_number" id="idCardNumberField" class="form-control" value="{{ old('id_card_number') }}">
						</div>
						<div class="mb-3">
							<label class="form-label">Comprobante de Pago (Imagen)</label>
							<input type="file" name="url_pay_imagen" class="form-control" accept="image/*">
							<small class="text-muted">Opcional. Se guarda manteniendo la proporción de la imagen.</small>
						</div>
						<div class="mb-3">
							<label class="form-label">Deudas a Asociar al Pago</label>
							@if(isset($debts) && $debts->count())
							@php
								$totalUserDebt = (float) $debts->sum(function ($sale) {
									return (float) ($sale->debt ?? 0);
								});
								$totalUserAuxDebt = (float) $debts->sum(function ($sale) {
									return (float) ($sale->aux_debt ?? 0);
								});
							@endphp
							<div class="alert alert-warning">
								<div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-2">
									<div class="fw-bold">Deudas pendientes</div>
									<div class="debt-summary-totals">
										<div>
											<strong>Total:</strong>
											<span id="userTotalDebtValue">{{ number_format($totalUserDebt, 2, ',', '.') }}</span>
										</div>
										<div>
											<strong>Total Ref:</strong>
											<span id="userTotalAuxDebtValue" class="fw-bold">{{ number_format($totalUserAuxDebt, 2, ',', '.') }}</span>
										</div>
									</div>
								</div>
								<div class="small text-dark mb-3" id="paymentAllocationSummary">
									Asignado: <span id="paymentAssignedTotal" class="fw-bold">0,00</span>
									| Restante: <span id="paymentRemainingTotal" class="fw-bold">0,00</span>
								</div>
								@foreach($debts as $sale)
									<div class="debt-card mb-2">
										<div class="row g-2 align-items-end mb-2">
											<div class="col-md-8">
												<div class="form-check">
													<input
														class="form-check-input"
														type="checkbox"
														name="sale_ids[]"
														value="{{ $sale->id }}"
														data-debt="{{ (float) ($sale->debt ?? 0) }}"
														data-aux-debt="{{ (float) ($sale->aux_debt ?? 0) }}"
														id="sale_{{ $sale->id }}"
														data-sale-checkbox="1"
														{{ in_array($sale->id, old('sale_ids', [])) ? 'checked' : '' }}
													>
													<label class="form-check-label fw-bold" for="sale_{{ $sale->id }}">
														Venta #{{ $sale->id }}
													</label>
												</div>
												<div class="debt-meta">
													<span class="debt-chip">
														<strong>Deuda:</strong>
														{{ number_format((float) ($sale->debt ?? 0), 2, ',', '.') }}
													</span>
													<span class="debt-chip">
														<strong>Resto:</strong>
														<span
															id="sale_remaining_{{ $sale->id }}"
															data-sale-remaining="1"
															data-sale-id="{{ $sale->id }}"
															data-debt="{{ (float) ($sale->debt ?? 0) }}"
															class="fw-bold"
														>
															{{ number_format((float) ($sale->debt ?? 0), 2, ',', '.') }}
														</span>
													</span>
												</div>
											</div>
											<div class="col-md-4">
												<label class="form-label mb-1 small" for="sale_amount_{{ $sale->id }}">Monto a abonar</label>
												<input
													type="text"
													name="sale_amounts[{{ $sale->id }}]"
													id="sale_amount_{{ $sale->id }}"
													class="form-control form-control-sm mountFormat"
													data-sale-amount="1"
													data-sale-id="{{ $sale->id }}"
													data-max-debt="{{ (float) ($sale->debt ?? 0) }}"
													value="{{ old('sale_amounts.' . $sale->id, number_format((float) ($sale->debt ?? 0), 2, ',', '.')) }}"
													placeholder="0,00"
												>
												<div class="valid-feedback">Monto valido para esta deuda.</div>
												<div class="invalid-feedback">El monto no puede ser mayor a la deuda pendiente.</div>
											</div>
										</div>
										<ul class="debt-detail-list">
											@foreach($sale->saleDetails as $detail)
												<li>
													@if($detail->product_id)
														Producto: {{ $detail->product->product_name ?? 'Producto no disponible' }}
													@elseif($detail->membership_user_id)
														Membresia: {{ $detail->membershipUser->membership->name ?? 'Membresia no disponible' }}
													@endif
													| Cant: {{ $detail->quantity }}
													| Subtotal: {{ number_format((float) ($detail->subtotal ?? 0), 2, ',', '.') }}
												</li>
											@endforeach
										</ul>
									</div>
								@endforeach
							</div>
							<div class="small text-danger mt-2 d-none" id="debtValidationMessage"></div>
							@else
								<div class="alert alert-light mb-0">No tienes deudas pendientes para asociar.</div>
						@endif
						</div>
						<div class="d-flex justify-content-end">
							<button type="submit" class="btn btn-success">Guardar</button>
						</div>
					</div>
				</div>
			</form>
		</div>
		<div class="col-md-4">
			<div class="card mb-3  shadow-sm">
				<div class="card-header bg-info text-white">Ayuda por Campo</div>
				<div class="card-body small bg-white">
					<p class="mb-2"><strong>Tipo de Pago:</strong> ID o nombre del tipo de pago (transferencia, efectivo, etc).</p>
					<p class="mb-2"><strong>Usuario:</strong> ID del usuario que realiza el pago.</p>
					<p class="mb-2"><strong>Fecha de Pago:</strong> Fecha en que se realizó el pago.</p>
					<p class="mb-2"><strong>Monto:</strong> Monto total pagado.</p>
					<p class="mb-2"><strong>Banco:</strong> Banco desde donde se realizó el pago (opcional).</p>
					<p class="mb-2"><strong>Referencia:</strong> Número de referencia bancaria (opcional).</p>
					<p class="mb-2"><strong>Cédula/Tarjeta:</strong> Número de documento o tarjeta asociado al pago (opcional).</p>
					<p class="mb-2"><strong>Comprobante:</strong> Imagen del pago (opcional).</p>
					<p class="mb-2"><strong>Estado:</strong> Estado del pago (pendiente, aprobado, rechazado).</p>
				</div>
			</div>
		</div>
	</div>
</div>
@endsection

<script>
document.addEventListener('DOMContentLoaded', function () {
	const form = document.getElementById('payForm');
	if (!form) {
		return;
	}

	const paymentAmountInput = form.querySelector('input[name="amount"]');
	const payTypeSelect = form.querySelector('#payTypeField');
	const bankField = form.querySelector('#bankField');
	const referenceField = form.querySelector('#referenceField');
	const idCardNumberField = form.querySelector('#idCardNumberField');
	const debtCheckboxes = Array.from(form.querySelectorAll('input[data-sale-checkbox="1"]'));
	const debtAmountInputs = Array.from(form.querySelectorAll('input[data-sale-amount="1"]'));
	const debtRemainingSpans = Array.from(form.querySelectorAll('span[data-sale-remaining="1"]'));
	const messageBox = document.getElementById('debtValidationMessage');
	const paymentAssignedTotal = document.getElementById('paymentAssignedTotal');
	const paymentRemainingTotal = document.getElementById('paymentRemainingTotal');
	const userTotalDebtValue = document.getElementById('userTotalDebtValue');
	const userTotalAuxDebtValue = document.getElementById('userTotalAuxDebtValue');

	function parseLocalizedNumber(value) {
		if (value === null || value === undefined) {
			return 0;
		}

		let raw = String(value).trim();
		if (raw === '') {
			return 0;
		}

		raw = raw.replace(/\s+/g, '');
		const hasComma = raw.includes(',');
		const hasDot = raw.includes('.');

		if (hasComma && hasDot) {
			if (raw.lastIndexOf(',') > raw.lastIndexOf('.')) {
				raw = raw.replace(/\./g, '').replace(',', '.');
			} else {
				raw = raw.replace(/,/g, '');
			}
		} else if (hasComma) {
			raw = raw.replace(/\./g, '').replace(',', '.');
		} else {
			raw = raw.replace(/,/g, '');
		}

		const parsed = Number(raw);
		return Number.isFinite(parsed) ? parsed : 0;
	}

	function setMessage(text) {
		if (!messageBox) {
			return;
		}

		if (text) {
			messageBox.textContent = text;
			messageBox.classList.remove('d-none');
		} else {
			messageBox.textContent = '';
			messageBox.classList.add('d-none');
		}
	}

	function formatLocalizedNumber(value) {
		const numeric = Number(value);
		if (!Number.isFinite(numeric)) {
			return '0,00';
		}

		return numeric.toLocaleString('es-VE', {
			minimumFractionDigits: 2,
			maximumFractionDigits: 2,
		});
	}

	function isCashPaymentSelected() {
		if (!payTypeSelect) {
			return false;
		}

		const selectedOption = payTypeSelect.options[payTypeSelect.selectedIndex];
		if (!selectedOption) {
			return false;
		}

		return selectedOption.getAttribute('data-is-cash') === '1';
	}

	function syncPaymentMethodFieldRequirements() {
		const isCashPayment = isCashPaymentSelected();
		const optionalFields = [bankField, referenceField, idCardNumberField].filter(Boolean);

		optionalFields.forEach(function (field) {
			field.disabled = isCashPayment;
			field.required = !isCashPayment;
			if (isCashPayment) {
				field.value = '';
			}
		});
	}

	function updateSingleRemaining(saleId) {
		const checkbox = form.querySelector('input[data-sale-checkbox="1"][value="' + saleId + '"]');
		const amountInput = form.querySelector('input[name="sale_amounts[' + saleId + ']"]');
		const remainingSpan = form.querySelector('span[data-sale-remaining="1"][data-sale-id="' + saleId + '"]');

		if (!remainingSpan) {
			return;
		}

		const maxDebt = Number(remainingSpan.getAttribute('data-debt')) || 0;
		const selectedAmount = checkbox && checkbox.checked
			? parseLocalizedNumber(amountInput ? amountInput.value : 0)
			: 0;
		const remaining = Math.max(0, maxDebt - selectedAmount);
		remainingSpan.textContent = formatLocalizedNumber(remaining);
	}

	function updateAllRemaining() {
		debtRemainingSpans.forEach(function (remainingSpan) {
			const saleId = remainingSpan.getAttribute('data-sale-id');
			if (!saleId) {
				return;
			}
			updateSingleRemaining(saleId);
		});
	}

	function getPaymentAmount() {
		return parseLocalizedNumber(paymentAmountInput ? paymentAmountInput.value : 0);
	}

	function shouldEnableDebtAmounts() {
		return getPaymentAmount() > 0;
	}

	function syncDebtAmountsEnabledState() {
		const enabled = shouldEnableDebtAmounts();

		debtAmountInputs.forEach(function (amountInput) {
			amountInput.disabled = !enabled;
			if (!enabled) {
				amountInput.classList.remove('is-valid');
				amountInput.classList.remove('is-invalid');
			}
		});

		if (!enabled) {
			setMessage('Primero debes ingresar el monto del pago para habilitar los montos por deuda.');
		}
	}

	function getCheckedAmountTotal() {
		return debtCheckboxes.reduce(function (total, checkbox) {
			if (!checkbox.checked) {
				return total;
			}

			const saleId = checkbox.value;
			const amountInput = form.querySelector('input[name="sale_amounts[' + saleId + ']"]');
			const currentAmount = parseLocalizedNumber(amountInput ? amountInput.value : 0);
			return total + currentAmount;
		}, 0);
	}

	function updatePaymentAllocationSummary() {
		if (!paymentAssignedTotal || !paymentRemainingTotal) {
			return;
		}

		const paymentAmount = getPaymentAmount();
		const selectedTotal = getCheckedAmountTotal();
		const remaining = Math.max(0, paymentAmount - selectedTotal);

		paymentAssignedTotal.textContent = formatLocalizedNumber(selectedTotal);
		paymentRemainingTotal.textContent = formatLocalizedNumber(remaining);
	}

	function updateAuxDebtSummary() {
		if (!userTotalAuxDebtValue) {
			return;
		}

		const totalAuxDebtRemaining = debtCheckboxes.reduce(function (total, checkbox) {
			const maxDebt = Number(checkbox.getAttribute('data-debt')) || 0;
			const auxDebt = Number(checkbox.getAttribute('data-aux-debt')) || 0;

			if (!checkbox.checked) {
				return total + auxDebt;
			}

			const saleId = checkbox.value;
			const amountInput = form.querySelector('input[name="sale_amounts[' + saleId + ']"]');
			const selectedAmount = parseLocalizedNumber(amountInput ? amountInput.value : 0);
			const clampedAmount = Math.min(Math.max(selectedAmount, 0), maxDebt);
			const auxDiscount = maxDebt > 0 ? (clampedAmount * auxDebt) / maxDebt : 0;
			const remainingAux = Math.max(0, auxDebt - auxDiscount);

			return total + remainingAux;
		}, 0);

		userTotalAuxDebtValue.textContent = formatLocalizedNumber(totalAuxDebtRemaining);
	}

	function updateDebtSummary() {
		if (!userTotalDebtValue) {
			return;
		}

		const totalDebtRemaining = debtCheckboxes.reduce(function (total, checkbox) {
			const maxDebt = Number(checkbox.getAttribute('data-debt')) || 0;

			if (!checkbox.checked) {
				return total + maxDebt;
			}

			const saleId = checkbox.value;
			const amountInput = form.querySelector('input[name="sale_amounts[' + saleId + ']"]');
			const selectedAmount = parseLocalizedNumber(amountInput ? amountInput.value : 0);
			const clampedAmount = Math.min(Math.max(selectedAmount, 0), maxDebt);
			const remainingDebt = Math.max(0, maxDebt - clampedAmount);

			return total + remainingDebt;
		}, 0);

		userTotalDebtValue.textContent = formatLocalizedNumber(totalDebtRemaining);
	}

	function validateSingleDebtAmount(amountInput) {
		const maxDebt = Number(amountInput.getAttribute('data-max-debt')) || 0;
		const currentAmount = parseLocalizedNumber(amountInput.value);
		const hasValue = String(amountInput.value || '').trim() !== '';

		if (hasValue && currentAmount > maxDebt) {
			amountInput.classList.remove('is-valid');
			amountInput.classList.add('is-invalid');
			setMessage('No puedes colocar un monto mayor que la deuda pendiente de esa venta.');
			return false;
		}

		amountInput.classList.remove('is-invalid');
		if (hasValue) {
			amountInput.classList.add('is-valid');
		} else {
			amountInput.classList.remove('is-valid');
		}
		return true;
	}

	function validateGlobalTotals() {
		const paymentAmount = getPaymentAmount();
		const selectedTotal = getCheckedAmountTotal();

		if (selectedTotal > paymentAmount) {
			setMessage('La suma de las deudas seleccionadas no puede ser mayor al monto del pago.');
			return false;
		}

		return true;
	}

	function validateAll() {
		let valid = true;

		syncDebtAmountsEnabledState();
		if (!shouldEnableDebtAmounts()) {
			return true;
		}

		debtAmountInputs.forEach(function (amountInput) {
			if (!validateSingleDebtAmount(amountInput)) {
				valid = false;
			}
		});

		if (!validateGlobalTotals()) {
			valid = false;
		}

		if (valid) {
			setMessage('');
		}

		return valid;
	}

	debtAmountInputs.forEach(function (amountInput) {
		amountInput.addEventListener('input', function () {
			validateAll();
			updatePaymentAllocationSummary();
			updateDebtSummary();
			updateAuxDebtSummary();
			const saleId = amountInput.getAttribute('data-sale-id');
			if (saleId) {
				updateSingleRemaining(saleId);
			}
		});
		amountInput.addEventListener('blur', function () {
			validateAll();
			updatePaymentAllocationSummary();
			updateDebtSummary();
			updateAuxDebtSummary();
			const saleId = amountInput.getAttribute('data-sale-id');
			if (saleId) {
				updateSingleRemaining(saleId);
			}
		});
	});

	debtCheckboxes.forEach(function (checkbox) {
		checkbox.addEventListener('change', function (event) {
			const saleId = checkbox.value;
			const amountInput = form.querySelector('input[name="sale_amounts[' + saleId + ']"]');

			if (checkbox.checked) {
				const maxDebt = Number(checkbox.getAttribute('data-debt')) || 0;
				const selectedAmount = parseLocalizedNumber(amountInput ? amountInput.value : 0);

				if (selectedAmount > maxDebt) {
					checkbox.checked = false;
					if (amountInput) {
						amountInput.classList.add('is-invalid');
					}
					setMessage('No puedes seleccionar una deuda con monto superior a su saldo pendiente.');
					event.preventDefault();
					return;
				}

				const paymentAmount = getPaymentAmount();
				const selectedTotal = getCheckedAmountTotal();
				if (selectedTotal > paymentAmount) {
					checkbox.checked = false;
					setMessage('No puedes seleccionar esa deuda porque supera el monto total del pago.');
					event.preventDefault();
					return;
				}
			}

			validateAll();
			updateSingleRemaining(saleId);
			updatePaymentAllocationSummary();
			updateDebtSummary();
			updateAuxDebtSummary();
		});
	});

	if (paymentAmountInput) {
		paymentAmountInput.addEventListener('input', function () {
			syncDebtAmountsEnabledState();
			validateAll();
			updatePaymentAllocationSummary();
			updateDebtSummary();
			updateAuxDebtSummary();
		});
		paymentAmountInput.addEventListener('blur', function () {
			syncDebtAmountsEnabledState();
			validateAll();
			updatePaymentAllocationSummary();
			updateDebtSummary();
			updateAuxDebtSummary();
		});
	}

	if (payTypeSelect) {
		payTypeSelect.addEventListener('change', function () {
			syncPaymentMethodFieldRequirements();
		});
	}

	form.addEventListener('submit', function (event) {
		if (!validateAll()) {
			event.preventDefault();
		}
	});

	syncDebtAmountsEnabledState();
	syncPaymentMethodFieldRequirements();
	validateAll();
	updateAllRemaining();
	updatePaymentAllocationSummary();
	updateDebtSummary();
	updateAuxDebtSummary();
});
</script>