@extends('layouts.yellow')

@section('css')
    @parent
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .accordion-button:not(.collapsed) {
            background-color: #f8f9fa;
            box-shadow: inset 0 -1px 0 rgba(0,0,0,.125);
        }
        .payment-row {
            background-color: #f8f9fa;
        }
        .child-payment {
            background-color: #f8f9fa;
            border-left: 3px solid #e9ecef;
            transition: all 0.2s ease;
        }
        
        .child-payment:hover {
            background-color: #f1f8ff;
            border-left-color: #4e73df;
        }
        .payment-amount {
            font-weight: bold;
        }
        .accordion-body {
            padding: 0.5rem 1.25rem;
        }
        .child-row td {
            padding-left: 2rem !important;
        }
        .child-badge {
            font-size: 0.75em;
            margin-left: 0.5rem;
        }
    </style>
@endsection

@section('content')
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h3 style="color: white !important;">{{ __('Relación de Citas y Pagos') }}</h3>
                    <div>
                        <a href="/admin/appointment-payment-relation/export?{{ http_build_query(request()->all()) }}" class="btn btn-success">
                            <i class="fas fa-file-excel mr-2"></i> Exportar a Excel
                        </a>
                    </div>
                </div>

                <div class="card-body">
                    <!-- Filtros -->
                    <div class="filter-card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0"><i class="fas fa-filter me-2"></i>Filtros de Búsqueda</h5>
                            <span class="badge bg-white text-primary">{{ $appointments->total() }} resultados encontrados</span>
                        </div>
                        <div class="card-body">
                            <form method="GET" action="/admin/appointment-payment-relation" class="row g-4">
                                <!-- Fila 1 -->
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label for="payment_status" class="form-label">
                                        <i class="fas fa-money-bill-wave me-1"></i> Estado de Pago
                                    </label>
                                    <select class="form-select" id="payment_status" name="payment_status">
                                        <option value="">Todos los pagos</option>
                                        <option value="with_payment" {{ request('payment_status') == 'with_payment' ? 'selected' : '' }}>Con Pago</option>
                                        <option value="without_payment" {{ request('payment_status') == 'without_payment' ? 'selected' : '' }}>Sin Pago</option>
                                    </select>
                                </div>
                                
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label for="appointment_status" class="form-label">
                                        <i class="fas fa-calendar-check me-1"></i> Estado de Consulta
                                    </label>
                                    <select class="form-select" id="appointment_status" name="appointment_status">
                                        <option value="">Todos los estados</option>
                                        <option value="0" {{ request('appointment_status') === '0' ? 'selected' : '' }}>Pendiente</option>
                                        <option value="2" {{ request('appointment_status') == '2' ? 'selected' : '' }}>Concretada</option>
                                        <option value="3" {{ request('appointment_status') == '3' ? 'selected' : '' }}>No concretada</option>
                                    </select>
                                </div>
                                
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label for="tag_id" class="form-label">
                                        <i class="fas fa-tags me-1"></i> Etiqueta
                                    </label>
                                    <select class="form-select" id="tag_id" name="tag_id">
                                        <option value="">Todas las etiquetas</option>
                                        @foreach($tags as $tag)
                                            <option value="{{ $tag->id }}" {{ request('tag_id') == $tag->id ? 'selected' : '' }}>{{ $tag->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                
                                <div class="col-12 col-md-6 col-lg-3">
                                    <label for="doctor_id" class="form-label">
                                        <i class="fas fa-user-md me-1"></i> Doctor
                                    </label>
                                    <select class="form-select" id="doctor_id" name="doctor_id">
                                        <option value="">Todos los doctores</option>
                                        @foreach($doctors as $doctor)
                                            <option value="{{ $doctor->id }}" {{ request('doctor_id') == $doctor->id ? 'selected' : '' }}>{{ $doctor->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                
                                <!-- Fila 2 -->
                                <div class="col-12 col-md-6 col-lg-4">
                                    <label for="date_from" class="form-label">
                                        <i class="far fa-calendar-alt me-1"></i> Fecha desde
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="far fa-calendar"></i></span>
                                        <input type="date" class="form-control" id="date_from" name="date_from" value="{{ request('date_from') }}">
                                    </div>
                                </div>
                                
                                <div class="col-12 col-md-6 col-lg-4">
                                    <label for="date_to" class="form-label">
                                        <i class="far fa-calendar-alt me-1"></i> Fecha hasta
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="far fa-calendar"></i></span>
                                        <input type="date" class="form-control" id="date_to" name="date_to" value="{{ request('date_to') }}">
                                    </div>
                                </div>
                                
                                <!-- Botones de acción -->
                                <div class="col-12 col-lg-4 d-flex align-items-end gap-2">
                                    <button type="submit" class="btn-filter flex-grow-1" name="filter" value="1">
                                        <i class="fas fa-search me-1"></i> Aplicar Filtros
                                    </button>
                                    <a href="/admin/appointment-payment-relation" class="btn-clear">
                                        <i class="fas fa-undo me-1"></i> Limpiar
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Tabla de relación citas-pagos -->
                    @if($appointments->count() > 0)
                    <div class="table-responsive mt-4">
                        <table class="table table-striped table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Código Cita</th>
                                    <th>Fecha</th>
                                    <th>Paciente</th>
                                    <th>Doctor</th>
                                    <th>Etiquetas</th>
                                    <th>Estado Consulta</th>
                                    <th>Estado de Pago</th>
                                    <th>Monto Pagado</th>
                                    <th>Monto Total a Pagar</th>
                                    <th>Deuda</th>
                                    <th>Método de Pago</th>
                                    <th>Referencia</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($appointments as $appointment)
    @php
        $hasChildren = $appointment->payment && $appointment->payment->children->isNotEmpty();
    @endphp
    
    <!-- Fila principal del pago -->
    <tr class="payment-row">
        <td>{{ $appointment->code }}</td>
        <td>{{ \Carbon\Carbon::parse($appointment->date)->format('d/m/Y H:i') }}</td>
        <td>
            <a href="/admin/detail-patient?id={{ $appointment->patient->id }}" class="text-decoration-none">
                {{ $appointment->patient->firstname . ' ' . $appointment->patient->lastname ?? 'N/A' }}
            </a>
        </td>
        <td>{{ $appointment->user->profile->firstname . ' ' . $appointment->user->profile->lastname ?? 'N/A' }}</td>
        <td>
            @foreach($appointment->tags as $tag)
                <span class="badge" style="background-color: {{ $tag->color }}">{{ $tag->name }}</span>
            @endforeach
        </td>
        <td>
            @if($appointment->status == 2)
                <span class="badge bg-success">Concretada</span>
            @elseif($appointment->status == 3)
                <span class="badge bg-danger">No concretada</span>
            @elseif($appointment->status == 1)
                <span class="badge bg-info">Confirmada</span>
            @elseif($appointment->status == 4)
                <span class="badge bg-warning text-dark">No asistió</span>
            @else
                <span class="badge bg-secondary">Pendiente</span>
            @endif
        </td>
        <td>
            @if($appointment->payment)
                @php
                    $totalPaid = $appointment->payment->amount + $appointment->payment->children->sum('amount');
                    $totalServices = $appointment->payment->medicalServices->sum('cost');
                    $isFullyPaid = $totalPaid >= $totalServices;
                @endphp
                @if($isFullyPaid)
                    <span class="badge bg-success">Pagado</span>
                @else
                    <span class="badge bg-warning">Pendiente</span>
                @endif
            @else
                <span class="badge bg-secondary">Sin pago</span>
            @endif
        </td>
        <td>
            @if($appointment->payment)
                <div class="d-flex justify-content-between align-items-center">
                    <span>
                        {{ number_format($appointment->payment->amount, 2) }}
                        {{ $appointment->payment->currency->code ?? '' }}
                        @if($hasChildren)
                            <span class="badge bg-info child-badge">+{{ $appointment->payment->children->count() }}</span>
                        @endif
                    </span>
                    @if($hasChildren)
                        <button class="btn btn-sm btn-link p-0 ms-2" type="button" data-bs-toggle="collapse" 
                                data-bs-target="#paymentChildren{{ $appointment->id }}" 
                                aria-expanded="false" 
                                aria-controls="paymentChildren{{ $appointment->id }}">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    @endif
                </div>
            @else
                -
            @endif
        </td>
        <td>
            @if($appointment->payment)
                {{ number_format($appointment->payment->medicalServices->sum('cost'), 2) }}
            @else
                0.00
            @endif
        </td>
        <td>
            @if($appointment->payment)
                @php
                    $totalPaid = $appointment->payment->amount + $appointment->payment->children->sum('amount');
                    $totalServices = $appointment->payment->medicalServices->sum('cost');
                    $remaining = $totalServices - $totalPaid;
                @endphp
                {{ number_format($remaining, 2) }}
                @if($remaining > 0)
                    <span class="badge bg-warning">Pendiente</span>
                @else
                    <span class="badge bg-success">Pagado</span>
                @endif
            @else
                0.00
                <span class="badge bg-secondary">Sin pago</span>
            @endif
        </td>
        <td>
            @if($appointment->payment)
                {{ $appointment->payment->paymentMethod->title ?? 'N/A' }}
            @else
                -
            @endif
        </td>
        <td>
            @if($appointment->payment)
                {{ $appointment->payment->reference ?? 'N/A' }}
            @else
                -
            @endif
        </td>
        <td>
            <div class="d-flex">
                <button class="btn btn-sm btn-info me-1" data-bs-toggle="modal" data-bs-target="#servicesModal-{{ $appointment->payment->id ?? '' }}" @if(!$appointment->payment) disabled @endif>
                    <i class="fas fa-list"></i> 
                </button>
                <div class="btn-group" role="group">
                    <a href="/admin/detail-appointment?id={{ $appointment->id }}" class="btn btn-sm btn-info" title="Ver detalles de cita">
                        <i class="fas fa-eye"></i>
                    </a>
                    
                    @if($appointment->payment)
                        <a href="/admin/detail-payment?id={{ $appointment->payment->id }}" class="btn btn-sm btn-primary" title="Ver detalles del pago">
                            <i class="fas fa-dollar-sign"></i>
                        </a>
                    @else
                        <a href="/admin/payment-for-appointment-individual/{{ $appointment->id }}" class="btn btn-sm btn-primary" title="Realizar pago">
                            <i class="fas fa-dollar-sign"></i>
                        </a>    
                    @endif
                </div>
            </div>
        </td>
    </tr>
    
    <!-- Filas de pagos adicionales (acordeón) -->
    @if($hasChildren)
        <tr>
            <td colspan="13" class="p-0">
                <div class="collapse" id="paymentChildren{{ $appointment->id }}">
                    <div class="p-3 bg-light">
                        <h6 class="mb-3">Pagos Adicionales</h6>
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Referencia</th>
                                    <th>Método</th>
                                    <th>Monto</th>
                                    <th>Fecha</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($appointment->payment->children as $childPayment)
                                    <tr class="child-payment">
                                        <td>{{ $childPayment->reference }}</td>
                                        <td>{{ $childPayment->paymentMethod->title ?? 'N/A' }}</td>
                                        <td>{{ number_format($childPayment->amount, 2) }} {{ $childPayment->currency->code ?? '' }}</td>
                                        <td>{{ $childPayment->created_at->format('d/m/Y H:i') }}</td>
                                        <td>
                                            <a href="/admin/detail-payment?id={{ $childPayment->id }}" class="btn btn-sm btn-primary" title="Ver detalles">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </td>
        </tr>
    @endif
                                @empty
                                    <tr>
                                        <td colspan="13" class="text-center">No se encontraron resultados</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Paginación -->
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div class="text-muted">
                            Mostrando {{ $appointments->firstItem() }} a {{ $appointments->lastItem() }} de {{ $appointments->total() }} registros
                        </div>
                        <div>
                            {{ $appointments->appends(request()->query())->links() }}
                        </div>
                    </div>
                    @if($appointments->isEmpty())
                    <div class="alert alert-info mt-4">
                        <i class="fas fa-info-circle me-2"></i> No se encontraron citas que coincidan con los filtros aplicados.
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modales para servicios -->
@foreach($appointments as $appointment)
    @if(isset($appointment->payment))
        <!-- Modal Servicios -->
        <div class="modal fade" id="servicesModal-{{ $appointment->payment->id }}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Servicios Médicos - Pago #{{ $appointment->payment->id }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Servicio</th>
                                    <th>Precio</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($appointment->payment->medicalServices as $service)
                                    <tr>
                                        <td>{{ $service->name }}</td>
                                        <td>{{ number_format($service->cost, 2) }}</td>
                                    </tr>
                                @endforeach
                                <tr class="table-primary">
                                    <td><strong>Total</strong></td>
                                    <td><strong>{{ number_format($appointment->payment->medicalServices->sum('cost'), 2) }}</strong></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="modal-footer">
                        @if($appointment->payment)
                            @php
                                $totalPaid = $appointment->payment->amount + $appointment->payment->children->sum('amount');
                                $totalServices = $appointment->payment->medicalServices->sum('cost');
                                $remaining = $totalServices - $totalPaid;
                            @endphp
                            @if($remaining > 0)
                                <button type="button" class="btn btn-success me-auto" onclick="window.location.href='{{ route('additional-payment', $appointment->payment->id) }}'">
                                    <i class="fas fa-money-bill-wave"></i> Pagar Saldo ({{ number_format($remaining, 2) }})
                                </button>
                            @endif
                        @endif
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                    </div>
                </div>
            </div>
        </div>
    @endif
@endforeach
@endif

@endsection

@section('scripts')
    @parent
    <script>
        function payRemaining(paymentId) {
            if(confirm('¿Confirmar pago del saldo pendiente?')) {
                // Aquí iría la llamada AJAX para procesar el pago
                alert('Pago procesado para el pago ID: ' + paymentId);
                // Recargar la página para actualizar los datos
                location.reload();
            }
        }
    </script>
@endsection
