<!doctype html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Detalle Formulario - Profesional</title>
    <script>
        (function () {
            const root = document.documentElement;
            root.classList.add('sidebar-nav-pending');

            const releasePending = function () {
                root.classList.remove('sidebar-nav-pending');
            };

            const timeoutId = window.setTimeout(releasePending, 1200);

            if (document.querySelector('.admin-sidebar')) {
                window.clearTimeout(timeoutId);
                releasePending();
                return;
            }

            const observer = new MutationObserver(function () {
                if (!document.querySelector('.admin-sidebar')) {
                    return;
                }

                observer.disconnect();
                window.clearTimeout(timeoutId);
                releasePending();
            });

            observer.observe(document.documentElement, {
                childList: true,
                subtree: true,
            });
        })();
    </script>
    <style>
        @media (min-width: 992px) {
            html.sidebar-nav-pending main {
                visibility: hidden;
            }
        }
    </style>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    <style>
        #agenda-modal-profesional {
            min-height: 460px;
        }

        .fc .fc-bg-event.evento-feriado {
            opacity: 1 !important;
            background-color: rgba(220, 53, 69, 0.30) !important;
            border-color: rgba(220, 53, 69, 0.55) !important;
            color: #5b1f23 !important;
            font-weight: 600;
        }

        .fc .fc-bg-event.evento-receso,
        .fc .fc-bg-event.evento-vacaciones {
            opacity: 1 !important;
            background-color: rgba(220, 53, 69, 0.30) !important;
            border-color: rgba(220, 53, 69, 0.55) !important;
            color: #5b1f23 !important;
            font-weight: 600;
        }

            .fc .fc-bg-event.evento-disponibilidad {
                opacity: 1 !important;
                background-color: rgba(25, 135, 84, 0.24) !important;
                border-color: rgba(25, 135, 84, 0.42) !important;
            }

        .fc .fc-bg-event.evento-feriado .fc-event-title,
        .fc .fc-bg-event.evento-feriado .fc-bg-event-title,
        .fc .fc-bg-event.evento-receso .fc-event-title,
        .fc .fc-bg-event.evento-receso .fc-bg-event-title,
        .fc .fc-bg-event.evento-vacaciones .fc-event-title,
        .fc .fc-bg-event.evento-vacaciones .fc-bg-event-title {
            color: #5b1f23 !important;
            opacity: 1;
        }
    </style>
</head>
<body id="top" class="d-flex flex-column min-vh-100 bg-light">
    <header class="app-navbar">
        <nav class="navbar navbar-expand-lg">
            <div class="container">
                @php
                    $nombreSesion = trim((string) session('personal_nombre', 'Profesional'));
                    $nombreSaludo = $nombreSesion !== '' ? explode(' ', $nombreSesion)[0] : 'Profesional';
                @endphp
                <a class="navbar-brand d-flex align-items-center gap-2" href="/profesional/dashboard">
                    <div class="d-flex align-items-center justify-content-center" style="width: 130px; height: 52px;">
                        <img src="{{ asset('images/logo.png') }}" alt="Logo" class="img-fluid" style="max-height: 70px; width: auto; object-fit: contain;">
                    </div>
                    <span class="fw-semibold">¡Hola, {{ $nombreSaludo }}!</span>
                </a>

                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#menuPrincipal" aria-controls="menuPrincipal" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="menuPrincipal">
                    <ul class="navbar-nav mx-auto mb-2 mb-lg-0">
                        <li class="nav-item"><a class="btn app-navbar-link" href="/profesional/dashboard">Mi Agenda</a></li>
                        <li class="nav-item"><a class="btn app-navbar-link" href="/profesional/clientes">Mis Clientes</a></li>
                        <li class="nav-item"><a class="btn app-navbar-link" href="/profesional/mis-datos">Mis Datos</a></li>
                        <li class="nav-item">
                            <a class="btn app-navbar-link position-relative" href="/profesional/formularios">
                                Revisar Formularios
                                @if(($formulariosPendientesCount ?? 0) > 0)
                                    <span class="position-absolute top-0 start-100 translate-middle p-1 bg-danger rounded-circle js-notificaciones-badge">
                                        <span class="visually-hidden">Hay formularios pendientes</span>
                                    </span>
                                @endif
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="btn app-navbar-link position-relative" href="/profesional/notificaciones" data-notificaciones-claves='@json($notificacionesClaves ?? [])'>
                                Notificaciones
                                @if(($notificacionesCount ?? 0) > 0)
                                    <span class="position-absolute top-0 start-100 translate-middle p-1 bg-danger rounded-circle js-notificaciones-badge d-none">
                                        <span class="visually-hidden">Hay notificaciones</span>
                                    </span>
                                @endif
                            </a>
                        </li>
                    </ul>

                    <a class="btn app-navbar-link" href="/logout">Cerrar Sesion</a>
                </div>
            </div>
        </nav>
    </header>

    <main class="container py-4 flex-grow-1">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h1 class="h4 mb-0">Detalle del Formulario</h1>
            <a href="/profesional/formularios" class="btn btn-outline-secondary btn-sm">Volver a formularios</a>
        </div>

        @if($errors->any())
            <div class="alert alert-danger" role="alert">
                <ul class="mb-0 ps-3">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        @if(session('profesional_action_success'))
            <div class="alert alert-success" role="alert">
                {{ session('profesional_action_success') }}
            </div>
        @endif

        @if(session('profesional_action_error'))
            <div class="alert alert-danger" role="alert">
                {{ session('profesional_action_error') }}
            </div>
        @endif

        @if(session('formulario_turno_manual_warning'))
            <div class="alert alert-warning" role="alert">
                <p class="mb-2"><strong>Advertencias de agenda:</strong></p>
                <ul class="mb-0 ps-3">
                    @foreach((session('formulario_turno_manual_warning')['advertencias'] ?? []) as $advertencia)
                        <li>{{ $advertencia }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <div class="card border shadow-sm">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Nombre</p>
                        <p class="mb-0 fw-semibold">{{ $formulario->nombrecompleto ?? '-' }}</p>
                    </div>
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Fecha de envío</p>
                        <p class="mb-0 fw-semibold">
                            {{ $formulario->created_at ? $formulario->created_at->format('d/m/Y H:i:s') : ($formulario->fechaenvio ? \Illuminate\Support\Carbon::parse($formulario->fechaenvio)->format('d/m/Y') : '-') }}
                        </p>
                    </div>
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Profesional de preferencia</p>
                        <p class="mb-0 fw-semibold">
                            @if($profesionalPreferido)
                                {{ trim(($profesionalPreferido->persona?->nombre ?? '') . ' ' . ($profesionalPreferido->persona?->apellido ?? '')) ?: ('Profesional #' . $profesionalPreferido->id) }}
                            @else
                                Indistinto
                            @endif
                        </p>
                    </div>
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Mi estado en este formulario</p>
                        <p class="mb-0 fw-semibold">
                            @if(($formularioAceptadoPorOtro ?? false) && strcasecmp($estadoProfesionalFormulario, 'Aceptado') !== 0)
                                Aceptado por otro
                            @elseif(strcasecmp($estadoProfesionalFormulario, 'Rechazado') === 0)
                                Rechazado por mí
                            @elseif(strcasecmp($estadoProfesionalFormulario, 'Aceptado') === 0)
                                Aceptado por mí
                            @else
                                Pendiente
                            @endif
                        </p>
                    </div>
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Estado del formulario</p>
                        @php
                            $estadoBaseFormulario = trim((string) ($formulario->estado ?? ''));
                            $estadoFormulario = (($formularioAceptadoPorOtro ?? false)
                                && strcasecmp($estadoProfesionalFormulario, 'Aceptado') !== 0
                                && strcasecmp($estadoBaseFormulario, 'Aceptado') === 0)
                                ? 'Aceptado por otro'
                                : $estadoBaseFormulario;
                            $estadoClase = match (mb_strtolower($estadoFormulario)) {
                                'rechazado por todos' => 'text-bg-danger',
                                'aceptado' => 'text-bg-success',
                                'aceptado por otro' => 'text-bg-secondary',
                                default => 'text-bg-warning',
                            };
                        @endphp
                        <p class="mb-0">
                            <span class="badge {{ $estadoClase }}">{{ $estadoFormulario !== '' ? $estadoFormulario : '-' }}</span>
                        </p>
                    </div>
                    <div class="col-12">
                        <p class="mb-1 text-muted small">Descripción del formulario</p>
                        <div class="border rounded p-3 bg-light-subtle">
                            {{ $formulario->descripcion ?: 'Sin descripción.' }}
                        </div>
                    </div>
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Días de preferencia</p>
                        @if($formulario->diasPreferidos->isNotEmpty())
                            <div class="d-flex flex-wrap gap-2">
                                @foreach($formulario->diasPreferidos as $dia)
                                    <span class="badge text-bg-primary">{{ $dia->descripcion }}</span>
                                @endforeach
                            </div>
                        @else
                            <p class="mb-0">-</p>
                        @endif
                    </div>
                    <div class="col-12 col-md-6">
                        <p class="mb-1 text-muted small">Horario de preferencia</p>
                        @if($formulario->horariosPreferidos->isNotEmpty())
                            <div class="d-flex flex-wrap gap-2">
                                @foreach($formulario->horariosPreferidos as $horario)
                                    <span class="badge text-bg-secondary">{{ $horario->descripcion }}</span>
                                @endforeach
                            </div>
                        @else
                            <p class="mb-0">-</p>
                        @endif
                    </div>
                </div>

                @if($formularioAceptadoPorOtro ?? false)
                    <div class="alert alert-secondary mt-4 mb-0" role="alert">
                        Este formulario ya fue aceptado por otro profesional. No podés rechazarlo ni asignarle un turno.
                    </div>
                @endif

                <div class="d-flex flex-wrap justify-content-center gap-2 mt-4">
                    @if(!($formularioAceptadoPorOtro ?? false))
                        @if(strcasecmp($estadoProfesionalFormulario, 'Aceptado') === 0)
                            <form method="POST" action="/profesional/formularios/{{ $formulario->id }}/rechazar" onsubmit="return confirm('¿Confirmás devolver este formulario a pendiente?');">
                                @csrf
                                <button type="submit" class="btn btn-outline-secondary">Devolver formulario</button>
                            </form>
                        @else
                            <form method="POST" action="/profesional/formularios/{{ $formulario->id }}/rechazar" onsubmit="return confirm('¿Confirmás rechazar este formulario?');">
                                @csrf
                                <button type="submit" class="btn btn-outline-danger">Rechazar</button>
                            </form>
                            <button type="button" class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#modalAsignarTurnoManual">Asignar turno manual</button>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalAsignarTurnoAutomatico">Asignar turno automático</button>
                        @endif
                    @endif
                </div>
            </div>
        </div>
    </main>

    <div class="modal fade" id="modalAsignarTurnoAutomatico" tabindex="-1" aria-labelledby="modalAsignarTurnoAutomaticoLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title fs-5" id="modalAsignarTurnoAutomaticoLabel">Asignación automática de turno</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-3">La sugerencia se calcula desde el día siguiente y respetando la agenda configurada.</p>

                    @if($turnoAutomaticoSugerido)
                        <div class="alert alert-info mb-0" role="alert">
                            <p class="mb-1"><strong>Día sugerido:</strong> {{ $turnoAutomaticoSugerido['inicio']->format('d/m/Y') }}</p>
                            <p class="mb-0"><strong>Horario sugerido:</strong> {{ $turnoAutomaticoSugerido['inicio']->format('H:i') }}</p>
                        </div>
                    @else
                        <div class="alert alert-warning mb-0" role="alert">
                            No se encontró un turno disponible en los próximos 90 días desde mañana.
                        </div>
                    @endif
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">No aceptar</button>
                    @if($turnoAutomaticoSugerido)
                        <form method="POST" action="/profesional/formularios/{{ $formulario->id }}/asignar-turno-automatico" class="m-0">
                            @csrf
                            <button type="submit" class="btn btn-primary">Aceptar y asignar turno</button>
                        </form>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalAsignarTurnoManual" tabindex="-1" aria-labelledby="modalAsignarTurnoManualLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" action="/profesional/formularios/{{ $formulario->id }}/asignar-turno-manual">
                    @csrf
                    <div class="modal-header">
                        <h2 class="modal-title fs-5" id="modalAsignarTurnoManualLabel">Asignar turno manual</h2>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="fecha_turno" class="form-label">Fecha de turno</label>
                            <input type="date" class="form-control" id="fecha_turno" name="fecha_turno" value="{{ old('fecha_turno') }}" min="{{ now()->toDateString() }}" required>
                        </div>
                        <div class="mb-0">
                            <label for="hora_turno" class="form-label">Horario</label>
                            <input type="time" class="form-control" id="hora_turno" name="hora_turno" value="{{ old('hora_turno') }}" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" data-bs-target="#modalAgendaProfesional" data-bs-toggle="modal" data-bs-dismiss="modal">Ver agenda</button>
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Guardar turno</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @php
        $formularioTurnoManualWarning = session('formulario_turno_manual_warning');
    @endphp

    <div class="modal fade" id="modalAdvertenciaAsignarTurnoManual" tabindex="-1" aria-labelledby="modalAdvertenciaAsignarTurnoManualLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title fs-5" id="modalAdvertenciaAsignarTurnoManualLabel">Advertencia al asignar turno</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-2">El día u horario elegido coincide con restricciones de agenda.</p>
                    <ul class="mb-0 ps-3">
                        @foreach(($formularioTurnoManualWarning['advertencias'] ?? []) as $advertencia)
                            <li>{{ $advertencia }}</li>
                        @endforeach
                    </ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">No aceptar</button>
                    <form method="POST" action="/profesional/formularios/{{ $formulario->id }}/asignar-turno-manual" class="m-0">
                        @csrf
                        <input type="hidden" name="omitir_restricciones" value="1">
                        <input type="hidden" name="fecha_turno" value="{{ $formularioTurnoManualWarning['inputs']['fecha_turno'] ?? '' }}">
                        <input type="hidden" name="hora_turno" value="{{ $formularioTurnoManualWarning['inputs']['hora_turno'] ?? '' }}">
                        <button type="submit" class="btn btn-primary">Aceptar igualmente</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modalAgendaProfesional" tabindex="-1" aria-labelledby="modalAgendaProfesionalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title fs-5" id="modalAgendaProfesionalLabel">Agenda del profesional</h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div id="agenda-modal-profesional"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-target="#modalAsignarTurnoManual" data-bs-toggle="modal" data-bs-dismiss="modal">Volver a asignar turno</button>
                </div>
            </div>
        </div>
    </div>

    <button type="button" id="openAsignarTurnoModal" class="d-none" data-bs-toggle="modal" data-bs-target="#modalAsignarTurnoManual"></button>
    <button type="button" id="openAdvertenciaTurnoManualModal" class="d-none" data-bs-toggle="modal" data-bs-target="#modalAdvertenciaAsignarTurnoManual"></button>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const eventosAgenda = @json($agendaEventosProfesional ?? []);
            const modalAgendaEl = document.getElementById('modalAgendaProfesional');
            const agendaEl = document.getElementById('agenda-modal-profesional');

            let calendar = null;

            if (modalAgendaEl && agendaEl) {
                modalAgendaEl.addEventListener('shown.bs.modal', function () {
                    if (!calendar) {
                        calendar = new FullCalendar.Calendar(agendaEl, {
                            locale: window.FullCalendarLocales?.es || 'es',
                            plugins: [
                                window.FullCalendarPlugins?.dayGridPlugin,
                                window.FullCalendarPlugins?.timeGridPlugin,
                                window.FullCalendarPlugins?.interactionPlugin,
                            ].filter(Boolean),
                            initialView: 'timeGridWeek',
                            headerToolbar: {
                                left: 'prev,next today',
                                center: 'title',
                                right: 'dayGridMonth,timeGridWeek,timeGridDay'
                            },
                            buttonText: {
                                today: 'Hoy',
                                month: 'Mes',
                                week: 'Semana',
                                day: 'Día'
                            },
                            height: 'auto',
                            contentHeight: 'auto',
                            eventDisplay: 'block',
                            eventOverlap: true,
                            eventOrder: 'start,-duration,allDay,title',
                            eventDidMount: function (info) {
                                const props = info.event.extendedProps || {};
                                if (props.tipoEvento) {
                                    return;
                                }

                                const harness = info.el.closest('.fc-timegrid-event-harness');
                                if (harness) {
                                    harness.style.left = '0px';
                                    harness.style.right = '0px';
                                }
                            },
                            events: eventosAgenda,
                        });
                        calendar.render();
                    } else {
                        calendar.updateSize();
                    }
                });
            }

            const abrirModalSeguro = (modalElement, triggerElement) => {
                if (!modalElement) {
                    return;
                }

                if (window.bootstrap?.Modal) {
                    window.bootstrap.Modal.getOrCreateInstance(modalElement).show();
                    return;
                }

                triggerElement?.click();
            };

            @if($formularioTurnoManualWarning)
                const modalAdvertencia = document.getElementById('modalAdvertenciaAsignarTurnoManual');
                const botonAbrirAdvertencia = document.getElementById('openAdvertenciaTurnoManualModal');
                abrirModalSeguro(modalAdvertencia, botonAbrirAdvertencia);
            @elseif($errors->any())
                const openModalBtn = document.getElementById('openAsignarTurnoModal');
                const modalAsignarTurnoManual = document.getElementById('modalAsignarTurnoManual');
                abrirModalSeguro(modalAsignarTurnoManual, openModalBtn);
            @endif
        });
    </script>

    @include('partials.reportar-falla-boton')
</body>
</html>



