@extends('layouts.yellow')
<style>
    /* ======== ESTRUCTURA GENERAL ======== */
.container-fluid {
    padding: 20px;
}

/* ======== TITULO DE PANTALLA ======== */
.page-title {
    background-color: #f8f9fa;
    padding: 15px;
    border-bottom: 2px solid #ddd;
    margin-bottom: 20px;
}

.title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    text-align: center;
}

/* ======== MENSAJES ======== */
.success-message {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
    padding: 10px;
    border-radius: 5px;
    text-align: center;
}

/* ======== BOTONES DE ACCIÓN ======== */
.action-buttons {
    margin-top: 15px;
    text-align: right;
}

.btn-custom {
    font-size: 16px;
    padding: 10px 15px;
    border-radius: 8px;
    transition: all 0.3s ease-in-out;
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
    margin: 5px;
}

/* Efecto hover */
.btn-custom:hover {
    transform: scale(1.05);
}

/* ======== MODAL PERSONALIZADO ======== */
.modal-backdrop {
    background-color: #000 !important;
    opacity: 0.7 !important;
}

.modal-content {
    box-shadow: 0 5px 15px rgba(0,0,0,.5);
}

.date-input-wrapper {
    position: relative;
}

.date-input-wrapper .calendar-icon {
    position: absolute;
    right: 10px;
    top: 10px;
    pointer-events: none;
    color: #6c757d;
}

/* Responsividad */
@media (max-width: 768px) {
    .btn-custom {
        width: 100%;
        margin-bottom: 10px;
    }

    .page-title {
        text-align: center;
    }
}

</style>
@section('content')
<input type="hidden" name="appointmentId" id="appointmentId" value="{{ $model->id }}">

<!-- Contenedor principal con estructura estándar -->
<div class="container-fluid">
    <div class="row page-title">
        <div class="col-12">
            <h2 class="title">{{ __('detail-appointment.detailView') }}</h2>
        </div>
    </div>

    @if (session('success'))
        <div class="row">
            <div class="col-12">
                <div class="alert alert-success success-message">
                    {{ session('success') }}
                </div>
            </div>
        </div>
    @endif

    <!-- Botón de eliminación -->
    <div class="row">
        <div class="col-12">
            <x-ButtonDeleteDetail></x-ButtonDeleteDetail>
        </div>
    </div>

    <!-- Botones de acción -->
    <div class="row action-buttons">
        <div class="col-lg-4 col-md-6 col-12 offset-lg-8 offset-md-6 text-md-end text-center">
            <a class="btn btn-primary btn-custom" href="remember-appointment?id={{ $model->id }}">
                {{ __("common.rememberAppointment") }}
                <i class="bi bi-envelope ms-1"></i>
            </a>

            <a class="btn btn-light btn-custom" href="detail-patient?id={{ $model->patient()->first()->id }}">
                {{ $model->patient()->first()->firstname . " " . $model->patient()->first()->lastname }}
                <i class="bi bi-person-badge ms-1"></i>
            </a>

            <a class="btn btn-info btn-custom" href="{{ route('patient.documents', ['patientId' => $model->patient()->first()->id, 'source' => 'appointment', 'sourceId' => $model->id]) }}">
                {{ __('patient-documents.title') }}
                <i class="bi bi-folder-fill ms-1"></i>
            </a>

            <a class="btn btn-warning btn-custom" href="#" data-bs-toggle="modal" data-bs-target="#modalReschedule">
                {{ __("detail-appointment.rescheduleAppointment") }}
                <i class="bi bi-calendar-plus ms-1"></i>
            </a>

            <a class="btn btn-danger btn-custom" href="#" data-bs-toggle="modal" data-bs-target="#modalAppointment">
                {{ __("detail-appointment.endAppointment") }}
            </a>
        </div>
    </div>

    <!-- Detalles de la cita -->
    <div class="row">
        <div class="col-12">
            <livewire:appointment-detail-view :model="$model" />
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="p-2 text-center">
                <div class="d-flex justify-content-center gap-2">
                    <a href="{{ route('recurring-appointments.create', ['appointment_id' => $model->id]) }}" class="btn btn-primary">
                        <i class="bi bi-calendar-check me-2"></i>
                        {{ __('recurring-appointments.setupRecurring') }}
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal para reagendar cita -->
<div class="modal fade" id="modalReschedule" tabindex="-1" aria-labelledby="modalRescheduleLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title" id="modalRescheduleLabel">{{ __("detail-appointment.rescheduleAppointment") }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('/admin/reschedule-appointment') }}" method="POST">
                @csrf
                <div class="modal-body">
                    <input type="hidden" name="appointment_id" value="{{ $model->id }}">
                    
                    @if(session('error'))
                    <div class="alert alert-danger mb-3">
                        {{ session('error') }}
                    </div>
                    @endif
                    
                    <div class="mb-3">
                        <label for="current_date" class="form-label">{{ __("detail-appointment.currentDate") }}</label>
                        <input type="text" class="form-control" id="current_date" value="{{ \Carbon\Carbon::parse($model->date)->format('d/m/Y H:i:s') }}" disabled>
                    </div>
                    
                    <div class="mb-3">
                        <label for="new_date" class="form-label">{{ __("detail-appointment.newDate") }} *</label>
                        <div class="date-input-wrapper">
                            <input type="text" class="form-control datetimepicker" id="new_date" name="new_date" required readonly>
                            <i class="bi bi-calendar-date calendar-icon"></i>
                        </div>
                        <small class="text-muted">Haga clic para seleccionar fecha y hora</small>
                        <div id="availability-feedback"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="current_doctor" class="form-label">{{ __("detail-appointment.currentDoctor") }}</label>
                        <input type="text" class="form-control" id="current_doctor" value="Dr. {{ $model->user->name ?? 'No asignado' }}" disabled>
                    </div>
                    
                    <div class="mb-3">
                        <label for="users_id" class="form-label">{{ __("detail-appointment.newDoctor") }}</label>
                        <select class="form-select" id="users_id" name="users_id">
                            <option value="">{{ __("detail-appointment.keepCurrentDoctor") }}</option>
                            @foreach(App\Models\User::whereHas('roles', function($q) { $q->where('name', 'doctor'); })->get() as $doctor)
                                <option value="{{ $doctor->id }}" {{ $model->users_id == $doctor->id ? 'selected' : '' }}>
                                    Dr. {{ $doctor->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __("detail-appointment.cancel") }}</button>
                    <button type="submit" class="btn btn-warning">{{ __("detail-appointment.reschedule") }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

@csrf
@endsection

@section('javascript')
    <script src="{{ asset('js/detail-appointment.js') }}" defer></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const doctorSelect = document.getElementById('users_id');
            let selectedDate = null;
            
            // Inicializar el datetimepicker para la nueva fecha
            if (typeof flatpickr !== 'undefined') {
                const datePicker = flatpickr(".datetimepicker", {
                    enableTime: true,
                    dateFormat: "d/m/Y H:i:s",
                    time_24hr: false,
                    defaultDate: "{{ \Carbon\Carbon::parse($model->date)->format('d/m/Y H:i:s') }}",
                    minDate: "today",
                    allowInput: false,
                    disableMobile: true,
                    locale: {
                        firstDayOfWeek: 1,
                        weekdays: {
                            shorthand: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
                            longhand: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado']
                        },
                        months: {
                            shorthand: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
                            longhand: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']
                        }
                    },
                    onChange: function(selectedDates, dateStr) {
                        // Asegurar que la fecha tiene un formato correcto con segundos completos
                        // Si la fecha seleccionada termina con un solo dígito en segundos o sin segundos, corregirla
                        if (dateStr.match(/\d{2}:\d{2}:(\d)$/)) {
                            // Un solo dígito en segundos
                            selectedDate = dateStr.replace(/(\d{2}:\d{2}:)(\d)$/, '$10$2');
                        } else if (dateStr.match(/\d{2}:\d{2}$/)) {
                            // Sin segundos
                            selectedDate = dateStr + ':00';
                        } else {
                            selectedDate = dateStr;
                        }
                        console.log("Fecha original:", dateStr);
                        console.log("Fecha corregida:", selectedDate);
                        checkDoctorAvailability();
                    }
                });
            } else {
                console.warn('Flatpickr not loaded. Loading alternative...');
                // Cargar flatpickr dinámicamente si no está disponible
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css';
                document.head.appendChild(link);

                var script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/flatpickr';
                script.onload = function() {
                    const datePicker = flatpickr(".datetimepicker", {
                        enableTime: true,
                        dateFormat: "d/m/Y H:i:s",
                        time_24hr: false,
                        defaultDate: "{{ \Carbon\Carbon::parse($model->date)->format('d/m/Y H:i:s') }}",
                        minDate: "today",
                        allowInput: false,
                        disableMobile: true,
                        onChange: function(selectedDates, dateStr) {
                            // Asegurar que la fecha tiene un formato correcto con segundos completos
                            // Si la fecha seleccionada termina con un solo dígito en segundos o sin segundos, corregirla
                            if (dateStr.match(/\d{2}:\d{2}:(\d)$/)) {
                                // Un solo dígito en segundos
                                selectedDate = dateStr.replace(/(\d{2}:\d{2}:)(\d)$/, '$10$2');
                            } else if (dateStr.match(/\d{2}:\d{2}$/)) {
                                // Sin segundos
                                selectedDate = dateStr + ':00';
                            } else {
                                selectedDate = dateStr;
                            }
                            console.log("Fecha original:", dateStr);
                            console.log("Fecha corregida:", selectedDate);
                            checkDoctorAvailability();
                        }
                    });
                };
                document.head.appendChild(script);
            }
            
            // Verificar disponibilidad cuando cambia el doctor
            if (doctorSelect) {
                doctorSelect.addEventListener('change', function() {
                    checkDoctorAvailability();
                });
            }
            
            // Función para verificar disponibilidad del doctor
            function checkDoctorAvailability() {
                const dateInput = document.getElementById('new_date');
                const doctorId = doctorSelect.value || '{{ $model->users_id }}';
                const submitBtn = document.querySelector('#modalReschedule button[type="submit"]');
                const feedbackContainer = document.getElementById('availability-feedback');
                
                // Si no tenemos fecha o doctor, no hacemos nada
                if (!selectedDate || !doctorId) return;
                
                // Crear o actualizar el contenedor de feedback si no existe
                if (!feedbackContainer) {
                    const container = document.createElement('div');
                    container.id = 'availability-feedback';
                    container.className = 'mt-2';
                    dateInput.parentNode.after(container);
                }
                
                // Mostrar indicador de carga
                if (feedbackContainer) {
                    feedbackContainer.innerHTML = '<div class="text-info"><i class="bi bi-hourglass-split"></i> Verificando disponibilidad...</div>';
                }
                
                // Desactivar el botón mientras verificamos
                if (submitBtn) submitBtn.disabled = true;
                
                // Hacer petición AJAX para verificar disponibilidad
                console.log("Fecha enviada:", selectedDate);
                fetch(`/admin/doctor/available-days?doctor_id=${doctorId}&date=${encodeURIComponent(selectedDate)}`)
                    .then(response => response.json())
                    .then(data => {
                        console.log("Respuesta del servidor:", data);
                        if (data.available) {
                            // El doctor está disponible
                            if (feedbackContainer) {
                                feedbackContainer.innerHTML = '<div class="text-success"><i class="bi bi-check-circle"></i> El doctor está disponible en esta fecha y hora</div>';
                            }
                            if (submitBtn) submitBtn.disabled = false;
                        } else {
                            // El doctor no está disponible
                            if (feedbackContainer) {
                                feedbackContainer.innerHTML = '<div class="text-danger"><i class="bi bi-x-circle"></i> El doctor no está disponible en esta fecha y hora</div>';
                            }
                            if (submitBtn) submitBtn.disabled = true;
                        }
                    })
                    .catch(error => {
                        console.error('Error al verificar disponibilidad:', error);
                        if (feedbackContainer) {
                            feedbackContainer.innerHTML = '<div class="text-warning"><i class="bi bi-exclamation-triangle"></i> No se pudo verificar la disponibilidad. Por favor, inténtelo de nuevo.</div>';
                        }
                        if (submitBtn) submitBtn.disabled = false; // Permitimos enviar aunque no se pudo verificar
                    });
            }
        });
    </script>
@endsection
