@extends('layouts.yellow')

@push('styles')
<style>
    .payment-card {
        border: none;
        border-radius: 12px;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.08);
        overflow: hidden;
        transition: transform 0.2s ease-in-out;
    }
    
    .payment-card:hover {
        transform: translateY(-2px);
    }
    
    .card-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        border-bottom: none;
        color: white;
    }
    
    .card-header h1, 
    .card-header h2, 
    .card-header h3, 
    .card-header h4, 
    .card-header h5, 
    .card-header h6,
    .card-header .fa-credit-card,
    .card-header p,
    .card-header .opacity-75 {
        color: white !important;
        opacity: 1 !important;
    }
    
    .section-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #4e73df;
        border-bottom: 2px solid #e3e6f0;
        padding-bottom: 0.5rem;
        margin-bottom: 1.5rem;
    }
    
    .form-label {
        font-weight: 600;
        color: #5a5c69;
        margin-bottom: 0.5rem;
    }
    
    .form-control, .form-select {
        border: 1px solid #d1d3e2;
        border-radius: 0.5rem;
        padding: 0.65rem 1rem;
        transition: border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #bac8f3;
        box-shadow: 0 0 0 0.25rem rgba(78, 115, 223, 0.25);
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        border: none;
        padding: 0.65rem 1.5rem;
        font-weight: 600;
        border-radius: 0.5rem;
        transition: all 0.2s ease-in-out;
    }
    
    .btn-primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    
    .payment-summary {
        background-color: #f8f9fc;
        border-radius: 0.5rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .payment-detail {
        display: flex;
        justify-content: space-between;
        margin-bottom: 0.75rem;
        padding-bottom: 0.75rem;
        border-bottom: 1px solid #e3e6f0;
    }
    
    .payment-detail:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }
    
    .payment-detail.total {
        font-size: 1.1rem;
        font-weight: 600;
        color: #2e59d9;
    }
    
    .service-badge {
        background-color: #e3e6f0;
        color: #4e73df;
        padding: 0.5rem 1rem;
        border-radius: 50px;
        margin-right: 0.5rem;
        margin-bottom: 0.5rem;
        display: inline-flex;
        align-items: center;
    }
    
    .service-badge .btn-close {
        margin-left: 0.5rem;
        font-size: 0.65rem;
        opacity: 0.7;
    }
    
    .service-badge .btn-close:hover {
        opacity: 1;
    }
    
    .reference-field {
        display: none;
        animation: fadeIn 0.3s ease-in-out;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .additional-payment {
        border-left: 3px solid #4e73df;
        padding-left: 1rem;
        margin-left: 0.5rem;
    }
    
    .additional-payment-detail {
        background-color: #f0f4ff;
        border-radius: 0.5rem;
        padding: 1rem;
        margin-bottom: 1rem;
    }
    
    .nav-tabs .nav-link {
        border: none;
        border-bottom: 3px solid transparent;
        color: #5a5c69;
        padding: 0.75rem 1.5rem;
        font-weight: 600;
        transition: all 0.2s ease;
    }
    
    .nav-tabs .nav-link.active {
        color: #4e73df;
        border-bottom-color: #4e73df;
        background-color: transparent;
    }
    
    .nav-tabs .nav-link:hover:not(.active) {
        color: #4e73df;
        border-bottom-color: #e9ecef;
    }
    
    .tab-content {
        padding: 1.5rem 0;
    }
    
    /* Nuevos estilos para referencia en móviles */
    .reference-field {
        word-wrap: break-word;
        overflow-wrap: break-word;
        max-width: 100%;
    }
    
    @media (max-width: 768px) {
        .reference-field {
            white-space: normal;
            word-break: break-all;
        }
        
        .reference-container {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .reference-label {
            margin-bottom: 0.25rem;
        }
    }
</style>
@endpush

@section('content')
@if(session()->has('error'))
    <div class="alert alert-danger">
        {{ session('error') }} &nbsp;&nbsp; <a href="{{ route('/admin/create-appointment') }}" class="btn btn-primary">  {{ __('common.backAppointment') }}</a>
    </div>
@endif
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-12 col-lg-10">
            <div class="card payment-card">
                <div class="card-header text-white py-4">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-credit-card me-3" style="font-size: 1.75rem;"></i>
                        <div>
                            <h1 class="h4 mb-0 fw-bold">{{ __('common.paymentForAppointment') }}</h1>
                            <p class="mb-0 opacity-75">{{ __('Complete los detalles del pago') }}</p>
                        </div>
                    </div>
                </div>

                <div class="card-body p-4 p-md-5">
                    <!-- Información de la cita (siempre visible) -->
                    <div class="alert bg-light-primary border-0 mb-4">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-calendar-check me-3" style="font-size: 1.5rem;"></i>
                            <div>
                                <h5 class="mb-1 fw-bold">{{ __('common.appointmentDetails') }}</h5>
                                <div class="row mt-2">
                                    <div class="col-md-6">
                                        <p class="mb-1"><i class="fas fa-user me-2 text-primary"></i> {{ $patient->firstname }} {{ $patient->lastname }}</p>
                                        <p class="mb-1"><i class="fas fa-user-md me-2 text-primary"></i> {{ $doctor->name }}</p>
                                    </div>
                                    <div class="col-md-6">
                                        <p class="mb-1"><i class="far fa-calendar-alt me-2 text-primary"></i> {{ \Carbon\Carbon::parse($appointmentData['date'])->format('d/m/Y') }}</p>
                                        <p class="mb-0"><i class="far fa-clock me-2 text-primary"></i> {{ \Carbon\Carbon::parse($appointmentData['date'])->format('h:i A') }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    @if(isset($isChildPayment) && $isChildPayment)
                    <!-- Pestañas solo para pagos hijos -->
                    <ul class="nav nav-tabs mb-4" id="paymentTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summary" type="button" role="tab" aria-controls="summary" aria-selected="true">
                                <i class="fas fa-receipt me-2"></i> Resumen de Pagos
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="form-tab" data-bs-toggle="tab" data-bs-target="#form" type="button" role="tab" aria-controls="form" aria-selected="false">
                                <i class="fas fa-credit-card me-2"></i> Realizar Pago
                            </button>
                        </li>
                    </ul>
                    
                    <div class="tab-content" id="paymentTabsContent">
                        <!-- Pestaña de Resumen -->
                        <div class="tab-pane fade show active" id="summary" role="tabpanel" aria-labelledby="summary-tab">
                            <!-- Contenido del resumen para pagos hijos -->
                            <!-- Resumen de Pagos -->
                            <div class="payment-summary mb-4">
                                <h5 class="section-title"><i class="fas fa-receipt me-2"></i> Resumen de Pagos</h5>
                                
                                <!-- Pago Principal -->
                                <div class="mb-3">
                                    <h6 class="fw-bold mb-2"><i class="fas fa-file-invoice-dollar me-2 text-primary"></i>Pago Principal</h6>
                                    <div class="payment-detail">
                                        <span>Monto:</span>
                                        <span class="fw-medium">{{ number_format($parentPayment->amount, 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                    </div>
                                    <div class="payment-detail">
                                        <span>Referencia:</span>
                                        <span class="text-muted">{{ $parentPayment->reference }}</span>
                                    </div>
                                </div>
                                
                                <!-- Pagos Adicionales -->
                                @if($parentPayment->children->isNotEmpty())
                                    <div class="mb-3">
                                        <h6 class="fw-bold mb-2"><i class="fas fa-plus-circle me-2 text-info"></i>Pagos Adicionales ({{ $parentPayment->children->count() }})</h6>
                                        @foreach($parentPayment->children as $childPayment)
                                            <div class="additional-payment-detail mb-2">
                                                <div class="d-flex justify-content-between">
                                                    <span>Monto:</span>
                                                    <span class="fw-medium">{{ number_format($childPayment->amount, 2) }} {{ $childPayment->currency->code ?? '' }}</span>
                                                </div>
                                                <div class="d-flex justify-content-between">
                                                    <span>Referencia:</span>
                                                    <span class="text-muted">{{ $childPayment->reference }}</span>
                                                </div>
                                            </div>
                                        @endforeach
                                        <div class="payment-detail fw-bold">
                                            <span>Total Pagos Adicionales:</span>
                                            <span class="text-primary">{{ number_format($parentPayment->children->sum('amount'), 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                        </div>
                                    </div>
                                @endif
                                
                                <!-- Resumen -->
                                <div class="mt-4 pt-3 border-top">
                                    <div class="payment-detail">
                                        <span>Total Servicios:</span>
                                        <span class="fw-medium">{{ number_format($parentPayment->medicalServices->sum('cost'), 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                    </div>
                                    <div class="payment-detail">
                                        <span>Total Pagado:</span>
                                        <span class="fw-medium text-success">{{ number_format($parentPayment->amount + $parentPayment->children->sum('amount'), 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                    </div>
                                    <div class="payment-detail total">
                                        <span>Saldo Pendiente:</span>
                                        <span class="text-danger">{{ number_format($remainingDebt, 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Pestaña de Formulario -->
                        <div class="tab-pane fade" id="form" role="tabpanel" aria-labelledby="form-tab">
                            <!-- Formulario de Pago -->
                            <form name="payment-form" id="payment-form" action="{{ route('admin.payments.additional', $parentPayment->id) }}" method="POST" autocomplete="off">
                    @else
                    <!-- Formulario para pagos principales -->
                    <form name="payment-form" id="payment-form" action="/admin/complete-payment-individual" method="POST" autocomplete="off">
                    @endif
                                @csrf
                                @if(isset($isChildPayment) && $isChildPayment)
                                    <input type="hidden" name="parent_payment_id" value="{{ $parentPayment->id }}">
                                    <input type="hidden" name="is_child_payment" value="1">
                                @endif
                                <input type="hidden" name="appointment_id" value="{{ $appointmentData['id'] }}">
                                
                                @if(isset($isChildPayment) && $isChildPayment)
                                <!-- Mostrar resumen de pagos existentes -->
                                <div class="row mb-4">
                                    <div class="col-12">
                                        <div class="card">
                                            <div class="card-header bg-light">
                                                <h5 class="mb-0">{{ __('Resumen de Pagos') }}</h5>
                                            </div>
                                            <div class="card-body">
                                                <!-- Pago Principal -->
                                                <div class="mb-3">
                                                    <h6>Pago Principal</h6>
                                                    <div class="d-flex justify-content-between">
                                                        <span>Monto:</span>
                                                        <span>{{ number_format($parentPayment->amount, 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between">
                                                        <span>Referencia:</span>
                                                        <span>{{ $parentPayment->reference }}</span>
                                                    </div>
                                                </div>
                                                
                                                <!-- Pagos Adicionales -->
                                                @if($parentPayment->children->isNotEmpty())
                                                    <div class="mb-3">
                                                        <h6>Pagos Adicionales ({{ $parentPayment->children->count() }})</h6>
                                                        @foreach($parentPayment->children as $childPayment)
                                                            <div class="ps-3 mb-2 border-start border-2 border-light">
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Monto:</span>
                                                                    <span>{{ number_format($childPayment->amount, 2) }} {{ $childPayment->currency->code ?? '' }}</span>
                                                                </div>
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Referencia:</span>
                                                                    <span>{{ $childPayment->reference }}</span>
                                                                </div>
                                                            </div>
                                                        @endforeach
                                                        <div class="d-flex justify-content-between fw-bold">
                                                            <span>Total Pagos Adicionales:</span>
                                                            <span>{{ number_format($parentPayment->children->sum('amount'), 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                                        </div>
                                                    </div>
                                                @endif
                                                
                                                <!-- Resumen -->
                                                <div class="border-top pt-2 mt-2">
                                                    <div class="d-flex justify-content-between">
                                                        <span class="fw-bold">Total Servicios:</span>
                                                        <span class="fw-bold">{{ number_format($parentPayment->medicalServices->sum('cost'), 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between">
                                                        <span class="fw-bold">Total Pagado:</span>
                                                        <span class="fw-bold">{{ number_format($parentPayment->amount + $parentPayment->children->sum('amount'), 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between">
                                                        <span class="fw-bold">Saldo Pendiente:</span>
                                                        <span class="fw-bold text-danger">{{ number_format($remainingDebt, 2) }} {{ $parentPayment->currency->code ?? '' }}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                @endif
                                <div class="row">
                                    <div class="col-12">
                                        <div class="p-2">
                                            <label for="payer">{{ __('com-form-payment.payer') }}</label>
                                            <input type="text" name="payer" class="form-control" value="{{ $patient->firstname }} {{ $patient->lastname }}">
                                        </div>
                                    </div>
                                </div>
                                @if(!isset($isChildPayment) || !$isChildPayment)
                                <div class="row mb-4">
                                    <div class="col-12">
                                        <h5 class="section-title"><i class="fas fa-procedures me-2"></i> Servicios Médicos</h5>
                                        @if(isset($isChildPayment) && $isChildPayment)
                                            <div class="alert alert-info">
                                                <i class="fas fa-info-circle me-2"></i>
                                                Los servicios médicos se heredan del pago principal y no pueden ser modificados.
                                            </div>
                                            <div class="d-flex flex-wrap mt-3">
                                                @foreach($parentPayment->medicalServices as $service)
                                                    <span class="service-badge">
                                                        {{ $service->name }}
                                                        <span class="ms-2">{{ number_format($service->cost, 2) }} {{ $service->currency->title ?? 'USD' }}</span>
                                                        <input type="hidden" name="medical_services[]" value="{{ $service->id }}">
                                                    </span>
                                                @endforeach
                                            </div>
                                        @else
                                            <div class="mb-3">
                                                <label for="medical_services" class="form-label">{{ __('com-form-payment.medicalServices') }}</label>
                                                <select class="form-select" id="medical_services">
                                                    <option value="">{{ __('Seleccione un servicio') }}</option>
                                                    @foreach($medicalServices as $service)
                                                        <option value="{{ $service->id }}" data-cost="{{ $service->cost }}">
                                                            {{ $service->name }} - {{ number_format($service->cost, 2) }} {{ $service->currency->title ?? 'USD' }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                <div id="selected-services" class="mt-3 d-flex flex-wrap">
                                                    <!-- Los servicios seleccionados aparecerán aquí -->
                                                </div>
                                            </div>
                                        @endif
                                    </div>
                                </div>
                                <div class="row mb-4">
                                    <div class="col-12">
                                        <label for="total_amount">{{ __('com-form-payment.totalAmount') }}</label>
                                        <input type="text" name="total_amount" id="total_amount" class="form-control" readonly>
                                    </div>
                                </div>
                                @endif
                                <div class="row">
                                    <div class="col-12 col-lg-3 col-md-3">
                                        <div class="p-2">
                                            <label for="currency">{{ __('com-form-payment.currency') }}</label>
                                            <select class="form-control" name="currency" id="currency" required>
                                                <option value="">{{ __('com-form-history.selectValue') }}</option>
                                                @foreach($currencies as $option)
                                                    <option value="{{ $option->id }}" {{ (isset($parentCurrency) && $option->id == $parentCurrency->id) ? 'selected' : '' }}>
                                                        {{ $option->title }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-12 col-lg-6 col-md-6">
                                        <div class="p-2">
                                            <label for="amount">{{ __('com-form-payment.amount') }}</label>
                                            <input type="text" name="amount" id="amount" class="form-control" required>
                                        </div>
                                    </div>
                                    <div class="col-12 col-lg-3 col-md-3">
                                        <div class="p-2">
                                            <label for="paymentMethods">{{ __('com-form-payment.method') }}</label>
                                            <select class="form-control" name="paymentMethods" id="paymentMethods" required>
                                                <option value="">{{ __('com-form-history.selectValue') }}</option>
                                                @foreach($paymentMethods as $option)
                                                    <option value="{{ $option->id }}">{{ $option->title }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row mt-2">
                                    <div class="col-12 col-lg-4 col-md-4">
                                        <div class="p-3 form-check ps-4">
                                            <input type="checkbox" name="is_electronic" id="is_electronic" class="form-check-input" onchange="toggleReferenceField()">
                                            <label for="is_electronic" class="form-check-label">{{ __('com-form-payment.isElectronic') }}</label>
                                        </div>
                                    </div>
                                    <div class="col-12 col-lg-8 col-md-8" id="user_reference_container" style="display: none;">
                                        <div class="p-2">
                                            <label for="user_reference">{{ __('com-form-payment.userReference') }} <span class="text-danger">*</span></label>
                                            <input type="text" name="user_reference" id="user_reference" class="form-control">
                                            <small class="text-muted">{{ __('com-form-payment.userReferenceHelp') }}</small>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-12">
                                        <div class="p-2">
                                            <label for="address_payer">{{ __('com-form-payment.address') }}</label>
                                            <textarea required name="address_payer" class="form-control" cols="30" rows="5" @if(isset($isChildPayment) && $isChildPayment) readonly @endif>{{ isset($parentAddress) ? $parentAddress : '' }}</textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12  col-lg-6 col-md-6">
                                        <div class="p-2">
                                            <label for="especiality">{{ __('com-form-history.especiality') }}</label>
                                            @if(isset($isChildPayment) && $isChildPayment && isset($parentPayment->especiality_id))
                                                <input type="hidden" name="especiality" value="{{ $parentPayment->especiality_id }}">
                                                <input type="text" class="form-control" value="{{ $parentPayment->especiality->name ?? '' }}" readonly>
                                            @else
                                                <select class="form-control" name="especiality" id="especiality" required>
                                                    <option value="">{{ __('com-form-history.selectValue') }}</option>
                                                    @if(isset($optionsEspeciality))
                                                        @foreach($optionsEspeciality as $key => $option)
                                                            <option value="{{ $key }}" {{ (isset($appointmentData['especiality']) && $appointmentData['especiality'] == $key) ? 'selected' : '' }}>{{ $option }}</option>
                                                        @endforeach
                                                    @endif
                                                </select>
                                            @endif
                                        </div>
                                    </div>
                                    <div class="col-12 col-lg-6 col-md-6">
                                        <div class="p-2">
                                            <label for="doctors">{{ __('com-form-payment.doctor') }}</label>
                                            @if(isset($doctors))
                                                <select class="form-control" name="doctors" id="doctors" required>
                                                    <option value="">{{ __('com-form-history.selectValue') }}</option>
                                                    @foreach($doctors as $option)
                                                        <option value="{{ $option->id }}" {{ $appointmentData['users_id'] == $option->id ? 'selected' : '' }}>{{ $option->name }}</option>
                                                    @endforeach
                                                </select>
                                            @endif
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-12">
                                        <div class="p-2">
                                            <label for="reason">{{ __('com-form-payment.reason') }}</label>
                                            <textarea required name="reason" class="form-control" cols="30" rows="5">Pago por cita médica</textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12">
                                        <div class="p-2 text-center">
                                            <button type="submit" class="btn btn-primary px-5" id="payment-form-submit">
                                                <i class="bi bi-check-circle me-2"></i> {{ __('common.completeAppointmentWithPayment') }}
                                            </button>
                                            <a href="{{ route('/admin/create-appointment') }}" class="btn btn-secondary ms-2">
                                                <i class="bi bi-x-circle me-2"></i> {{ __('common.cancel') }}
                                            </a>
                                        </div>
                                    </div>
                                </div>
                    </form>
                    
                    @if(isset($isChildPayment) && $isChildPayment)
                        </div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    // Inicializar tooltips
    document.addEventListener('DOMContentLoaded', function() {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // Inicializar el campo de referencia si ya está marcado como pago electrónico
        if (document.getElementById('is_electronic').checked) {
            document.getElementById('reference_field').style.display = 'block';
        }
    });
    
    // Función para mostrar/ocultar el campo de referencia
    function toggleReferenceField() {
        const isElectronic = document.getElementById('is_electronic').checked;
        const referenceContainer = document.getElementById('user_reference_container');
        const referenceField = document.getElementById('user_reference');
        
        if (isElectronic) {
            referenceContainer.style.display = 'block';
            referenceField.setAttribute('required', 'required');
        } else {
            referenceContainer.style.display = 'none';
            referenceField.removeAttribute('required');
            referenceField.value = '';
        }
    }
    
    // Formatear monto mientras se escribe
    document.getElementById('amount')?.addEventListener('input', function(e) {
        let value = e.target.value.replace(/[^0-9.]/g, '');
        let parts = value.split('.');
        
        if (parts.length > 2) {
            // Si hay más de un punto, eliminar el último
            value = parts[0] + '.' + parts.slice(1).join('');
        }
        
        // Limitar a 2 decimales
        if (parts.length > 1 && parts[1].length > 2) {
            value = parts[0] + '.' + parts[1].substring(0, 2);
        }
        
        e.target.value = value;
    });
    
    // Validar el formulario antes de enviar
    document.getElementById('payment-form')?.addEventListener('submit', function(e) {
        const submitButton = document.getElementById('payment-form-submit');
        const spinner = document.getElementById('submit-spinner');
        
        // Mostrar spinner y deshabilitar botón
        submitButton.disabled = true;
        spinner.classList.remove('d-none');
        
        // Validar monto
        const amountInput = document.getElementById('amount');
        if (amountInput) {
            let amount = parseFloat(amountInput.value.replace(/,/g, ''));
            if (isNaN(amount) || amount <= 0) {
                e.preventDefault();
                alert('Por favor ingrese un monto válido mayor a cero');
                submitButton.disabled = false;
                spinner.classList.add('d-none');
                return false;
            }
        }
        
        // Si es pago electrónico, validar referencia
        const isElectronic = document.getElementById('is_electronic');
        if (isElectronic && isElectronic.checked) {
            const reference = document.getElementById('user_reference')?.value.trim();
            if (!reference) {
                e.preventDefault();
                alert('Por favor ingrese el número de referencia para pagos electrónicos');
                submitButton.disabled = false;
                spinner.classList.add('d-none');
                return false;
            }
        }
        
        return true;
    });
</script>
@endpush

<script>
    // Script para manejar las pestañas
    document.addEventListener('DOMContentLoaded', function() {
        // Activar la primera pestaña por defecto
        new bootstrap.Tab(document.getElementById('summary-tab')).show();
        
        // Validación al cambiar de pestaña
        document.getElementById('form-tab').addEventListener('click', function() {
            // Lógica de validación si es necesario
        });
    });
</script>

<script>
$(document).ready(function() {
    $('#amount').on("keydown",(function(e) {
    var key = e.keyCode || e.charCode;
    // Allow numeric keys, navigation keys, backspace, tab, arrow keys
    // And specifically allow the comma (key 188) for the decimal separator in es-VE
    if ((key >= 48 && key <= 57) || // 0-9
        (key >= 96 && key <= 105) || // Numpad 0-9
        key === 8 || // Backspace
        key === 9 || // Tab
        key === 37 || // Left arrow
        key === 39 || // Right arrow
        key === 188) { // Comma (,) for decimal separator in es-VE
        return true;
    }
    // Prevent other key presses
    e.preventDefault();
    return false;
}));

$("#amount").on("focus", function(e) {
    if (this.value !== "" && this.value !== undefined) {
        // When focusing, only remove thousands separators (dots) for 'es-VE' locale.
        // Keep the decimal comma as is for user editing.
        let valueForEditing = this.value.replace(/\./g, '');

        // Now, parse this string. Since 'es-VE' uses comma as decimal,
        // parseFloat will stop at the comma. We need to handle it.
        // A simple way is to temporarily replace comma with dot for parsing, then convert back if needed.
        let parseableValue = valueForEditing.replace(',', '.');
        let parsedValue = parseFloat(parseableValue);

        if (!isNaN(parsedValue)) {
            // Display the raw numeric value for editing.
            // This time, if it had a decimal, keep the comma.
            // We'll revert to the standard internal number format (dot for decimal) for parseFloat.
            let displayedValue = parsedValue.toFixed(2); // e.g., 2500.85 becomes "2500.85"

            // Now, remove the .00 if it's a whole number and replace . with , for display
            if (displayedValue.endsWith('.00')) {
                this.value = displayedValue.replace('.00', ''); // 2500.00 -> 2500
            } else {
                this.value = displayedValue.replace('.', ','); // 2500.85 -> 2500,85
            }
        } else {
            this.value = "";
        }
    }
});

$("#amount").on("blur", function(e) {
    if (this.value !== "" && this.value !== undefined) {
        // For parsing, remove thousands separators and replace the decimal comma with a dot.
        let cleanedValue = this.value.replace(/\./g, '').replace(',', '.');

        let numericValue = parseFloat(cleanedValue);

        if (!isNaN(numericValue)) {
            // Format the number back to 'es-VE' locale with 2 decimal places
            this.value = numericValue.toLocaleString('es-VE', {
                style: 'decimal',
                maximumFractionDigits: 2,
                minimumFractionDigits: 2
            });
        } else {
            this.value = "";
        }
    }
});

$("#payment-form").on("submit",function(e){
    let button = document.getElementById("payment-form-submit");
    button.disabled = true;
    button.innerHTML = "<span class='spinner-border spinner-border-sm' role='status' aria-hidden='true'></span> Procesando...";
});

    let totalAmount = 0;
    
    // Si es un pago hijo, establecer el monto total como la deuda pendiente
    @if(isset($isChildPayment) && $isChildPayment)
        totalAmount = {{ $remainingDebt }};
        document.getElementById('total_amount').value = totalAmount.toFixed(2);
    @endif
        
    // Add service when selected
    $('#medical_services').change(function() {
        const selectedOption = $(this).find('option:selected');
        const serviceId = selectedOption.val();
        const serviceText = selectedOption.text();
        const serviceCost = parseFloat(selectedOption.data('cost'));
        
        if (serviceId) {
            // Add service as a span with hidden input
            $('#selected-services').append(`
                <span class="badge bg-primary d-flex align-items-center" data-cost="${serviceCost}">
                    ${serviceText}
                    <button type="button" class="btn-close btn-close-white ms-2" aria-label="Remove" data-id="${serviceId}"></button>
                    <input type="hidden" name="medical_services[]" value="${serviceId}">
                </span>
            `);
            
            // Update total amount
            totalAmount += serviceCost;
            $('#total_amount').val(totalAmount.toFixed(2));
            
            // Reset dropdown
            $(this).val('');
        }
    });
        
    // Remove service when close button clicked
    $(document).on('click', '.btn-close', function() {
        const cost = parseFloat($(this).parent().data('cost'));
        totalAmount -= cost;
        $('#total_amount').val(totalAmount.toFixed(2));
        $(this).parent().remove();
    });
});
</script>
@endsection
