

<?php $__env->startSection('title', 'Ticket #' . $ticket->ticket_number); ?>
<?php $__env->startSection('page-title', 'Detalle del Ticket #' . $ticket->ticket_number); ?>

<?php $__env->startSection('content'); ?>
<?php if (isset($component)) { $__componentOriginale19f62b34dfe0bfdf95075badcb45bc2 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginale19f62b34dfe0bfdf95075badcb45bc2 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.breadcrumb','data' => ['items' => [
    ['label' => 'Tickets', 'url' => route('tickets.index'), 'icon' => 'ticket'],
    ['label' => $ticket->ticket_number, 'active' => true]
]]] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('breadcrumb'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(Illuminate\View\AnonymousComponent::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['items' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute([
    ['label' => 'Tickets', 'url' => route('tickets.index'), 'icon' => 'ticket'],
    ['label' => $ticket->ticket_number, 'active' => true]
])]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginale19f62b34dfe0bfdf95075badcb45bc2)): ?>
<?php $attributes = $__attributesOriginale19f62b34dfe0bfdf95075badcb45bc2; ?>
<?php unset($__attributesOriginale19f62b34dfe0bfdf95075badcb45bc2); ?>
<?php endif; ?>
<?php if (isset($__componentOriginale19f62b34dfe0bfdf95075badcb45bc2)): ?>
<?php $component = $__componentOriginale19f62b34dfe0bfdf95075badcb45bc2; ?>
<?php unset($__componentOriginale19f62b34dfe0bfdf95075badcb45bc2); ?>
<?php endif; ?>

<div class="row">
    <!-- Ticket Details -->
    <div class="col-lg-8">
        <div class="card mb-3">
            <div class="card-header bg-white">
                <div class="d-flex justify-content-between align-items-center">
                    <h4 class="mb-0"><?php echo e($ticket->title); ?></h4>
                    <div>
                        <?php
                            $wasReopened = $ticket->activities()->where('action', 'reopened')->exists();
                        ?>
                        
                        <?php if($wasReopened): ?>
                        <span class="badge bg-warning text-dark me-2" title="Este ticket fue reabierto">
                            <i class="bi bi-arrow-counterclockwise"></i> Reabierto
                        </span>
                        <?php endif; ?>
                        
                        <span class="badge badge-priority-<?php echo e($ticket->priority); ?> me-2">
                            <?php echo e(ucfirst($ticket->priority)); ?>

                        </span>
                        <span class="badge badge-status-<?php echo e($ticket->status); ?>">
                            <?php echo e(ucfirst(str_replace('_', ' ', $ticket->status))); ?>

                        </span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-4">
                    <h6 class="text-muted mb-2">Descripción</h6>
                    <p style="white-space: pre-wrap;"><?php echo e($ticket->description); ?></p>
                </div>
                
                <?php if($ticket->resolution_notes): ?>
                <div class="alert alert-success">
                    <h6 class="alert-heading"><i class="bi bi-check-circle me-2"></i>Notas de Resolución</h6>
                    <p class="mb-0" style="white-space: pre-wrap;"><?php echo e($ticket->resolution_notes); ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Comments Section -->
        <div class="card">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="bi bi-chat-dots me-2"></i>Comentarios</h5>
            </div>
            <div class="card-body">
                <?php $__empty_1 = true; $__currentLoopData = $ticket->comments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $comment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <?php
                    $isReopenComment = strpos($comment->content, '🔄 **Ticket Reabierto**') !== false;
                ?>
                <div class="d-flex mb-3 pb-3 border-bottom <?php echo e($isReopenComment ? 'bg-warning bg-opacity-10 p-2 rounded' : ''); ?>">
                    <div class="flex-shrink-0">
                        <div class="bg-<?php echo e($isReopenComment ? 'warning' : 'primary'); ?> text-<?php echo e($isReopenComment ? 'dark' : 'white'); ?> rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                            <?php if($isReopenComment): ?>
                            <i class="bi bi-arrow-counterclockwise"></i>
                            <?php else: ?>
                            <?php echo e(substr($comment->user->name, 0, 1)); ?>

                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <strong><?php echo e($comment->user->name); ?></strong>
                                <span class="badge <?php echo e(role_badge_class($comment->user->role)); ?> ms-2"><?php echo e(role_name($comment->user->role)); ?></span>
                                <?php if($isReopenComment): ?>
                                <span class="badge bg-warning text-dark ms-1">
                                    <i class="bi bi-exclamation-triangle"></i> Reapertura
                                </span>
                                <?php endif; ?>
                            </div>
                            <small class="text-muted"><?php echo e($comment->created_at->diffForHumans()); ?></small>
                        </div>
                        <p class="mb-0 mt-2" style="white-space: pre-wrap;"><?php echo nl2br(e($comment->content)); ?></p>
                        
                        
                        <?php if(config('app.debug')): ?>
                        <small class="text-muted">DEBUG: <?php echo e($comment->attachments->count()); ?> archivo(s) adjunto(s)</small>
                        <?php endif; ?>
                        
                        <?php if($comment->attachments->count() > 0): ?>
                        <div class="mt-3">
                            <small class="text-muted"><i class="bi bi-paperclip me-1"></i>Archivos adjuntos:</small>
                            <div class="mt-2">
                                <?php $__currentLoopData = $comment->attachments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $attachment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <div class="d-inline-flex align-items-center me-3 mb-2">
                                    <?php if(str_starts_with($attachment->mime_type, 'image/')): ?>
                                    <a href="<?php echo e(Storage::url($attachment->file_path)); ?>" target="_blank" class="text-decoration-none">
                                        <img src="<?php echo e(Storage::url($attachment->file_path)); ?>" 
                                             alt="<?php echo e($attachment->original_name); ?>" 
                                             class="img-thumbnail" 
                                             style="max-width: 150px; max-height: 150px; cursor: pointer;"
                                             title="<?php echo e($attachment->original_name); ?>">
                                    </a>
                                    <?php else: ?>
                                    <a href="<?php echo e(Storage::url($attachment->file_path)); ?>" 
                                       download="<?php echo e($attachment->original_name); ?>"
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-file-earmark"></i> <?php echo e(Str::limit($attachment->original_name, 20)); ?>

                                        <small class="text-muted">(<?php echo e(number_format($attachment->file_size / 1024, 1)); ?> KB)</small>
                                    </a>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <p class="text-muted text-center">No hay comentarios todavía</p>
                <?php endif; ?>
                
                <!-- Add Comment Form -->
                <?php
                    $user = auth()->user();
                    $canComment = false;
                    
                    if ($user->role === 'administrador') {
                        $canComment = true;
                    } elseif ($user->role === 'solicitante') {
                        $canComment = ($ticket->requester_id === $user->id);
                    } elseif (in_array($user->role, ['responsable', 'ingeniero', 'supervisor'])) {
                        $assignedProjectIds = $user->getAssignedProjectIds();
                        $canComment = ($ticket->assigned_to === $user->id) ||
                                      ($ticket->requester_id === $user->id) ||
                                      (in_array($ticket->project_id, $assignedProjectIds));
                    }
                ?>
                
                <?php if($ticket->status != 'cerrado' && $canComment): ?>
                <div class="mt-4">
                    <h6>Agregar Comentario</h6>
                    <form method="POST" action="<?php echo e(route('tickets.comments.store', $ticket)); ?>" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <div class="mb-3">
                            <textarea class="form-control" name="comment" rows="3" placeholder="Escribe tu comentario..." required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="comment_attachments" class="form-label">
                                <i class="bi bi-paperclip me-1"></i>Adjuntar Archivos (Opcional)
                            </label>
                            <input type="file" 
                                   class="form-control" 
                                   id="comment_attachments" 
                                   name="attachments[]" 
                                   multiple 
                                   accept="image/*,.pdf,.doc,.docx,.txt">
                            <div class="form-text">
                                Puedes adjuntar imágenes, documentos o archivos (máx. 10MB por archivo)
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-send me-2"></i>Enviar Comentario
                        </button>
                    </form>
                </div>
                <?php elseif($ticket->status != 'cerrado'): ?>
                <div class="mt-4">
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        No tienes permisos para comentar en este ticket. Solo puedes comentar en tickets de tus proyectos asignados.
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Sidebar Info -->
    <div class="col-lg-4">
        <div class="card mb-3">
            <div class="card-header bg-white">
                <h6 class="mb-0">Información del Ticket</h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <small class="text-muted d-block">ID del Ticket</small>
                    <strong><?php echo e($ticket->ticket_number); ?></strong>
                </div>
                
                <div class="mb-3">
                    <small class="text-muted d-block">Proyecto</small>
                    <?php if($ticket->project): ?>
                    <strong><?php echo e($ticket->project->name); ?></strong>
                    <?php else: ?>
                    <span class="text-muted">Sin proyecto</span>
                    <?php endif; ?>
                </div>
                
                <div class="mb-3">
                    <small class="text-muted d-block">Creado por</small>
                    <strong><?php echo e($ticket->requester->name); ?></strong>
                </div>
                
                <div class="mb-3">
                    <small class="text-muted d-block">Asignado a</small>
                    <?php if($ticket->assignedUser): ?>
                    <strong><?php echo e($ticket->assignedUser->name); ?></strong>
                    <?php else: ?>
                    <span class="text-muted">Sin asignar</span>
                    <?php endif; ?>
                </div>
                
                <div class="mb-3">
                    <small class="text-muted d-block">Fecha de Creación</small>
                    <strong><?php echo e($ticket->created_at->format('d/m/Y H:i')); ?></strong>
                </div>
                
                <?php if($ticket->due_date): ?>
                <div class="mb-3">
                    <small class="text-muted d-block">Fecha Límite</small>
                    <strong class="<?php echo e($ticket->isOverdue() ? 'text-danger' : ''); ?>">
                        <?php echo e($ticket->due_date->format('d/m/Y')); ?>

                        <?php if($ticket->isOverdue()): ?>
                        <i class="bi bi-exclamation-triangle ms-1"></i>
                        <?php endif; ?>
                    </strong>
                </div>
                <?php endif; ?>
                
                <?php if($ticket->resolved_at): ?>
                <div class="mb-3">
                    <small class="text-muted d-block">Fecha de Resolución</small>
                    <strong><?php echo e($ticket->resolved_at->format('d/m/Y H:i')); ?></strong>
                </div>
                <?php endif; ?>
                
                <?php if($ticket->closed_at): ?>
                <div class="mb-3">
                    <small class="text-muted d-block">Fecha de Cierre</small>
                    <strong><?php echo e($ticket->closed_at->format('d/m/Y H:i')); ?></strong>
                </div>
                <?php endif; ?>
                
                <?php
                    $reopenCount = $ticket->activities()->where('action', 'reopened')->count();
                ?>
                <?php if($reopenCount > 0): ?>
                <div class="mb-3">
                    <small class="text-muted d-block">Veces Reabierto</small>
                    <strong class="text-warning">
                        <i class="bi bi-arrow-counterclockwise me-1"></i><?php echo e($reopenCount); ?> <?php echo e($reopenCount == 1 ? 'vez' : 'veces'); ?>

                    </strong>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Tiempo de Trabajo -->
        <?php if(in_array(auth()->user()->role, ['responsable', 'ingeniero', 'supervisor', 'administrador'])): ?>
        <div class="card mb-3">
            <div class="card-header bg-white">
                <h6 class="mb-0">
                    <i class="bi bi-clock-history me-2"></i>Tiempo de Trabajo
                </h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <small class="text-muted d-block">Tiempo Total Invertido</small>
                    <strong class="fs-5 text-primary">
                        <?php echo e($ticket->getFormattedTotalWorkTime() ?: '0m'); ?>

                    </strong>
                </div>
                
                <?php
                    $activeSession = $ticket->workSessions()
                        ->where('user_id', auth()->id())
                        ->whereNull('ended_at')
                        ->first();
                ?>
                
                <?php if($activeSession): ?>
                <div class="alert alert-success mb-0">
                    <i class="bi bi-hourglass-split me-2"></i>
                    <strong>Sesión activa</strong><br>
                    <small>Iniciada: <?php echo e($activeSession->started_at->format('H:i:s')); ?></small><br>
                    <small>Tiempo: <span id="session-timer">Calculando...</span></small>
                </div>
                <?php endif; ?>
                
                <?php if($ticket->workSessions->count() > 0): ?>
                <hr>
                <small class="text-muted d-block mb-2">Historial de Sesiones (<?php echo e($ticket->workSessions->count()); ?>)</small>
                <div style="max-height: 200px; overflow-y: auto;">
                    <?php $__currentLoopData = $ticket->workSessions->take(10); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $session): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div class="mb-2 pb-2 border-bottom">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="small">
                                <strong><?php echo e($session->user->name); ?></strong><br>
                                <span class="text-muted"><?php echo e($session->started_at->format('d/m/Y H:i')); ?></span>
                            </div>
                            <span class="badge bg-secondary">
                                <?php echo e($session->formatted_duration); ?>

                            </span>
                        </div>
                    </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Actions -->
        <div class="card">
            <div class="card-header bg-white">
                <h6 class="mb-0">Acciones</h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <?php
                        // Verificar permisos de edición
                        $canEdit = auth()->user()->hasRole(['administrador', 'supervisor']) || 
                                   auth()->id() == $ticket->requester_id;
                        
                        // Verificar permisos para cambiar estado
                        $canChangeStatus = false;
                        if (auth()->user()->hasRole(['administrador'])) {
                            $canChangeStatus = true;
                        } elseif (in_array(auth()->user()->role, ['responsable', 'ingeniero', 'supervisor'])) {
                            $assignedProjectIds = auth()->user()->getAssignedProjectIds();
                            $canChangeStatus = ($ticket->assigned_to === auth()->id()) ||
                                              (in_array($ticket->project_id, $assignedProjectIds));
                        }
                    ?>
                    
                    <?php if($canEdit): ?>
                    <a href="<?php echo e(route('tickets.edit', $ticket)); ?>" class="btn btn-outline-primary">
                        <i class="bi bi-pencil me-2"></i>Editar Ticket
                    </a>
                    <?php endif; ?>
                    
                    <?php if($canChangeStatus && $ticket->status != 'cerrado'): ?>
                    <form method="POST" action="<?php echo e(route('tickets.update', $ticket)); ?>">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PATCH'); ?>
                        <input type="hidden" name="status" value="en_progreso">
                        <?php if($ticket->status == 'abierto'): ?>
                        <button type="submit" class="btn btn-warning w-100">
                            <i class="bi bi-hourglass-split me-2"></i>Iniciar Trabajo
                        </button>
                        <?php endif; ?>
                    </form>
                    
                    <form method="POST" action="<?php echo e(route('tickets.update', $ticket)); ?>">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PATCH'); ?>
                        <input type="hidden" name="status" value="resuelto">
                        <?php if($ticket->status != 'resuelto'): ?>
                        <button type="submit" class="btn btn-success w-100">
                            <i class="bi bi-check-circle me-2"></i>Marcar como Resuelto
                        </button>
                        <?php endif; ?>
                    </form>
                    <?php endif; ?>
                    
                    <?php if(auth()->id() == $ticket->requester_id && $ticket->status == 'resuelto'): ?>
                    <div class="alert alert-info mb-2">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong>¿El problema fue solucionado?</strong><br>
                        <small>Si confirmas que todo funciona correctamente, puedes cerrar este ticket.</small>
                    </div>
                    <button type="button" class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#closeTicketModal">
                        <i class="bi bi-check2-circle me-2"></i>Confirmar y Cerrar Ticket
                    </button>
                    <?php endif; ?>
                    
                    <?php if($ticket->status == 'cerrado'): ?>
                    <button type="button" class="btn btn-warning w-100" data-bs-toggle="modal" data-bs-target="#reopenModal">
                        <i class="bi bi-arrow-counterclockwise me-2"></i>Reabrir Ticket
                    </button>
                    <?php endif; ?>
                    
                    <?php if(!$canChangeStatus && !auth()->user()->hasRole(['administrador'])): ?>
                    <div class="alert alert-info mb-0">
                        <small>
                            <i class="bi bi-info-circle me-1"></i>
                            Solo puedes gestionar tickets de tus proyectos asignados
                        </small>
                    </div>
                    <?php endif; ?>
                    
                    <a href="<?php echo e(route('tickets.index')); ?>" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left me-2"></i>Volver a Lista
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal para Reabrir Ticket -->
<div class="modal fade" id="reopenModal" tabindex="-1" aria-labelledby="reopenModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning text-white">
                <h5 class="modal-title" id="reopenModalLabel">
                    <i class="bi bi-arrow-counterclockwise me-2"></i>Reabrir Ticket
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="<?php echo e(route('tickets.reopen', $ticket)); ?>">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PATCH'); ?>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        <strong>¿Estás seguro de reabrir este ticket?</strong>
                        <p class="mb-0 mt-2 small">El ticket pasará de estado "Cerrado" a "Abierto" y deberá ser atendido nuevamente.</p>
                    </div>
                    
                    <div class="mb-3">
                        <label for="reopen_reason" class="form-label">
                            <strong>Motivo de Reapertura <span class="text-danger">*</span></strong>
                        </label>
                        <textarea class="form-control" 
                                  id="reopen_reason" 
                                  name="reopen_reason" 
                                  rows="4" 
                                  placeholder="Explica por qué necesitas reabrir este ticket. Ej: El problema persiste, se encontró un nuevo error relacionado, etc."
                                  required></textarea>
                        <div class="form-text">
                            <i class="bi bi-info-circle me-1"></i>
                            Es obligatorio indicar el motivo para mantener un registro claro.
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>Cancelar
                    </button>
                    <button type="submit" class="btn btn-warning">
                        <i class="bi bi-arrow-counterclockwise me-1"></i>Reabrir Ticket
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para Cerrar Ticket (Cliente) -->
<div class="modal fade" id="closeTicketModal" tabindex="-1" aria-labelledby="closeTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="closeTicketModalLabel">
                    <i class="bi bi-check2-circle me-2"></i>Cerrar Ticket
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="<?php echo e(route('tickets.close', $ticket)); ?>">
                <?php echo csrf_field(); ?>
                <?php echo method_field('PATCH'); ?>
                <div class="modal-body">
                    <div class="alert alert-success">
                        <i class="bi bi-check-circle me-2"></i>
                        <strong>¿Confirmas que el problema fue solucionado?</strong>
                        <p class="mb-0 mt-2 small">Al cerrar este ticket, confirmas que el servicio técnico resolvió satisfactoriamente tu solicitud.</p>
                    </div>
                    
                    <div class="mb-3">
                        <label for="close_comment" class="form-label">
                            <strong>Comentario de Cierre (Opcional)</strong>
                        </label>
                        <textarea class="form-control" 
                                  id="close_comment" 
                                  name="close_comment" 
                                  rows="3" 
                                  placeholder="Puedes agregar un comentario final sobre la solución recibida (opcional)"></textarea>
                        <div class="form-text">
                            <i class="bi bi-info-circle me-1"></i>
                            Si el problema persiste, NO cierres el ticket. En su lugar, agrega un comentario explicando la situación.
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>Cancelar
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="bi bi-check2-circle me-1"></i>Confirmar y Cerrar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Prevenir envío duplicado del formulario de comentarios
    const commentForm = document.querySelector('form[action="<?php echo e(route('tickets.comments.store', $ticket)); ?>"]');
    if (commentForm) {
        let isSubmitting = false;
        commentForm.addEventListener('submit', function(e) {
            if (isSubmitting) {
                e.preventDefault();
                return false;
            }
            isSubmitting = true;
            // Deshabilitar el botón de envío
            const submitButton = commentForm.querySelector('button[type="submit"]');
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Enviando...';
            }
        });
    }
    
    <?php if(isset($activeSession) && $activeSession): ?>
    // Variables para el timer
    let startTime = new Date('<?php echo e($activeSession->started_at->toIso8601String()); ?>');
    let sessionId = <?php echo e($activeSession->id); ?>;
    let ticketId = <?php echo e($ticket->id); ?>;
    let timerElement = document.getElementById('session-timer');
    
    // Actualizar el timer cada segundo
    function updateTimer() {
        let now = new Date();
        let diff = Math.floor((now - startTime) / 1000); // diferencia en segundos
        
        let hours = Math.floor(diff / 3600);
        let minutes = Math.floor((diff % 3600) / 60);
        let seconds = diff % 60;
        
        let timeString = '';
        if (hours > 0) {
            timeString = `${hours}h ${minutes}m ${seconds}s`;
        } else if (minutes > 0) {
            timeString = `${minutes}m ${seconds}s`;
        } else {
            timeString = `${seconds}s`;
        }
        
        if (timerElement) {
            timerElement.textContent = timeString;
        }
    }
    
    // Actualizar cada segundo
    setInterval(updateTimer, 1000);
    updateTimer(); // Primera actualización inmediata
    
    // Heartbeat: enviar señal cada 30 segundos para mantener la sesión activa
    function sendHeartbeat() {
        fetch('<?php echo e(route("tickets.work-session.heartbeat", $ticket)); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (!data.active) {
                console.log('Sesión no activa');
            }
        })
        .catch(error => console.error('Error en heartbeat:', error));
    }
    
    // Enviar heartbeat cada 30 segundos
    setInterval(sendHeartbeat, 30000);
    
    // Cerrar sesión al salir de la página
    window.addEventListener('beforeunload', function(e) {
        // Usar sendBeacon para enviar la solicitud de manera confiable
        const url = '<?php echo e(route("tickets.work-session.end", $ticket)); ?>';
        const data = new FormData();
        data.append('_token', '<?php echo e(csrf_token()); ?>');
        
        navigator.sendBeacon(url, data);
    });
    
    // También cerrar sesión si el usuario navega a otra página
    window.addEventListener('pagehide', function(e) {
        const url = '<?php echo e(route("tickets.work-session.end", $ticket)); ?>';
        const data = new FormData();
        data.append('_token', '<?php echo e(csrf_token()); ?>');
        
        navigator.sendBeacon(url, data);
    });
    <?php endif; ?>
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp_1\htdocs\Ticketera\resources\views/tickets/show.blade.php ENDPATH**/ ?>