@extends('layouts.app')
@section('content')
<div class="container">
	<div class="row justify-content-center">
		<div class="col-md-12">
			@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

			<div class="card">
				<div class="card-header d-flex justify-content-between align-items-center">
					<span>Registrar Tasa</span>
					<a href="{{ !empty($returnTo) ? $returnTo : route('home') }}" class="btn btn-sm btn-secondary">
					<i class="bi bi-chevron-left"></i>
					Volver</a>
				</div>
				<div class="card-body">
					<form method="POST" action="{{ route('admin_fit.rate.store') }}" id="rate-form">
						@csrf
						<input type="hidden" name="return_to" value="{{ old('return_to', $returnTo) }}">
						<div class="row g-3">
							<div class="col-md-6">
								<label for="usd_rate" class="form-label">Tasa USD</label>
								<input
									type="text"
									name="usd_rate"
									id="usd_rate"
									class="form-control"
									value="{{ old('usd_rate') }}"
									placeholder="Ej: 1.234,5678"
									inputmode="decimal"
									autocomplete="off"
									required
								>
								<small class="text-muted">Use punto para miles y coma para decimales. Máximo 4 decimales.</small>
							</div>
							<div class="col-12">
								<div class="form-check">
									<input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" {{ old('is_active', true) ? 'checked' : '' }}>
									<label class="form-check-label" for="is_active">Dejar como tasa activa</label>
								</div>
							</div>
						</div>

						<div class="d-flex justify-content-end mt-4">
							<button type="submit" class="btn btn-success">Guardar</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
	const input = document.getElementById('usd_rate');
	const form = document.getElementById('rate-form');
	let isConfirmedSubmit = false;

	if (!input || !form) {
		return;
	}

	const keepAllowedChars = (value) => value.replace(/[^\d,]/g, '');

	const formatRateEs = (value) => {
		const cleaned = keepAllowedChars(value);
		const parts = cleaned.split(',');
		const hasComma = cleaned.includes(',');
		const integerRaw = (parts[0] || '').replace(/^0+(?=\d)/, '');
		const integerPart = integerRaw.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
		const decimalPart = parts.slice(1).join('').slice(0, 4);

		if (decimalPart.length > 0) {
			return `${integerPart || '0'},${decimalPart}`;
		}

		if (hasComma) {
			return `${integerPart || '0'},`;
		}

		return integerPart;
	};

	const toBackendDecimal = (value) => {
		if (!value) {
			return '';
		}

		return value.replace(/\./g, '').replace(',', '.');
	};

	const validateRate = () => {
		const formatted = input.value.trim();
		const normalized = toBackendDecimal(formatted);
		const numericValue = Number(normalized);
		const regex = /^\d+(\.\d{1,4})?$/;

		if (!formatted || !regex.test(normalized) || Number.isNaN(numericValue) || numericValue <= 0) {
			input.setCustomValidity('Ingrese una tasa válida con formato 1.234,5678 (máximo 4 decimales).');
			return false;
		}

		input.setCustomValidity('');
		return true;
	};

	input.addEventListener('input', function () {
		input.value = formatRateEs(input.value);
		validateRate();
	});

	input.addEventListener('blur', function () {
		input.value = formatRateEs(input.value);
		validateRate();
	});

	form.addEventListener('submit', async function (event) {
		if (isConfirmedSubmit) {
			return;
		}

		event.preventDefault();
		event.stopPropagation();

		input.value = formatRateEs(input.value);

		if (!validateRate()) {
			event.preventDefault();
			event.stopPropagation();
			input.reportValidity();
			return;
		}

		const rateToConfirm = input.value.trim();
		let confirmed = false;

		if (typeof Swal !== 'undefined' && typeof Swal.fire === 'function') {
			const result = await Swal.fire({
				title: 'Confirmar registro',
				html: `Se guardará la siguiente tasa:<br><strong>${rateToConfirm}</strong>`,
				icon: 'question',
				showCancelButton: true,
				confirmButtonText: 'Sí, guardar',
				cancelButtonText: 'Cancelar',
				reverseButtons: true,
				allowOutsideClick: true
			});
			confirmed = result.isConfirmed;
		} else {
			confirmed = window.confirm(`¿Deseas guardar esta tasa?\n\nTasa: ${rateToConfirm}`);
		}

		if (!confirmed) {
			return;
		}

		input.value = toBackendDecimal(input.value);
		isConfirmedSubmit = true;
		form.submit();
	});

	if (input.value) {
		input.value = formatRateEs(input.value);
	}
});
</script>
@endpush