templates/administracion/ticketsView.html.twig line 1

Open in your IDE?
  1. {% extends 'base.html.twig' %}
    {% block title %}Tickets{% endblock %}
    {% block breadcrumb %}Tickets{% endblock %}
    {% block body %}
    
    {% for ticket in ticket %}
    <div class="card-body pt-0">
        <div>
        <a href="/administracion/tickets" class="btn btn-sm btn-light btn-flex btn-center btn-active-light-primary" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end"><i class="ki-outline ki-double-left ms-1"></i>Volver
                                                    </a>
            <hr>
            <div class="row">
                <!-- Primera columna: Datos Ticket -->
                <div class="col-md-6">
                    <h3>Datos Ticket</h3>
                    <!-- Ticket ID (Read-only) -->
                    <div class="form-group mb-3">
                        <label for="ticket_id" class="form-label">Ticket ID:</label>
                        <input type="text" id="ticket_id" name="ticket_id" class="form-control" value="{{ ticket.id_ticket_pk }}" readonly>
                    </div>
                    <!-- Nodo => Empresa afectada => Cuenta afectada -->
                    <div class="form-group mb-3">
                        <label for="ticket_nodo_empresa_cuenta" class="form-label">Nodo => Empresa afectada => Cuenta afectada:</label>
                        <input type="text" id="ticket_nodo_empresa_cuenta" name="ticket_nodo_empresa_cuenta" class="form-control" value="{{ ticket.desc_nodo }} ({{ ticket.id_nodo }}) => {{ ticket.desc_empresa_afectada }} ({{ticket.id_empresa_nodo}}) => {{ticket.desc_cuenta_afectada}} ({{ticket.id_cuenta_nodo}})" readonly>
                    </div>
                    <!-- Fecha de creación -->
                    <div class="form-group mb-3">
                        <label for="ticket_fecha_creacion" class="form-label">Fecha de creación (DD/MM/YYYY):</label>
                        <input type="text" id="ticket_fecha_creacion" name="ticket_fecha_creacion" class="form-control" data-utc-timestamp="{{ ticket.timestamp_creacion_ticket }}" readonly>
                    </div>
                    <!-- Tipo Ticket -->
                    <div class="form-group mb-3">
                        <label for="ticket_tipo" class="form-label">Tipo Ticket:</label>
                        <input type="text" id="ticket_tipo" name="ticket_tipo" class="form-control" value="{{ ticket.label_tipo_ticket }}" readonly>
                    </div>
                    <!-- Impacto Ticket -->
                    <div class="form-group mb-3">
                        <label for="ticket_impacto" class="form-label">Impacto Ticket:</label>
                        <input type="text" id="ticket_impacto" name="ticket_impacto" class="form-control" value="{{ ticket.label_impacto_ticket }}" readonly>
                    </div>
                    <!-- Asunto -->
                    <div class="form-group mb-3">
                        <label for="ticket_asunto" class="form-label">Asunto:</label>
                        <input type="text" id="ticket_asunto" name="ticket_asunto" class="form-control" value="{{ ticket.desc_asunto }}" readonly>
                    </div>
                </div>
    
                <!-- Segunda columna: Datos Reclamante -->
                <div class="col-md-6">
                    <h3>Datos Reclamante</h3>
                    <!-- Username -->
                    <div class="form-group mb-3">
                        <label for="reclamante_username" class="form-label">Username:</label>
                        <input type="text" id="reclamante_username" name="reclamante_username" class="form-control" value="{{ ticket.username }}" readonly>
                    </div>
                    <!-- Email -->
                    <div class="form-group mb-3">
                        <label for="reclamante_email" class="form-label">Email:</label>
                        <input type="text" id="reclamante_email" name="reclamante_email" class="form-control" value="{{ ticket.user_email }}" readonly>
                    </div>
                    <!-- Telefono -->
                    <div class="form-group mb-3">
                        <label for="reclamante_telefono" class="form-label">Telefono:</label>
                        <input type="text" id="reclamante_telefono" name="reclamante_telefono" class="form-control" value="{{ ticket.user_telefono }}" readonly>
                    </div>
    
                    <hr>
    
                    <!-- Descripción -->
                    <div class="form-group mb-3">
                        <label for="ticket_descripcion" class="form-label">Descripción:</label>
                        <textarea id="ticket_descripcion" name="ticket_descripcion" class="form-control" rows="6" readonly>{{ ticket.desc_descripcion }}</textarea>
                    </div>
    
                    {% if ticket.flag_adjunto == 1 %}
                    <div class="mb-3">
                        <label class="font-weight-bold form-label">Descargar Archivo Adjunto</label>
    
                        <!-- Display the file name -->
                        <input type="text" id="blob-filename" class="form-control" disabled value="{{ ticket.name_blob }}">
                        <div id="image-preview"></div>
                        <!-- Prettier download button -->
                        <button id="download-btn" type="button" class="btn btn-primary mt-2">
                            <i class="fas fa-download"></i> Descargar Archivo
                        </button>
    
                        <!-- Store the base64 blob in a hidden input for JavaScript -->
                        <input type="hidden" id="blob-data" value="{{ticket.blob_adjunto}}">
                    </div>
                       {% endif %}
                </div>
            </div>
    
            <hr>
            <h3>Datos Caso</h3>
            <div class="row">
                <!-- Ticket Status -->
                <div class="col">
                    <div class="form-group mb-3">
                        <label for="new_ticket_estado" class="form-label font-weight-bold">Estado</label>
                        <select class="form-control" id="new_ticket_estado">
                            {% if ticket.id_usuario_responsable == usuario.id_usuario_pk %}
                                {% for estado in estados %}
                                    <option value="{{estado.id_tipo_estado_ticket_pk}}" {% if estado.id_tipo_estado_ticket_pk == ticket.id_estado_ticket %}selected{% endif %}>
                                        {{estado.label_estado_ticket}} ({{estado.desc_estado_ticket}})
                                    </option>
                                {% endfor %}
                            {% else %}
                                {% for estado in estados %}
                                    {% if estado.id_tipo_estado_ticket_pk == ticket.id_estado_ticket %}
                                    <option value="{{estado.id_tipo_estado_ticket_pk}}" selected>
                                        {{estado.label_estado_ticket}} ({{estado.desc_estado_ticket}})
                                    </option>
                                    {% endif %}
                                {% endfor %}
                            {% endif %}
                        </select>
                    </div>
    
                    <!-- Comercial Asociado -->
                    <div class="form-group mb-3">
                        <label for="comercial_asociado" class="form-label">Comercial Asociado:</label>
                        <input type="text" id="comercial_asociado" name="comercial_asociado" class="form-control" value="{{ ticket.nickname_comercial_owner }}" readonly>
                    </div>
    
                    <!-- Requiere Cotización -->
                    <div class="form-group mb-3 d-flex align-items-center">
                        <label for="flag_requier_cotiz" class="form-label mb-0 me-2">Requiere cotización</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="checkbox" id="flag_requier_cotiz" name="flag_requier_cotiz" value="1" {% if ticket.flag_requier_cotiz == 1 %} checked {% endif %}
                            {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %} disabled {% endif %}>
                        </div>
                    </div>
    
    
                    <!-- Cantidad de horas -->
                    <div class="form-group mb-3">
                        <label for="cant_horas_aplicadas" class="form-label">Cantidad de horas:</label>
                        <input type="number" id="cant_horas_aplicadas" name="cant_horas_aplicadas" class="form-control" value="{{ ticket.cant_horas_aplicadas }}" min="0"
                        {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %} readonly {% endif %}>
                    </div>
    
    
                    <!-- Aceptado por cliente -->
                    <div class="form-group mb-3 d-flex align-items-center">
                        <label for="flag_aceptado_por_cliente" class="form-label mb-0 me-2">Aceptado por cliente</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="checkbox" id="flag_aceptado_por_cliente" name="flag_aceptado_por_cliente" value="1" {% if ticket.flag_aceptado_por_cliente == 1 %} checked {% endif %}
                            {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %} disabled {% endif %}>
                        </div>
                    </div>
    
                    <!-- Notas privadas (No visibles por cliente) -->
                    <div class="form-group mb-3">
                        <label for="desc_notas_privadas" class="form-label">Notas privadas (No visibles por cliente):</label>
                        <textarea id="desc_notas_privadas" name="desc_notas_privadas" class="form-control" rows="6"
                        {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %} readonly {% endif %}>{{ ticket.desc_notas_privadas }}</textarea>
                    </div>
                </div>
    
                <!-- Responsable -->
                <div class="col">
                    <div class="form-group mb-3">
                        <label for="ticket_responsable" class="form-label">Responsable:</label>
                        <div class="input-group">
                            <input type="text" id="ticket_responsable" name="ticket_responsable" class="form-control" value="{{ ticket.desc_usuario_responsable }}" readonly>
                            
                                {% if ticket.id_usuario_responsable == usuario.id_usuario_pk %}
                                    <button type="button" class="btn btn-primary" onClick="dejarCaso()">Dejar caso</button>
                                {% else %}
                                    <button type="button" class="btn btn-primary" onClick="tomarCaso()">Tomar caso</button>
                                {% endif %}
                            
                        </div>
                    </div>
                    {% if ticket.id_usuario_responsable == usuario.id_usuario_pk %}
                    <!-- Derivar caso -->
                    <div class="col">
                    <div class="form-group mb-3">
                        <label for="new_usuario_derivar" class="form-label font-weight-bold">Derivar caso</label>
                        <div class="input-group">
                        <select class="form-control" id="new_usuario_derivar">
                            {% for derivables in usuariosDerivables %}
                                <option value="{{derivables.id_usuario_pk}}" {% if derivables.id_usuario_pk == ticket.id_usuario_responsable %}selected{% endif %}>
                                    {{derivables.name}} ({{derivables.nickname}})
                                </option>
                            {% endfor %}
                        </select>
                        <button type="button" class="btn btn-primary" onClick="derivarCaso()">Derivar caso</button>
                        </div>
                    </div>
                    {% endif %}
    
                    <!-- Fecha de Atención -->
                    <div class="form-group mb-3">
                        <label for="ticket_fecha_atencion" class="form-label">Fecha de atención (DD/MM/YYYY):</label>
                        <input type="text" id="ticket_fecha_atencion" name="ticket_fecha_atencion" class="form-control" data-utc-timestamp="{{ ticket.timestamp_apertura_ticket }}" readonly>
                    </div>
    
                    <!-- Fecha de Cierre -->
                    <div class="form-group mb-3">
                        <label for="ticket_fecha_cierre" class="form-label">Fecha de cierre (DD/MM/YYYY):</label>
                        <input type="text" id="ticket_fecha_cierre" name="ticket_fecha_cierre" class="form-control" data-utc-timestamp="{{ ticket.timestamp_cierre_ticket }}" readonly>
                    </div>
    
                    <div class="fv-row mb-7">
                        <div class="d-flex align-items-center">
                            <label class="fs-6 fw-semibold mb-0" for="flag_error_cliente">Error del cliente</label>
                            <div class="ms-2 form-check form-switch form-check-custom form-check-solid">
                                <input class="form-check-input" type="checkbox" id="flag_error_cliente" {% if ticket.flag_error_del_cliente %}checked{% endif %}
                                {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %}disabled{% endif %}>
                            </div>
                        </div>
                        <div id="error-textarea-container" class="form-group mb-3" style="{% if not ticket.flag_error_del_cliente %}display: none;{% endif %}">
                            <label for="desc_error_cliente" class="form-label">Detalle del error del cliente:</label>
                            <textarea id="desc_error_cliente" name="desc_error_cliente" class="form-control" rows="6" {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %}readonly{% endif %}>{{ ticket.desc_error_cliente }}</textarea>
                        </div>
                        <script>
                            document.getElementById('flag_error_cliente').addEventListener('change', function() {
                                document.getElementById('error-textarea-container').style.display = this.checked ? 'block' : 'none';
                            });
                        </script>
                    </div>
    
    
    
    
                </div>
            </div>
    
            <div class="text-end m-3">
                {% if ticket.id_usuario_responsable == usuario.id_usuario_pk %}
                    <button type="submit" class="btn btn-primary" onClick="guardarCambios()">Guardar cambios</button>
                {% endif %}
            </div>
        </div>
    
        <hr>
        <h3>Chat</h3>
        <!-- Chat  -->
    <div class="chat-box">
        {% for message in ticket.messages %} {% if message.flag_comentario_user_soporte != 0 %}
        <div class="chat-message tech">
            <div class="chat-bubble tech-bubble">
                <p><strong>{{message.desc_user_nodo}}:</strong> {{message.desc_comentario}}</p>
                {% if message.flag_adjunto == 1 %}
                <p>
                    <a style="color:purple" onClick=descargarAdjuntoMensaje({{message.id_ticket_comentario_pk}}) download="{{ message.name_blob }}">
                        <i class="bi bi-download"></i> Descargar {{ message.name_blob }}
                    </a>
                </p>
                {% endif %}
            ({{message.cr_timestamp}} UTC) 
            </div>
            <img src="https://n4.damap.cloud/images/user_icon_image.png" class="chat-profile-pic" alt="Yo">
        </div>
        {% else %}
        <div class="chat-message">
            <img src="https://n4.damap.cloud/images/user_icon_image.png" class="chat-profile-pic" alt="Usuario">
            <div class="chat-bubble user-bubble">
                <p><strong>{{message.desc_user_nodo}}:</strong> {{message.desc_comentario}}</p>
                {% if message.flag_adjunto == 1 %}
                <p>
                    <a style="color:purple" onClick=descargarAdjuntoMensaje({{message.id_ticket_comentario_pk}}) download="{{ message.name_blob }}">
                        <i class="bi bi-download"></i> Descargar {{ message.name_blob }}
                    </a>
                </p>
                {% endif %}
            ({{message.cr_timestamp}} UTC) 
            </div>
        </div>
        {% endif %} {% endfor %}
    </div>
    <!-- Barra de entrada de chat -->
    {% if ticket.id_estado_ticket != 8 %}
    <!-- Notification for file attached -->
    <div id="fileAttachedNotification_{{ticket.id_ticket_pk}}" style="display: none; color: green; font-weight: bold;">
        Archivo adjunto: <span id="attachedFileName_{{ticket.id_ticket_pk}}"></span>
    </div>
    {% if ticket.id_usuario_responsable != usuario.id_usuario_pk %}
                    <input readonly id="messageTextBox_{{ticket.id_ticket_pk}}" type="text" class="form-control" placeholder="Tome el caso para enviar un mensaje">
        <!-- Hidden file input -->
        <input type="file" id="fileInput_{{ticket.id_ticket_pk}}" style="display: none;" />
    </div>
                    {% else %}
    <div class="chat-bar">
        <textarea id="messageTextBox_{{ticket.id_ticket_pk}}" class="form-control message-box" placeholder="Escribe un mensaje..."></textarea>
        <!-- Hidden file input -->
        <input type="file" id="fileInput_{{ticket.id_ticket_pk}}" style="display: none;" />
        <!-- Paperclip button for file upload -->
        <button class="btn btn-light" onClick="triggerFileInput({{ticket.id_ticket_pk}})"><i class="bi bi-paperclip"></i></button>
        <!-- Send button -->
        <button class="btn btn-primary" onClick="sendMessage({{ticket.id_ticket_pk}})"><i class="bi bi-send"></i></button>
    </div>
    <script>
        document.getElementById('messageTextBox_{{ticket.id_ticket_pk}}').addEventListener('input', function () {
        this.style.height = 'auto'; // Reset height to auto
        this.style.height = (this.scrollHeight) + 'px'; // Set height to the scrollHeight
    });
    </script>
    
                    {% endif %}
    
    {% endif %}
    </div>
    {% endfor %}
    
    <!-- CSS del chat -->
    <style>
            /* Estilo de scrollbar para la caja de chat */
            .message-box {
            overflow-y: auto;
            resize: none;
            min-height: 60px;
            max-height: 300px;
            padding: 10px;
            width: 100%;
            box-sizing: border-box;
            scrollbar-width: thin; /* Para navegadores como Firefox */
            scrollbar-color: #6c757d #f1f1f1; /* Color de la barra y el fondo */
            }
    
            .chat-box {
            max-height: 300px;
            overflow-y: auto;
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
            scrollbar-width: thin; /* Para navegadores como Firefox */
            scrollbar-color: #6c757d #f1f1f1; /* Color de la barra y el fondo */
            }
            .chat-box p{
            color: black;
            }
            /* Estilo de scrollbar para Chrome, Edge y Safari */
            .chat-box::-webkit-scrollbar {
            width: 8px;
            }
            .chat-box::-webkit-scrollbar-track {
            background: black; /* Fondo de la barra */
            border-radius: 10px;
            }
            .chat-box::-webkit-scrollbar-thumb {
            background-color: black; /* Color del scroll */
            border-radius: 10px;
            border: 2px solid black; /* Espacio alrededor del scroll */
            }
            .chat-box::-webkit-scrollbar-thumb:hover {
            background-color: #495057; /* Color del scroll cuando se pasa el cursor por encima */
            }
            .chat-message {
            display: flex;
            align-items: flex-start;
            margin-bottom: 10px;
            }
            .chat-message.tech {
            justify-content: flex-end;
            }
            .chat-profile-pic {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
            margin-left: 10px;
            }
            .chat-bubble {
            padding: 10px;
            border-radius: 10px;
            background-color: white;
            max-width: 60%;
            }
                    /* Styling for the downloadable link */
            .chat-bubble a {
                color: #007bff; /* A more vibrant blue color */
                font-weight: bold; /* Make the text bold */
                text-decoration: underline; /* Add underline to make it more prominent */
                font-size: 14px; /* Adjust the font size to make it slightly larger */
            }
        
            .chat-bubble a:hover {
                color: #0056b3; /* Darker color on hover for better contrast */
                text-decoration: none; /* Remove underline on hover */
            }
            .user-bubble {
            background-color: #d1e7dd;
            }
            .tech-bubble {
            background-color: #bee5eb;
            }
            .chat-bar {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            border-top: 1px solid #ddd;
            }
            .chat-bar input {
            flex-grow: 1;
            }
            .chat-bar button {
            display: flex;
            align-items: center;
            justify-content: center;
            }
            .btn-link {
            color: #007bff;
            text-decoration: none;
            }
            .btn-link:hover {
            text-decoration: underline;
            }
    </style>
    
    <script>
    
        var attachedFileBase64 = "";
        var attachedFileName = "";
        function convertUTCToLocal(utcDateString) {
               const utcDate = new Date(utcDateString + ' UTC');
               return utcDate.toLocaleString();
            }
            
            document.addEventListener('DOMContentLoaded', function() {
               // Select all elements that have the data-utc-timestamp attribute (both divs and table cells)
               const timestampElements = document.querySelectorAll('[data-utc-timestamp]');
            
               // Loop through each element and update the value/text content with the local time
               timestampElements.forEach(function(element) {
                   const utcTimestamp = element.getAttribute('data-utc-timestamp');
                   if (utcTimestamp) {
                       const localTime = convertUTCToLocal(utcTimestamp);
                       
                       // If it's an input element, update the value. Otherwise, update text content.
                       if (element.tagName.toLowerCase() === 'input') {
                           element.value = localTime;
                       } else {
                           element.textContent = localTime;
                       }
                   }
               });
            });
        
                $(document).ready(function() {
                    $("#kt_customers_table").DataTable();
                    $("#kt_customers_table_2").DataTable();
                });
        
                
        // Trigger file input on paperclip click
        function triggerFileInput(idTicket) {
            // Trigger the hidden file input for the specific ticket
            $('#fileInput_' + idTicket).click();
        
            // Listen for file selection
            $('#fileInput_' + idTicket).on('change', function(event) {
                var file = event.target.files[0]; // Get the selected file
        
                // If a file is selected, convert it to base64
                if (file) {
                    var reader = new FileReader();
                    reader.onloadend = function() {
                        // Store the base64-encoded file
                        attachedFileBase64 = reader.result.split(',')[1]; // Remove the base64 prefix
                        attachedFileName = file.name; // Store the file name
        
                        // Update the file attached notification
                        $('#fileAttachedNotification_' + idTicket).show(); // Show the notification
                        $('#attachedFileName_' + idTicket).text(attachedFileName); // Display the file name
                    };
        
                    // Read the file as a Data URL (base64)
                    reader.readAsDataURL(file);
                }
            });
        }
        function descargarAdjuntoMensaje(idTicket){
            var formData = new FormData();
            formData.append('idTicket', idTicket);
                
            // Enviar los datos mediante una petición AJAX
            $.ajax({
                url: '{{path('getFileFromMessageInterno')}}',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    href="data:application/octet-stream;base64,"+response.blob_adjunto;
    
                    var link = document.createElement('a');
                    link.href = "data:application/octet-stream;base64," + response.blob_adjunto;
                    link.download = response.name_blob;  // Añadir el nombre del archivo
    
                    // Añadir el enlace al DOM y hacer clic en él automáticamente
                    document.body.appendChild(link);
                    link.click();
    
                    // Eliminar el enlace después de la descarga
                    document.body.removeChild(link);
                },
                error: function() {
                    // Manejar el error
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.error,
                    });
                }
            });
            
        }
        // Function to send message along with optional file attachment
        function sendMessage(idTicket) {
            // Obtener los valores de los inputs
            var message = $('#messageTextBox_' + idTicket).val();
            message = message.trim();
        
            // Verificar si los campos obligatorios están completos
            if (!message || (!message && !attachedFileBase64)) {
                alert('Por favor, escribe un mensaje antes de enviarlo.');
                return;
            }
        
            // Crear un objeto FormData para enviar los datos
            var formData = new FormData();
            formData.append('idTicket', idTicket);
            formData.append('message', message);
        
            // If there is a file attached (in base64), append it to formData
            formData.append('blob_adjunto', attachedFileBase64); // Add the base64 file to the request
            formData.append('name_blob', attachedFileName);
                
            // Enviar los datos mediante una petición AJAX
            $.ajax({
                url: '{{path('sendTicketMessageInterno')}}',  // Reemplazar con la URL del servidor
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    location.reload(); // Reload the page on success
                },
                error: function() {
                    // Manejar el error
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.error,
                    });
                }
            });
        }
        
            // Add event listener to the download button
            document.addEventListener('DOMContentLoaded', function() {
                // Select all download buttons and attach the click event
                document.querySelectorAll('#download-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        downloadBlobFile({{ticket[0].id_ticket_pk}});
                    });
                });
            });
    
            window.onload = function () {
                previewImage();
            }
            function downloadBlobFile(idTicket) {
                // Crear un objeto FormData para enviar los datos
    
                // Get the hidden input field containing the base64 blob data for the ticket
                var blobData = document.querySelector(`#blob-data`).value;
        
                // Get the file name from the input field that contains the file name
                var fileName = document.querySelector(`#blob-filename`).value;
        
                // Convert the base64 string to a binary string
                var byteString = atob(blobData);
        
                // Create an ArrayBuffer and a view (as unsigned 8-bit)
                var arrayBuffer = new ArrayBuffer(byteString.length);
                var uint8Array = new Uint8Array(arrayBuffer);
        
                // Assign the binary string to the ArrayBuffer
                for (var i = 0; i < byteString.length; i++) {
                    uint8Array[i] = byteString.charCodeAt(i);
                }
        
                // Create a Blob from the ArrayBuffer, defining the MIME type
                var blob = new Blob([arrayBuffer], { type: 'application/octet-stream' });
        
                // Create a temporary anchor element for the download
                var a = document.createElement('a');
                a.href = window.URL.createObjectURL(blob);
                a.download = fileName;  // Set the file name
        
                // Append the anchor to the document, trigger the click, and remove it
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
            
            function previewImage(){
                var blobData = document.querySelector(`#blob-data`).value;
                var fileName = document.querySelector(`#blob-filename`).value;
                var byteString = atob(blobData);
    
                var arrayBuffer = new ArrayBuffer(byteString.length);
                var uint8Array = new Uint8Array(arrayBuffer);
    
                for (var i = 0; i < byteString.length; i++) {
                    uint8Array[i] = byteString.charCodeAt(i);
                }
    
                var mimeType = '';
                if (fileName.endsWith('.png')) {
                    mimeType = 'image/png';
                } else if (fileName.endsWith('.jpg') || fileName.endsWith('.jpeg')) {
                    mimeType = 'image/jpeg';
                } else {
                    mimeType = 'application/octet-stream'; 
                }
    
                var blob = new Blob([uint8Array], { type: mimeType });
                if (mimeType === 'image/png' || mimeType === 'image/jpeg') {
                    var imageUrl = window.URL.createObjectURL(blob);
                    var imagePreview = document.querySelector('#image-preview');
                    imagePreview.innerHTML = '';
    
                    var imgElement = document.createElement('img');
                    imgElement.src = imageUrl;
                    imgElement.alt = 'Image preview';
                    imgElement.style.maxWidth = '100%';
    
                    imagePreview.appendChild(imgElement);
                }
            }
        
    
        function derivarCaso(){
                    function sendAlertMissingInput(missingInputName) {
                    Swal.fire({
                        title: 'Campo Requerido',
                        text: 'Por favor, complete el campo ' + missingInputName + '.',
                        icon: 'warning',
                        confirmButtonText: 'Aceptar'
                    });
                    }
        
                    function validateInput(selector, fieldName) {
                    var value = $(selector).val();
                    if (!value || value.length === 0) {
                        sendAlertMissingInput(fieldName);
                        return null;
                    }
                    return value;
                    }
                        
                var new_usuario_derivar = validateInput('#new_usuario_derivar', 'Estado');
                if (!new_usuario_derivar) return;
        
                    var formData = new FormData();
                    formData.append('id_ticket', {{ticket[0].id_ticket_pk}});
                    formData.append('usuarioDerivable', new_usuario_derivar);
        
                    $.ajax({
                        url:  '{{path("editTicket")}}',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            console.log(response);
                            if (response.cod_status === 0) {  // 0 is OK
                                location.reload();
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message,
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'An unexpected error occurred.',
                            });
                        }
                    });
        
                }
    
            function tomarCaso(){
                var formData = new FormData();
                        formData.append('id_ticket', {{ticket[0].id_ticket_pk}});
    $.ajax({    
                        url:  '{{path("tomarCaso")}}',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            console.log(response);
                            if (response.cod_status === 0) {  // 0 is OK
                                location.reload();
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message,
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'An unexpected error occurred.',
                            });
                        }
                    });
     }
    
     
    
     function dejarCaso(){
                var formData = new FormData();
                        formData.append('id_ticket', {{ticket[0].id_ticket_pk}});
    $.ajax({    
                        url:  '{{path("dejarCaso")}}',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            console.log(response);
                            if (response.cod_status === 0) {  // 0 is OK
                                location.reload();
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message,
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'An unexpected error occurred.',
                            });
                        }
                    });
     }
    
    
    
            function guardarCambios(){
                    function sendAlertMissingInput(missingInputName) {
                    Swal.fire({
                        title: 'Campo Requerido',
                        text: 'Por favor, complete el campo ' + missingInputName + '.',
                        icon: 'warning',
                        confirmButtonText: 'Aceptar'
                    });
                    }
        
                    function validateInput(selector, fieldName) {
                    var value = $(selector).val();
                    if (!value || value.length === 0) {
                        sendAlertMissingInput(fieldName);
                        return null;
                    }
                    return value;
                    }
                        
                var estado = validateInput('#new_ticket_estado', 'Estado');
                if (!estado) return;
    
                var requiere_cotiz = document.querySelector(`#flag_requier_cotiz`).checked ? 1 : 0;
                var aceptado_por_cliente = document.querySelector(`#flag_aceptado_por_cliente`).checked ? 1 : 0;
                
                var cant_horas_aplicadas = validateInput('#cant_horas_aplicadas', 'Cantidad de horas aplicadas');
                if (!cant_horas_aplicadas) return;
                if (cant_horas_aplicadas < 0) sendAlertMissingInput('Cantidad de horas aplicadas');
    
                var desc_notas_privadas = $('#desc_notas_privadas').val();
    
                    var flag = document.getElementById('flag_error_cliente').checked ? 1 : 0;
                    var desc = document.getElementById('desc_error_cliente').value;
                    
                    var formData = new FormData();
                    formData.append('flag_error_cliente', flag);
                    formData.append('desc_error_cliente', desc);
                    
                    formData.append('id_ticket', {{ticket[0].id_ticket_pk}});
                    formData.append('estado', estado);
                    formData.append('flag_requier_cotiz', requiere_cotiz);
                    formData.append('flag_aceptado_por_cliente', aceptado_por_cliente);
                    formData.append('cant_horas_aplicadas', cant_horas_aplicadas);
                    formData.append('desc_notas_privadas', desc_notas_privadas);
                    
        
                    $.ajax({
                        url:  '{{path("editTicket")}}',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            console.log(response);
                            if (response.cod_status === 0) {  // 0 is OK
                                location.reload();
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message,
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'An unexpected error occurred.',
                            });
                        }
                    });
        
                }
    </script>
    
    {% endblock %}