@extends('layouts.admin')

@section('content')
<div class="p-6">
    <!-- Encabezado -->
    <div class="mb-8 flex items-center justify-between">
        <div>
            <a href="{{ route('admin.orders.list') }}" class="inline-flex items-center text-blue-600 hover:text-blue-800 mb-2">
                <i class="fas fa-arrow-left mr-2"></i>
                Volver a Lista de Órdenes
            </a>
            <h1 class="text-3xl font-bold text-gray-900">Orden de Servicio #{{ $orden->id }}</h1>
            <p class="text-gray-600 mt-2">Creada el {{ $orden->created_at->format('d/m/Y H:i') }}</p>
        </div>
        <div class="text-right">
            @if($orden->estado === 'pendiente')
                <span class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-yellow-100 text-yellow-800">
                    <span class="w-3 h-3 bg-yellow-600 rounded-full mr-2"></span>
                    Pendiente
                </span>
            @elseif($orden->estado === 'en_proceso')
                <span class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-purple-100 text-purple-800">
                    <span class="w-3 h-3 bg-purple-600 rounded-full mr-2"></span>
                    En Proceso
                </span>
            @elseif($orden->estado === 'atendido')
                <span class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-green-100 text-green-800">
                    <span class="w-3 h-3 bg-green-600 rounded-full mr-2"></span>
                    Atendido
                </span>
            @else
                <span class="inline-flex items-center px-4 py-2 rounded-full text-sm font-semibold bg-red-100 text-red-800">
                    <span class="w-3 h-3 bg-red-600 rounded-full mr-2"></span>
                    Cancelado
                </span>
            @endif
        </div>
    </div>

    <!-- Grid de Contenido -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Columna Izquierda - Información del Usuario (2/3) -->
        <div class="lg:col-span-2">
            <!-- Tarjeta de Información del Usuario -->
            <div class="bg-white rounded-lg shadow p-6 mb-6">
                <h2 class="text-xl font-bold text-gray-900 mb-4">Información del Cliente</h2>
                <div class="mb-4">
                    <form id="asignarTrabajadorForm" method="POST" action="{{ route('admin.orders.assignTrabajador', $orden->id) }}">
                        @csrf
                        <label for="trabajadorSelect" class="text-xs text-gray-500 uppercase font-semibold">Trabajado por</label>
                        <select id="trabajadorSelect" name="trabajado_por" class="w-full px-4 py-2 border border-gray-300 rounded-lg mt-1">
                            <option value="">Sin asignar</option>
                            @foreach(App\Models\User::where('role', 'admin')->get() as $admin)
                                <option value="{{ $admin->id }}" @if($orden->trabajado_por == $admin->id) selected @endif>{{ $admin->name }}</option>
                            @endforeach
                        </select>
                        <button type="submit" class="mt-2 inline-flex items-center px-4 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition">
                            <i class="fas fa-user-check mr-2"></i> Asignar Responsable
                        </button>
                    </form>
                </div>
                <div class="flex items-start">
                    <div class="w-16 h-16 rounded-full bg-gradient-to-br from-blue-400 to-blue-600 flex items-center justify-center flex-shrink-0 mr-6">
                        <span class="text-2xl font-bold text-white">
                            {{ strtoupper(substr($orden->user->name, 0, 1)) }}
                        </span>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-lg font-bold text-gray-900">{{ $orden->user->name }}</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Correo</p>
                                <p class="text-gray-900 mt-1">{{ $orden->user->email }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Teléfono</p>
                                <p class="text-gray-900 mt-1">
                                    @if($orden->user->phone)
                                        {{ $orden->user->phone }}
                                    @else
                                        <span class="text-gray-400">No proporcionado</span>
                                    @endif
                                </p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Institución</p>
                                <p class="text-gray-900 mt-1">{{ $pago ? $pago->nombre_ie : 'No disponible' }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Código Local</p>
                                <p class="text-gray-900 mt-1">{{ $pago ? $pago->codigo_local : 'No disponible' }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Tipo de Gestión</p>
                                <p class="text-gray-900 mt-1">{{ $pago ? ($pago->tipo_gestion ?: 'No especificado') : 'No disponible' }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Método de Pago</p>
                                <p class="text-gray-900 mt-1">{{ $pago ? $pago->metodo_pago : 'No disponible' }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Usuario desde</p>
                                <p class="text-gray-900 mt-1">{{ $orden->user->created_at->format('d/m/Y') }}</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase font-semibold">Orden creada</p>
                                <p class="text-gray-900 mt-1">{{ $orden->created_at->format('d/m/Y H:i') }}</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Botón de Reportes de Diagnóstico -->
                <div class="mt-6 pt-6 border-t border-gray-200">
                    <a href="{{ route('hojas-resumen', ['userId' => $orden->user->id]) }}" class="inline-flex items-center px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition shadow-md hover:shadow-lg">
                        <i class="fas fa-chart-bar mr-2"></i>
                        Ver Reportes de Diagnóstico
                    </a>
                </div>
            </div>

            <!-- Tarjeta de Documentos -->
            <div class="bg-white rounded-lg shadow p-6 mb-6">
                <h2 class="text-xl font-bold text-gray-900 mb-4">Estado de Documentos</h2>
                
                <div id="documentProgress" class="mb-6">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm font-medium text-gray-700">Progreso: <strong id="docCount">{{ $orden->documentosGenerados() }}</strong>/4</span>
                        <span class="text-xs text-gray-500">
                            <strong id="docPercent">{{ floor($orden->documentosGenerados() / 4 * 100) }}</strong>%
                        </span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div id="docBar" class="bg-green-600 h-2 rounded-full transition-all duration-300" style="width: {{ floor($orden->documentosGenerados() / 4 * 100) }}%"></div>
                    </div>
                </div>

                <!-- Lista de Documentos -->
                <div class="space-y-3">
                    <!-- PEI -->
                    <div class="flex items-center p-4 rounded-lg border-2 {{ $orden->pei_generado ? 'border-green-300 bg-green-50' : 'border-gray-200 bg-white' }} hover:shadow transition">
                        <div class="flex-shrink-0">
                            <input type="checkbox" id="peiCheckbox" class="w-5 h-5 text-green-600 rounded cursor-pointer" {{ $orden->pei_generado ? 'checked' : '' }} onchange="toggleDocument('pei')">
                        </div>
                        <label for="peiCheckbox" class="flex-1 ml-4 cursor-pointer">
                            <p class="text-sm font-medium text-gray-900">PEI - Proyecto Educativo Institucional</p>
                            <p class="text-xs text-gray-500 mt-1">Proyecto educativo institucional completo</p>
                        </label>
                        @if($orden->pei_generado)
                            <span class="inline-flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white">
                                <i class="fas fa-check text-sm"></i>
                            </span>
                        @endif
                    </div>

                    <!-- PAT -->
                    <div class="flex items-center p-4 rounded-lg border-2 {{ $orden->pat_generado ? 'border-green-300 bg-green-50' : 'border-gray-200 bg-white' }} hover:shadow transition">
                        <div class="flex-shrink-0">
                            <input type="checkbox" id="patCheckbox" class="w-5 h-5 text-green-600 rounded cursor-pointer" {{ $orden->pat_generado ? 'checked' : '' }} onchange="toggleDocument('pat')">
                        </div>
                        <label for="patCheckbox" class="flex-1 ml-4 cursor-pointer">
                            <p class="text-sm font-medium text-gray-900">PAT - Plan Anual de Trabajo</p>
                            <p class="text-xs text-gray-500 mt-1">Planificación anual de trabajo institucional</p>
                        </label>
                        @if($orden->pat_generado)
                            <span class="inline-flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white">
                                <i class="fas fa-check text-sm"></i>
                            </span>
                        @endif
                    </div>

                    <!-- PCI -->
                    <div class="flex items-center p-4 rounded-lg border-2 {{ $orden->pci_generado ? 'border-green-300 bg-green-50' : 'border-gray-200 bg-white' }} hover:shadow transition">
                        <div class="flex-shrink-0">
                            <input type="checkbox" id="pciCheckbox" class="w-5 h-5 text-green-600 rounded cursor-pointer" {{ $orden->pci_generado ? 'checked' : '' }} onchange="toggleDocument('pci')">
                        </div>
                        <label for="pciCheckbox" class="flex-1 ml-4 cursor-pointer">
                            <p class="text-sm font-medium text-gray-900">PCI - Proyecto Curricular Institucional</p>
                            <p class="text-xs text-gray-500 mt-1">Proyecto curricular de la institución</p>
                        </label>
                        @if($orden->pci_generado)
                            <span class="inline-flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white">
                                <i class="fas fa-check text-sm"></i>
                            </span>
                        @endif
                    </div>

                    <!-- RI -->
                    <div class="flex items-center p-4 rounded-lg border-2 {{ $orden->ri_generado ? 'border-green-300 bg-green-50' : 'border-gray-200 bg-white' }} hover:shadow transition">
                        <div class="flex-shrink-0">
                            <input type="checkbox" id="riCheckbox" class="w-5 h-5 text-green-600 rounded cursor-pointer" {{ $orden->ri_generado ? 'checked' : '' }} onchange="toggleDocument('ri')">
                        </div>
                        <label for="riCheckbox" class="flex-1 ml-4 cursor-pointer">
                            <p class="text-sm font-medium text-gray-900">RI - Reglamento Interno</p>
                            <p class="text-xs text-gray-500 mt-1">Reglamento interno de la institución</p>
                        </label>
                        @if($orden->ri_generado)
                            <span class="inline-flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white">
                                <i class="fas fa-check text-sm"></i>
                            </span>
                        @endif
                    </div>

                    <!-- OTROS -->
                    <div class="flex items-center p-4 rounded-lg border-2 {{ $orden->otros_docs_generado ? 'border-green-300 bg-green-50' : 'border-gray-200 bg-white' }} hover:shadow transition">
                        <div class="flex-shrink-0">
                            <input type="checkbox" id="otrosCheckbox" class="w-5 h-5 text-green-600 rounded cursor-pointer" {{ $orden->otros_docs_generado ? 'checked' : '' }} onchange="toggleDocument('otros')">
                        </div>
                        <label for="otrosCheckbox" class="flex-1 ml-4 cursor-pointer">
                            <p class="text-sm font-medium text-gray-900">Otros Documentos</p>
                            <p class="text-xs text-gray-500 mt-1">Documentos complementarios y anexos de la orden</p>
                        </label>
                        @if($orden->otros_docs_generado)
                            <span class="inline-flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white">
                                <i class="fas fa-check text-sm"></i>
                            </span>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Tarjeta de Notas -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-bold text-gray-900 mb-4">Notas de la Orden</h2>
                <textarea id="notasText" rows="5" placeholder="Agregue notas o comentarios sobre el progreso de la orden..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none">{{ $orden->notas }}</textarea>
                <button onclick="guardarNotas()" class="mt-3 inline-flex items-center px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition">
                    <i class="fas fa-save mr-2"></i>
                    Guardar Notas
                </button>
            </div>
        </div>

        <!-- Columna Derecha - Estado (1/3) -->
        <div>
            <!-- Tarjeta de Cambio de Estado -->
            <div class="bg-white rounded-lg shadow p-6 sticky top-6">
                <h2 class="text-lg font-bold text-gray-900 mb-4">Cambiar Estado</h2>
                
                <div class="space-y-2">
                    <button onclick="cambiarEstado('pendiente')" class="w-full px-4 py-3 text-left rounded-lg border-2 {{ $orden->estado === 'pendiente' ? 'border-yellow-500 bg-yellow-50' : 'border-gray-200 hover:border-gray-300' }} transition {{ $orden->estado === 'pendiente' ? 'bg-yellow-50' : '' }}">
                        <span class="flex items-center">
                            <span class="w-3 h-3 rounded-full {{ $orden->estado === 'pendiente' ? 'bg-yellow-600' : 'bg-gray-400' }} mr-3"></span>
                            <span class="text-sm font-medium text-gray-900">Pendiente</span>
                        </span>
                        <span class="text-xs text-gray-500 ml-6">Esperando procesamiento</span>
                    </button>

                    <button onclick="cambiarEstado('en_proceso')" class="w-full px-4 py-3 text-left rounded-lg border-2 {{ $orden->estado === 'en_proceso' ? 'border-purple-500 bg-purple-50' : 'border-gray-200 hover:border-gray-300' }} transition {{ $orden->estado === 'en_proceso' ? 'bg-purple-50' : '' }}">
                        <span class="flex items-center">
                            <span class="w-3 h-3 rounded-full {{ $orden->estado === 'en_proceso' ? 'bg-purple-600' : 'bg-gray-400' }} mr-3"></span>
                            <span class="text-sm font-medium text-gray-900">En Proceso</span>
                        </span>
                        <span class="text-xs text-gray-500 ml-6">Generando documentos</span>
                    </button>

                    <button onclick="cambiarEstado('atendido')" class="w-full px-4 py-3 text-left rounded-lg border-2 {{ $orden->estado === 'atendido' ? 'border-green-500 bg-green-50' : 'border-gray-200 hover:border-gray-300' }} transition {{ $orden->estado === 'atendido' ? 'bg-green-50' : '' }}">
                        <span class="flex items-center">
                            <span class="w-3 h-3 rounded-full {{ $orden->estado === 'atendido' ? 'bg-green-600' : 'bg-gray-400' }} mr-3"></span>
                            <span class="text-sm font-medium text-gray-900">Atendido</span>
                        </span>
                        <span class="text-xs text-gray-500 ml-6">Completado exitosamente</span>
                    </button>

                    <button onclick="cambiarEstado('cancelado')" class="w-full px-4 py-3 text-left rounded-lg border-2 {{ $orden->estado === 'cancelado' ? 'border-red-500 bg-red-50' : 'border-gray-200 hover:border-gray-300' }} transition {{ $orden->estado === 'cancelado' ? 'bg-red-50' : '' }}">
                        <span class="flex items-center">
                            <span class="w-3 h-3 rounded-full {{ $orden->estado === 'cancelado' ? 'bg-red-600' : 'bg-gray-400' }} mr-3"></span>
                            <span class="text-sm font-medium text-gray-900">Cancelado</span>
                        </span>
                        <span class="text-xs text-gray-500 ml-6">Orden no procesada</span>
                    </button>
                </div>

                <!-- Información adicional -->
                <div class="mt-6 pt-6 border-t border-gray-200">
                    <div class="bg-blue-50 rounded-lg p-3 mb-4">
                        <p class="text-xs text-blue-800 font-semibold">Estado actual:</p>
                        <p class="text-sm text-blue-900 capitalize mt-1">{{ str_replace('_', ' ', $orden->estado) }}</p>
                    </div>

                    @if($orden->fecha_atencion)
                        <div class="bg-green-50 rounded-lg p-3">
                            <p class="text-xs text-green-800 font-semibold">Fecha de atención:</p>
                            <p class="text-sm text-green-900 mt-1">{{ $orden->fecha_atencion->format('d/m/Y H:i') }}</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script>
const ordenId = {{ $orden->id }};

function cambiarEstado(nuevoEstado) {
    const original = '{{ $orden->estado }}';
    if (nuevoEstado === original) return;

    fetch(`/admin/ordenes/${ordenId}/estado`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ estado: nuevoEstado })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    })
    .catch(error => {
        alert('Error al cambiar el estado');
        console.error(error);
    });
}

function toggleDocument(tipoDocumento) {
    fetch(`/admin/ordenes/${ordenId}/documento`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ documento: tipoDocumento })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Actualizar la interfaz sin recargar
            document.getElementById('docCount').textContent = data.documentosGenerados;
            const percent = Math.floor((data.documentosGenerados / 4) * 100);
            document.getElementById('docPercent').textContent = percent;
            document.getElementById('docBar').style.width = percent + '%';
            
            // Recargar después de 500ms para actualizar los badges
            setTimeout(() => location.reload(), 500);
        }
    })
    .catch(error => {
        alert('Error al actualizar el documento');
        console.error(error);
    });
}

function guardarNotas() {
    const notas = document.getElementById('notasText').value;
    
    fetch(`/admin/ordenes/${ordenId}/nota`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ notas: notas })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Mostrar confirmación visual
            const btn = event.target;
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-check mr-2"></i>Guardado';
            btn.classList.remove('hover:bg-blue-700');
            btn.classList.add('bg-green-600');
            
            setTimeout(() => {
                btn.innerHTML = originalText;
                btn.classList.remove('bg-green-600');
                btn.classList.add('hover:bg-blue-700');
            }, 2000);
        }
    })
    .catch(error => {
        alert('Error al guardar las notas');
        console.error(error);
    });
}
</script>

<meta name="csrf-token" content="{{ csrf_token() }}">
@endsection
