@extends('layouts.yellow')
@push('styles')
<style>
    :root {
        --primary-color: #2B579A;
        --secondary-color: #337ab7;
        --success-color: #28a745;
        --info-color: #17a2b8;
        --light-gray: #f8f9fa;
        --border-radius: 0.5rem;
        --box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        --transition: all 0.3s ease;
    }

    .payment-header {
        background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
        color: white;
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: var(--box-shadow);
        position: relative;
        overflow: hidden;
    }

    .payment-header::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 200px;
        height: 200px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
    }

    .payment-icon {
        font-size: 3rem;
        margin-bottom: 1rem;
        color: rgba(255, 255, 255, 0.9);
    }

    .payment-card {
        background: white;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        margin-bottom: 2rem;
        overflow: hidden;
        transition: var(--transition);
        border: none;
    }

    .payment-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.1);
    }

    .card-header {
        background-color: var(--primary-color);
        color: white;
        font-weight: 600;
        padding: 1.25rem 1.5rem;
        border-bottom: none;
    }

    .card-body {
        padding: 2rem;
    }

    .form-group {
        margin-bottom: 1.5rem;
    }

    .form-group label {
        font-weight: 600;
        margin-bottom: 0.5rem;
        color: #495057;
    }

    .form-control {
        border-radius: 0.375rem;
        border: 1px solid #dee2e6;
        padding: 0.75rem 1rem;
        transition: var(--transition);
    }

    .form-control:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(43, 87, 154, 0.25);
    }

    .alert {
        border-radius: var(--border-radius);
        border: none;
        padding: 1.25rem 1.5rem;
    }

    .badge {
        font-weight: 500;
        padding: 0.5em 1em;
        border-radius: 50px;
    }

    /* Tabla de pagos adicionales */
    .payment-history {
        margin-top: 2rem;
    }

    .table {
        margin-bottom: 0;
    }

    .table thead th {
        background-color: #f1f5f9;
        color: #334155;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.05em;
        border-bottom: 2px solid #e2e8f0;
        padding: 1rem 1.5rem;
    }

    .table tbody td {
        padding: 1rem 1.5rem;
        vertical-align: middle;
        border-color: #f1f5f9;
    }

    .table tbody tr:hover {
        background-color: #f8fafc;
    }

    .table tfoot th {
        font-weight: 600;
        background-color: #f8fafc;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .payment-header {
            text-align: center;
            padding: 1.5rem 1rem;
        }
        
        .payment-icon {
            font-size: 2.5rem;
        }
        
        .card-body {
            padding: 1.5rem 1rem;
        }
        
        .table-responsive {
            border: 1px solid #e2e8f0;
            border-radius: var(--border-radius);
            overflow: hidden;
        }
    }

    /* Animations */
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .fade-in {
        animation: fadeIn 0.5s ease-out forwards;
    }
</style>
@endpush

@section('content')
<div class="container-fluid py-4">
    <!-- Encabezado principal -->
    <div class="payment-header text-center text-md-start fade-in">
        <div class="d-flex flex-column flex-md-row align-items-center">
            <div class="payment-icon me-md-4">
                <i class="fas fa-file-invoice-dollar"></i>
            </div>
            <div>
                <h1 class="h3 mb-2">{{ __('view-payments.detailView') }}</h1>
                <p class="mb-0 opacity-75">{{ __('Referencia') }}: <strong>{{ $model->reference }}</strong></p>
            </div>
        </div>
    </div>

    <!-- Tarjeta de información del pago -->
    <div class="row justify-content-center">
        <div class="col-12 col-xxl-10">
            <div class="payment-card fade-in" style="animation-delay: 0.1s">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-info-circle me-2"></i> {{ __('Información del Pago') }}</span>
                    @if($model->is_electronic)
                    <span class="badge bg-success">
                        <i class="fas fa-credit-card me-1"></i> {{ __('Electrónico') }}
                    </span>
                    @endif
                </div>
                <div class="card-body">
                    <div class="row g-4">
                        <!-- Información del pagador -->
                        <div class="col-12">
                            <div class="form-group">
                                <label for="payer">{{ __('com-form-payment.payer') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                    <input type="text" class="form-control" value="{{ $model->payer }}" readonly>
                                </div>
                            </div>
                        </div>

                        <!-- Monto y moneda -->
                        <div class="col-12 col-md-6 col-lg-4">
                            <div class="form-group">
                                <label for="amount">{{ __('com-form-payment.amount') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-dollar-sign"></i></span>
                                    <input type="text" class="form-control text-end fw-bold" 
                                           value="{{ number_format($model->amount, 2) }}" readonly>
                                    <span class="input-group-text bg-light">{{ $model->currency->code ?? '' }}</span>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-4">
                            <div class="form-group">
                                <label for="paymentMethod">{{ __('com-form-payment.method') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-credit-card"></i></span>
                                    <input type="text" class="form-control" 
                                           value="{{ $model->paymentMethod->title ?? 'N/A' }}" readonly>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6 col-lg-4">
                            <div class="form-group">
                                <label for="date">{{ __('Fecha de Pago') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
                                    <input type="text" class="form-control" 
                                           value="{{ $model->created_at->format('d/m/Y H:i') }}" readonly>
                                </div>
                            </div>
                        </div>

                        <!-- Referencia electrónica (si aplica) -->
                        @if($model->is_electronic && $model->user_reference)
                        <div class="col-12">
                            <div class="alert alert-info mb-0">
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-info-circle fa-2x me-3"></i>
                                    <div>
                                        <h5 class="alert-heading mb-1">{{ __('Información de Pago Electrónico') }}</h5>
                                        <p class="mb-0">{{ __('com-form-payment.userReference') }}: 
                                            <span class="badge bg-primary">{{ $model->user_reference }}</span>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endif

                        <!-- Información de la cita -->
                        <div class="col-12">
                            <h5 class="border-bottom pb-2 mb-3"><i class="fas fa-calendar-check me-2"></i> {{ __('Información de la Cita') }}</h5>
                        </div>

                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="especiality">{{ __('com-form-history.especiality') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-stethoscope"></i></span>
                                    <input type="text" class="form-control" 
                                           value="{{ $model->especiality->name ?? 'N/A' }}" readonly>
                                </div>
                            </div>
                        </div>

                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="doctor">{{ __('com-form-payment.doctor') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-user-md"></i></span>
                                    <input type="text" class="form-control" 
                                           value="{{ $model->user->name ?? 'N/A' }}" readonly>
                                </div>
                            </div>
                        </div>

                        <!-- Dirección y motivo -->
                        <div class="col-12">
                            <div class="form-group">
                                <label for="address">{{ __('com-form-payment.address') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
                                    <textarea class="form-control" rows="2" readonly>{{ $model->address_payer }}</textarea>
                                </div>
                            </div>
                        </div>

                        <div class="col-12">
                            <div class="form-group">
                                <label for="reason">{{ __('com-form-payment.reason') }}</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="far fa-comment-dots"></i></span>
                                    <textarea class="form-control" rows="3" readonly>{{ $model->description }}</textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Servicios Médicos -->
                        <div class="col-12">
                            <h5 class="border-bottom pb-2 mb-3">
                                <i class="fas fa-procedures me-2"></i> {{ __('Servicios Médicos') }}
                                @if($model->parent_id === null)
                                <button type="button" class="btn btn-sm btn-primary float-end" data-bs-toggle="modal" data-bs-target="#addServicesModal">
                                    <i class="fas fa-plus me-1"></i> {{ __('Agregar Servicios') }}
                                </button>
                                @endif
                            </h5>
                            
                            @if($model->medicalServices->isNotEmpty())
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle">
                                        <thead class="table-light">
                                            <tr>
                                                <th>{{ __('Servicio') }}</th>
                                                <th class="text-end">{{ __('Costo') }}</th>
                                                <th class="text-end">{{ __('Moneda') }}</th>
                                                <th>{{ __('Fecha de Registro') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($model->medicalServices as $service)
                                            <tr>
                                                <td>{{ $service->name }}</td>
                                                <td class="text-end fw-bold">{{ number_format($service->pivot->cost ?? $service->cost, 2) }}</td>
                                                <td class="text-end">{{ $model->currency->code ?? 'USD' }}</td>
                                                <td>{{ $model->created_at->format('d/m/Y H:i') }}</td>
                                            </tr>
                                            @endforeach
                                            <tr class="table-light fw-bold">
                                                <td colspan="1">{{ __('Total') }}:</td>
                                                <td class="text-end">{{ number_format($model->medicalServices->sum(function($item) {
                                                    return $item->pivot->cost ?? $item->cost;
                                                }), 2) }}</td>
                                                <td class="text-end">{{ $model->currency->code ?? 'USD' }}</td>
                                                <td></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            @else
                                <div class="alert alert-info mb-0">
                                    <i class="fas fa-info-circle me-2"></i> {{ __('No se han registrado servicios médicos para este pago.') }}
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>

            <!-- Historial de pagos adicionales -->
            @if(isset($childPayments) && $childPayments->isNotEmpty())
            <div class="payment-card fade-in" style="animation-delay: 0.2s">
                <div class="card-header">
                    <i class="fas fa-history me-2"></i> {{ __('Historial de Pagos Adicionales') }}
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="ps-4">{{ __('Fecha') }}</th>
                                    <th class="text-end pe-4">{{ __('Monto') }}</th>
                                    <th>{{ __('Moneda') }}</th>
                                    <th>{{ __('Método') }}</th>
                                    <th>{{ __('Referencia') }}</th>
                                    <th>{{ __('Registrado por') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($childPayments as $child)
                                <tr>
                                    <td class="ps-4">
                                        <i class="far fa-clock text-muted me-2"></i>
                                        {{ $child->created_at->format('d/m/Y H:i') }}
                                    </td>
                                    <td class="text-end fw-bold pe-4">
                                        {{ number_format($child->amount, 2) }}
                                    </td>
                                    <td>
                                        <span class="badge bg-light text-dark">
                                            {{ $child->currency->title ?? 'N/A' }}
                                        </span>
                                    </td>
                                    <td>
                                        <i class="fas fa-credit-card me-2 text-muted"></i>
                                        {{ $child->paymentMethod->title ?? 'N/A' }}
                                    </td>
                                    <td>
                                        @if($child->reference)
                                            <span class="badge bg-info text-dark">{{ $child->reference }}</span>
                                        @else
                                            <span class="text-muted">N/A</span>
                                        @endif
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-sm me-2">
                                                <span class="avatar-title bg-primary bg-opacity-10 text-primary rounded-circle">
                                                    {{ substr(($child->user->profile->firstname ?? 'U')[0], 0, 1) }}
                                                </span>
                                            </div>
                                            <div>
                                                <div class="fw-medium">
                                                    {{ $child->user->profile->firstname ?? 'Usuario' }} 
                                                    {{ $child->user->profile->lastname ?? '' }}
                                                </div>
                                                <small class="text-muted">
                                                    {{ $child->created_at->diffForHumans() }}
                                                </small>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                            <tfoot class="table-light">
                                <tr>
                                    <th colspan="5" class="text-end border-0 py-3">
                                        <h5 class="mb-0">{{ __('Total Pagado en Adicionales') }}:</h5>
                                    </th>
                                    <th class="text-end border-0 py-3">
                                        <h4 class="mb-0 text-primary">
                                            {{ number_format($childPayments->sum('amount'), 2) }}
                                            <small class="text-muted">{{ $model->currency->code ?? '' }}</small>
                                        </h4>
                                    </th>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
            @endif

            <!-- Modal para agregar servicios médicos -->
            @if($model->parent_id === null)
            <div class="modal fade" id="addServicesModal" tabindex="-1" aria-labelledby="addServicesModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="addServicesModalLabel">
                                <i class="fas fa-plus-circle me-2"></i> {{ __('Agregar Servicios Médicos') }}
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <form id="addServicesForm" method="POST" action="{{ route('admin.payments.add-services', $model->id) }}">
                            @csrf
                            <div class="modal-body">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    {{ __('Seleccione los servicios médicos adicionales que desea agregar a este pago.') }}
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-hover" id="servicesTable">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="50">
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" id="selectAll">
                                                    </div>
                                                </th>
                                                <th>{{ __('Servicio') }}</th>
                                                <th class="text-end">{{ __('Costo') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @php
                                                $currentServices = $model->medicalServices->pluck('id')->toArray();
                                                $availableServices = \App\Models\MedicalService::all();
                                            @endphp
                                            
                                            @if($availableServices->isNotEmpty())
                                                @foreach($availableServices as $service)
                                                <tr>
                                                    <td>
                                                        <div class="form-check">
                                                            <input class="form-check-input service-checkbox" type="checkbox" 
                                                                   name="services[]" value="{{ $service->id }}" 
                                                                   data-cost="{{ $service->cost }}">
                                                        </div>
                                                    </td>
                                                    <td>{{ $service->name }}</td>
                                                    <td class="text-end">
                                                        {{ number_format($service->cost, 2, ',', '.') }} {{ $model->currency->code ?? 'USD' }}
                                                    </td>
                                                </tr>
                                                @endforeach
                                            @else
                                                <tr>
                                                    <td colspan="4" class="text-center py-4">
                                                        <i class="fas fa-info-circle text-muted me-2"></i>
                                                        {{ __('No hay servicios médicos disponibles para agregar.') }}
                                                    </td>
                                                </tr>
                                            @endif
                                        </tbody>
                                        <tfoot class="table-light">
                                            <tr>
                                                <th colspan="2" class="text-end">{{ __('Total Seleccionado') }}:</th>
                                                <th class="text-end" id="selectedTotal">0,00 {{ $model->currency->code ?? 'USD' }}</th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                    <i class="fas fa-times me-1"></i> {{ __('Cancelar') }}
                                </button>
                                <button type="submit" class="btn btn-primary" id="saveServicesBtn" disabled>
                                    <i class="fas fa-save me-1"></i> {{ __('Guardar Servicios') }}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            @endif

            <!-- Botón de volver -->
            <div class="d-flex justify-content-start mt-4 mb-5">
                <a href="{{ route('appointment.payment.relation') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-2"></i> {{ __('Ir a relacion de pagos') }}
                </a>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    // Asegurar que los tooltips funcionen
    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 modal de servicios si existe
        var addServicesModal = document.getElementById('addServicesModal');
        if (addServicesModal) {
            // Resetear el modal cuando se cierre
            addServicesModal.addEventListener('hidden.bs.modal', function () {
                resetServicesForm();
            });

            // Configurar el evento de selección múltiple
            const selectAllCheckbox = document.getElementById('selectAll');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('.service-checkbox');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = selectAllCheckbox.checked;
                    });
                    updateSelectedTotal();
                });
            }

            // Actualizar total cuando se marcan/desmarcan servicios
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('service-checkbox')) {
                    updateSelectedTotal();
                }
            });

            // Función para mostrar alertas
            function showAlert(message, type = 'success') {
                // Eliminar alertas previas
                const existingAlerts = document.querySelectorAll('.dynamic-alert');
                existingAlerts.forEach(alert => alert.remove());
                
                // Crear nueva alerta
                const alertDiv = document.createElement('div');
                alertDiv.className = `alert alert-${type} alert-dismissible fade show dynamic-alert`;
                alertDiv.role = 'alert';
                alertDiv.innerHTML = `
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                `;
                
                // Insertar la alerta después del título del modal
                const modalTitle = document.querySelector('#addServicesModal .modal-title');
                if (modalTitle) {
                    modalTitle.parentNode.insertBefore(alertDiv, modalTitle.nextSibling);
                } else {
                    // Si no se encuentra el título, insertar al principio del modal body
                    const modalBody = document.querySelector('#addServicesModal .modal-body');
                    if (modalBody) {
                        modalBody.insertBefore(alertDiv, modalBody.firstChild);
                    }
                }
                
                // Hacer scroll hasta la alerta
                alertDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }

            // Manejar envío del formulario
            document.getElementById('addServicesForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Mostrar indicador de carga
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalBtnText = submitBtn.innerHTML;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Procesando...';
                
                // Validar que se haya seleccionado al menos un servicio
                const checkboxes = document.querySelectorAll('.service-checkbox:checked');
                if (checkboxes.length === 0) {
                    showAlert('Por favor seleccione al menos un servicio', 'danger');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalBtnText;
                    return false;
                }
                
                // Si todo está bien, enviar el formulario vía AJAX
                const formData = new FormData(this);
                
                fetch(this.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => { throw err; });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.redirect) {
                        // Redirigir a la página de detalle del pago
                        window.location.href = data.redirect;
                    } else {
                        // Recargar la página para ver los cambios
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    const errorMessage = error.message || 'Error al procesar la solicitud. Por favor, intente de nuevo.';
                    showAlert(errorMessage, 'danger');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalBtnText;
                });
            });
        }


        // Función para actualizar el total seleccionado
        function updateSelectedTotal() {
            let total = 0;
            const checkboxes = document.querySelectorAll('.service-checkbox:checked');
            const saveBtn = document.getElementById('saveServicesBtn');
            
            // Habilitar/deshabilitar botón de guardar según selección
            if (saveBtn) {
                saveBtn.disabled = checkboxes.length === 0;
            }
            
            // Calcular total de los servicios seleccionados
            checkboxes.forEach(checkbox => {
                const cost = parseFloat(checkbox.getAttribute('data-cost')) || 0;
                total += cost;
            });
            
            // Actualizar total en la interfaz
            const totalElement = document.getElementById('selectedTotal');
            if (totalElement) {
                totalElement.textContent = total.toLocaleString('es-ES', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            }
        }
        
        // Agregar event listeners a los checkboxes para actualizar el total
        document.addEventListener('DOMContentLoaded', function() {
            const checkboxes = document.querySelectorAll('.service-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedTotal);
            });
            
            // Inicializar el total
            updateSelectedTotal();
        });
        
        // Función para resetear el formulario de servicios
        function resetServicesForm() {
            const checkboxes = document.querySelectorAll('.service-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            
            const selectAll = document.getElementById('selectAll');
            if (selectAll) {
                selectAll.checked = false;
            }
            
            document.getElementById('selectedTotal').textContent = '0,00';
            
            const saveBtn = document.getElementById('saveServicesBtn');
            if (saveBtn) {
                saveBtn.disabled = true;
                saveBtn.innerHTML = '<i class="fas fa-save me-1"></i> {{ __("Guardar Servicios") }}';
            }
        }
    });
</script>
@endpush

@endsection