{extends file="$layouts_admin"}


 
 
 
 

{block name="content"}


 <link
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
  rel="stylesheet"
/>

 



<style type="text/css">

.color-red{
    color:red;
}

.btn-edit-referencia-personal {
         margin-bottom: 4px; 
         background-color: #001b3b; 
         color: white; 
         border: 1px solid rgb(211, 202, 192) !important; 
         box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px; 
         float: inline-end;
    }

   .btn-eliminar-referencia-personal {
      margin-bottom: 4px;
      background-color: red;
      color: white;
      border: 1px solid rgb(211, 202, 192) !important;
      box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
      float: inline-end;
    }

   .btn-edit-referencia-personal:hover i,
   .btn-eliminar-referencia-personal:hover i {
      color: white; /* Mantén el color blanco del icono en hover */
   }

   .tamano-icono{
      font-size:small;
   }
    
   .centrar-botones{
      text-align: center;
      justify-content: center;
      display: flex;
      padding: 0px;
   }

   .btn-descargar {
         margin-bottom: 4px; 
         background-color: #001b3b; 
         color: white; 
         border: 1px solid rgb(211, 202, 192) !important; 
         box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px; 
         float: inline-end;
    }

   .btn-eliminar {
      margin-bottom: 4px;
      background-color: red;
      color: white;
      border: 1px solid rgb(211, 202, 192) !important;
      box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
      float: inline-end;
    }

   .btn-descargar:hover i,
   .btn-eliminar:hover i {
      color: white; /* Mantén el color blanco del icono en hover */
   }


</style>

    <input
         type="text"
         value="{$url_base}"
         disabled
         hidden
         id="URL_BASE"
    />

    <input
         type="text"
         value="{$url_crm_administrativo}"
         disabled
         hidden
         id="url_crm_administrativo"
    />
 
    <div class="row cargando_pantalla " style=" margin: 0px; ">

        <div
            class="container"
            style="
                display: flex;
                justify-content: center;
                align-items: center;
                height: 45vh;
                box-shadow: 0 0 13px 0 rgba(31,17,173,.08);
                border-radius: 11px;
                background-color: white;
            "
        >
            <div style="text-align: center">
                <span
                class="spinner-border spinner-border-sm"
                style="height: 45px; width: 45px; margin-bottom: 10px"
                role="status"
                aria-hidden="true"
                ></span>
                <br />
                <strong>Please wait while the screen loads...</strong>
                <br />
            </div>
        </div>

    </div>

    <div class="row pantalla_cargada"  style="display: none;">

        <div class="col-md-12">
            <div class="panel" id="ib_box">
                <div class="panel-hdr">


                    <h2>{$_L['Open Ticket']}</h2>


                </div>

                <div class="panel-container">
                    <div class="panel-content">


                        <form id="create_ticket" class="form-horizontal push-10-t push-10" method="post">

                            <div class="mb-3">
                                <div class="col-xs-12">
                                    <label for="cid">{$_L['Customer']}</label>


                                    <input class="form-control showInputIsNotAdminCRMPartner" type="text" id="input_customer" name="input_customer"  disabled  >

                                    <div class="showSelectCustomerIsAdminsCRMPartner">
                                        <select id="cid" name="cid" class="form-control htmlSelectedCID">

                                            {*
                                                <option value="">{$_L['Customer']}...</option>
                                                {foreach $customers as $cs}
                                                    <option value="{$cs['id']}"
                                                            {if $p_cid eq ($cs['id'])}selected="selected" {/if}>{$cs['account']} {if $cs['email'] neq ''}- {$cs['email']}{/if}</option>
                                                {/foreach}

                                            *}

                                        </select>
                                    </div>
                                     
                                </div>
                            </div>



                            <div class="mb-3">
                                <div class="col-xs-12">
                                    <div class="mb-3">
                                        <label for="subject">{$_L['Subject']}</label>
                                        <input class="form-control" type="text" id="subject" name="subject" autofocus>


                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-6">
                                    <div class="mb-3">
                                        <label for="department">{$_L['Department']}<span class="color-red">*</span></label>
                                        <select class="form-select departmentHtml" id="department" name="department" size="1">
                                            
                                            {*
                                                {foreach $deps as $dep}
                                                    <option value="{$dep['id']}">{$dep['dname']}</option>
                                                    {foreachelse}
                                                    <option value="0">None</option>
                                                {/foreach}
                                            *}
                                             
                                        </select>

                                    </div>
                                </div>

                                <div class="col-6">
                                    <div class="mb-3">
                                        <label for="urgency">{$_L['Priority']}</label>
                                        <select class="form-select" id="urgency" name="urgency" size="1">
                                            <option value="High">{$_L['High']}</option>
                                            <option value="Medium" selected>{$_L['Medium']}</option>
                                            <option value="Low">{$_L['Low']}</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">

                                <div class="col-6">
                                    <div class="mb-3">
                                        <label for="email_client">Email <span class="color-red">*</span> </label>
                                        <input class="form-control email_client" type="text" id="email_client" name="email_client"  >
                                    </div>
                                </div>    

                                <div class="col-6">
                                    <div class="mb-3">
                                        <label for="phone_client">Phones <span class="color-red">*</span> </label>
                                        <input class="form-control phone_client" type="text" id="phone_client" name="phone_client"  >
                                    </div>
                                </div>    

                                <div class="col-12">
                                    <div class="mb-3">
                                        <label for="contact_client">Contact</label>
                                        <input class="form-control contact_client" type="text" id="contact_client" name="contact_client"  >
                                    </div>
                                </div>    



                            </div>

                        
                         
                            <div class="mb-3 mt-3">
                                <label for="content">{$_L['Message']}</label>
                                <textarea id="content"  class="form-control sysedit" name="content"></textarea>
                                
                                {*
                                    <div class="help-block"><a data-bs-toggle="modal" href="#modal_add_item"><i class="fal fa-paperclip"></i> {$_L['Attach File']}</a> </div> 
                                *}

                            </div>

                            <div class="row">

                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="file"><span class="h6">File</span><span class="text-danger"></span></label>
                                        <input type="file" id="file" name="file" class="form-control file">
                                    </div>
                                </div>
                            
                            </div>

                            <div class="row card_container mb-3">



                            </div>

                    

                            <div class="mb-3">
                                <input type="hidden" name="attachments" id="attachments" value="">

                                <button class="btn btn-primary" id="ib_form_submit" type="submit"><i class="fal fa-send push-5-r"></i> {$_L['Save']}</button>
                            </div>
                        </form>



                    </div>
                </div>

            </div>
        </div>

    </div>

    <div class="modal fade" id="modal_add_item" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">
                        {$_L['Attach File']}
                    </h4>
                    <button type="button" class="close btn btn-danger" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true"><i class="fal fa-times"></i></span>
                    </button>
                </div>
                <div class="modal-body">
                    <form action="" class="dropzone" id="upload_container">

                        <div class="dz-message">
                            <h3> <i class="fal fa-cloud-upload"></i>  {$_L['Drop File Here']}</h3>
                            <br />
                            <span class="note">{$_L['Click to Upload']}</span>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{$_L['Close']}</button>
                </div>
            </div>
        </div>
    </div>

    {* modal consulta *}
    <div class="modal fade" id="ventana_confirmacion" tabindex="-1" aria-labelledby="exampleModalLabel__ventanaconfirmacion" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false" >
        <div class="modal-dialog modal-dialog-centered"  >
            <div class="modal-content" style="background-color:white">
                <div class="modal-header">
                <h3 class="titulo_modal_confirmar" style="color:black">Estas seguro de eliminar</h3>
                    <button type="button" class="btn-close "  id="btn_close_ventana_confirmacion" ></button>
                </div>
                <div class="modal-body" style="background-color:white;border-radius:10px">
                
                    <div class="row">
                    <div class="col-md-12">
                        <div class="panel-container show" id="ibox_form">
                                <div class="panel-content">
                                    <div class="px-2">
                                            <div class="alert alert-danger" id="emsg" style="display: none;">
                                            <span id="emsgbody"></span>
                                            </div>
                                            <input class="tipo_modal_confirmar" hidden disabled/> 
                                            <input class="data_id" hidden disabled/> 
                                            <div class="row">
                                                <div class="col-md-12 col-sm-12">

                                                        <h4 class="mensaje_modal_confirmar" style="text-align:center; color:black">Estas seguro de eliminar</h4>
                                                        
                                                        <p class="mensaje_espera_moda_confirmacion mt-3" style="text-align:center; color:red; font-weight:600">Espere mientras termina el proceso</p>
                                                </div>
                                            
                                            </div>

                                            <div class="row mt-2">
                                                <div class="col-md-12">
                                                        <div style=" float: inline-end; ">
                                                        <button class="btn me-2" type="button" id="btn_cerrar_ventana_confirmacion" style=" background: #001b3b; ">close</button>
                                                        <button class="btn " type="button" id="btn_aplicar_ventana_confirmacion" style=" background: red; ">Remove</button>
                                                        </div>
                                                </div>
                                            </div>
                                    </div>
                                </div>
                                </div>
                    </div>
                    </div>
                
                </div>
                
            </div>
        </div>
    </div>
    {* fin modal para eliminar o consultar si desea hacer tal accion *}

{*    <div id="modal_add_item" class="modal fade" tabindex="-1" data-width="600" style="display: none;">*}
{*        <div class="modal-header">*}
{*            <button type="button" class="close btn btn-danger" data-bs-dismiss="modal" aria-hidden="true">×</button>*}
{*            <h4 class="modal-title">Add File</h4>*}
{*        </div>*}
{*        <div class="modal-body">*}
{*            <div class="row">*}



{*                <div class="col-md-12">*}
{*                    <form action="" class="dropzone" id="upload_container">*}

{*                        <div class="dz-message">*}
{*                            <h3> <i class="fal fa-cloud-upload"></i>  Drop File Here</h3>*}
{*                            <br />*}
{*                            <span class="note">Or Click to Upload</span>*}
{*                        </div>*}

{*                    </form>*}


{*                </div>*}




{*            </div>*}
{*        </div>*}
{*        <div class="modal-footer">*}

{*            <button type="button" data-bs-dismiss="modal" class="btn btn-danger">Close</button>*}

{*        </div>*}
{*    </div>*}

{/block}

{block name="script"}

    <script type="text/javascript" src="{$app_url}ui/lib/redactor/redactor.min.js"></script>

    {*
    <script src="https://cdn.jsdelivr.net/npm/redactor-html@1.0.0/redactor.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/redactor-html@1.0.0/redactor.min.css" rel="stylesheet">
    
    *}
     

    {literal}
    <script>

        var COLOR_FONDO_VENTANA_CERRAR = "#001b3b";
        var COLOR_TEXT_VENTANA_CERRAR = "white";

        var COLOR_FONDO_VENTANA_CONFIRMACION = "red";
        var COLOR_TEXT_VENTANA_CONFIRMACION = "white";


        var URL_BASE = $("#URL_BASE").val();
        var url_crm_administrativo = $("#url_crm_administrativo").val();

        console.log("url_crm_administrativo");
        console.log(url_crm_administrativo);

        var partner_crm_administrativo = 2;
        var arregloArchivos = [];
        var CompanyName     = "";


        function isEmailValid(email) {
            // Expresión regular para validar correo electrónico
            const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            
            // Validaciones adicionales
            if (!email || typeof email !== 'string') return false;
            if (isEmpty(email)) return false;
            
            return regex.test(email.trim());
        }

        function isEmpty(value) {
            // Verificar si es null o undefined
            if (value == null) return true;

            // Verificar si es una cadena vacía
            if (typeof value === "string" && value.trim() === "") return true;

            // Verificar si es un array vacío
            if (Array.isArray(value) && value.length === 0) return true;

            // Verificar si es un objeto vacío
            if (typeof value === "object" && Object.keys(value).length === 0) return true;

            return false;
        }

        Dropzone.autoDiscover = false;
        $(function () {
            
             

            var _url = $("#_url").val();

            var $ib_form_submit = $("#ib_form_submit");

            var $create_ticket = $("#create_ticket");
            var $ib_box = $("#ib_box");

            $("#cid").select2({

                }
            );


            var upload_resp;


            var ib_file = new Dropzone("#upload_container",
                {
                    url: _url + "tickets/admin/upload_file/",
                    maxFiles: 10,
                    acceptedFiles: "image/jpeg,image/png,image/gif"
                }
            );


            ib_file.on("sending", function() {

                $ib_form_submit.prop('disabled', true);

            });

            ib_file.on("success", function(file,response) {

                $ib_form_submit.prop('disabled', false);

                upload_resp = response;

                if(upload_resp.success == 'Yes'){

                    toastr.success(upload_resp.msg);
                    // $file_link.val(upload_resp.file);
                    // files.push(upload_resp.file);
                    //
                    // console.log(files);

                    $('#attachments').val(function(i,val) {
                        return val + (!val ? '' : ',') + upload_resp.file;
                    });


                }
                else{
                    toastr.error(upload_resp.msg);
                }







            });

            $ib_form_submit.on('click', function(e) {
                e.preventDefault();

                let email_client = $("#email_client").val();
                let phone_client = $("#phone_client").val();
                let department   = $("#department").val();

                
                if(isEmpty(department))
                {
                    toastr.error("The department field is required.");
                    return;
                }

                if(isEmpty(email_client))
                {
                    toastr.error("The emails field is required.");
                    return;
                }

                if(!isEmailValid(email_client))
                {
                    toastr.error("The email field must be a valid email.");
                    return;
                }

                if(isEmpty(phone_client))
                {
                    toastr.error("The phone field is required.");
                    return;
                }

                $ib_box.block({ message: block_msg });

                let information = {
                    cid:            $("#cid").val(), 
                    subject:        $("#subject").val(), 
                    department:     $("#department").val(), 
                    urgency:        $("#urgency").val(), 
                    message:        $('#content').val(), 
                    attachments:    $("#attachments").val(),

                    email_client:   $("#email_client").val(),
                    phone_client:   $("#phone_client").val(),
                    contact_client: $("#contact_client").val(),

                    partner_crm_administrativo: partner_crm_administrativo,
                    CompanyName               : CompanyName,

                    arregloArchivos: JSON.stringify(arregloArchivos),

                    url_crm_administrativo: url_crm_administrativo,
                };
 
                console.log("information");
                console.log(information);

                console.log(_url + "tickets/admin/add_post/");
                //return;

                $.post( _url + "tickets/admin/add_post/", information )
                    .done(function( data ) {

                        console.log("data")
                        console.log(data)
                        //return;

                        if(data.success == "Yes"){
                            window.location.href = _url + "tickets/admin/view/" + data.id + "/";
                        }
                        else {
                            $ib_box.unblock();
                            toastr.error(data.msg);
                            //  console.log(data);
                        }

                    });

            });
        });
 

        $(document).ready(function () {

            cargarPrincipal();

            function generateCardHtml(data) {
    
                let {
                    base64,
                    base64_original,
                    nombre_original,
                    extension,
                    UUID,
                    UUID_ENC,
                } = data;

                // Sanitize inputs to prevent XSS
                const sanitize = (str) => {
                    const div = document.createElement('div');
                    div.textContent = str;
                    return div.innerHTML;
                };

                const sanitizedId            = sanitize(UUID_ENC);
                const sanitizedTipoArchivo   = sanitize(extension);
                const sanitizedNameArchivo   = sanitize(nombre_original);

                // El base64_original ya trae el dataURL (ej: data:application/pdf;base64,....)
                const sanitizedDownloadUrl   = base64_original;
                const sanitizedFileName      = sanitizedNameArchivo || `document.${sanitizedTipoArchivo.toLowerCase()}`;

                return `
                    <div class="col-12 col-sm-4 pt-4 card_eliminar_${sanitizedId}">
                        <div class="card" style="width: 100%; max-width: 300px; box-shadow: rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px;">
                            <div class="card-body">
                                <h5 class="card-title">File type: <span class="card_tipo_archivo">${sanitizedTipoArchivo}</span></h5>
                                <h5 class="card-title">File name: <span class="card_nombre_archivo">${sanitizedNameArchivo}</span></h5>
                                <div class="row">
                                    <div class="col-12">
                                        <button type="button" class="btn btn-sm btn-eliminar waves-effect waves-themed" data-id="${sanitizedId}">
                                            <i class="fas fa-trash tamano-icono" aria-hidden="true"></i>
                                        </button>
                                        <a class="btn btn-sm btn-descargar waves-effect waves-themed" 
                                        data-id="${sanitizedId}" 
                                        href="${sanitizedDownloadUrl}" 
                                        download="${sanitizedFileName}">
                                            <i class="fas fa-download tamano-icono" aria-hidden="true"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }

            function generateUUIDv4() {
                // Generar un prefijo único basado en microsegundos (similar a uniqid en PHP)
                const time_low = Date.now().toString(16).padStart(8, '0') + Math.random().toString(16).slice(2, 6);
                // Generar 8 bytes aleatorios para completar el UUID (similar a random_bytes en PHP)
                const array = new Uint8Array(8);
                crypto.getRandomValues(array);
                const extra_bytes = Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
                // Unir las partes y crear el UUID v4
                const uuid = [
                    // 32 bits para "time_low"
                    time_low.slice(0, 8),
                    // 16 bits para "time_mid"
                    time_low.slice(8, 12),
                    // 16 bits para "time_hi_and_version" (empieza con 4 para UUID v4)
                    '4' + extra_bytes.slice(0, 3),
                    // 16 bits para "clk_seq_hi_res" (empieza con 8, 9, A o B para UUID v4)
                    ((parseInt(extra_bytes.slice(3, 7), 16) & 0x3fff) | 0x8000).toString(16),
                    // 48 bits para "node"
                    extra_bytes.slice(7, 12) + Math.random().toString(16).slice(2, 7)
                ].join('-');
                return uuid;
            }

            function uuidToBase64UrlRFC7515(uuid) {
                // Eliminar los guiones del UUID
                const cleanUuid = uuid.replace(/-/g, '');
                // Convertir el UUID de hexadecimal a binario
                const binaryUuid = new Uint8Array(cleanUuid.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
                // Convertir el binario a Base64
                const base64 = btoa(String.fromCharCode(...binaryUuid));
                // Convertir Base64 a formato URL-safe (RFC 7515)
                const base64Url = base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
                return base64Url;
            }

            
            $("#btn_aplicar_ventana_confirmacion").off("click")
            .on("click", function () {
            console.log("se dio click");
                $('#btn_aplicar_ventana_confirmacion').prop('disabled', true);
                $('#btn_close_ventana_confirmacion').prop('disabled', true);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', true);

                let opcion_predefinida = $(".tipo_modal_confirmar").val();
                let data_id = $(".data_id").val();
                
                if(opcion_predefinida == "eliminar_card_documento")
                {
                    $(".mensaje_espera_moda_confirmacion").text("");

                    $(".card_eliminar_" + data_id).remove();

                    let archivoEncontrado = arregloArchivos.find((data) => data.UUID_ENC == data_id );
                    
                    if(archivoEncontrado)
                    {
                        arregloArchivos = arregloArchivos.filter((data) => data.UUID_ENC != data_id );

                        if( !isEmpty(archivoEncontrado.id) )
                        {
                            arregloArchivosEliminados.push(archivoEncontrado);
                        }
                        
                    }

                    $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                    $('#btn_close_ventana_confirmacion').prop('disabled', false);
                    $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                    
                    $("#ventana_confirmacion").modal("hide");

                }

                if(opcion_predefinida == "navegar_pantalla_siguiente")
                {
                    window.location = URL_BASE + "credit/pre-approval-prospecting/"+data_id;
                }
            
            
            });

            $("#btn_cerrar_ventana_confirmacion").off("click")
            .on("click", function () {
            
                $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                $('#btn_close_ventana_confirmacion').prop('disabled', false);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                $("#ventana_confirmacion").modal("hide");
            
            });

            $("#btn_close_ventana_confirmacion").off("click")
            .on("click", function () {
                $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                $('#btn_close_ventana_confirmacion').prop('disabled', false);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                
                $("#ventana_confirmacion").modal("hide");
            
            });

            $('.btn_cerrar_confirmacion_modal').click(function() {
                $("#modalMensaje").modal("hide");
            });

            $('.abrir_modal_contacto').click(function() {
             $("#modal_asignar_clientes_contactos").modal("show");
            });

            function eventoEliminarDocumento() 
            {
                $('.btn-eliminar').off('click');
                $('.btn-eliminar').on('click', function() {
                    
                    let data_id = $(this).data("id");
                    console.log("data_id eliminar: " + data_id);

                    $(".titulo_modal_confirmar").text("You are sure?");
                    $(".mensaje_modal_confirmar").text("Are you sure you want to delete this record?");
                    $(".mensaje_espera_moda_confirmacion").text("");
                    $(".tipo_modal_confirmar").val("eliminar_card_documento");
                    $(".data_id").val(data_id);
                    $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                    $('#btn_close_ventana_confirmacion').prop('disabled', false);
                    $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);

                    $('#btn_cerrar_ventana_confirmacion').css({
                        'background-color': COLOR_FONDO_VENTANA_CERRAR,
                        'color': COLOR_TEXT_VENTANA_CERRAR
                    });
                

                    $('#btn_aplicar_ventana_confirmacion').css({
                        'background-color': COLOR_FONDO_VENTANA_CONFIRMACION,
                        'color': COLOR_TEXT_VENTANA_CONFIRMACION,
                        //'display': "none"
                    });

                    $("#ventana_confirmacion").modal("show");

                });

            }

            $('.file').on('change', function() {
 
                getFileBase64AndExtension('#file', function(result) {
                if (result.error) {
                        toastr.error(result.error);
                        return;
                }

                base64_original  = result.base64;
                const base64Data = result.base64.split(',')[1]; // Extract only the Base64 part
            
                base64          = base64Data;
                extension       = result.extension;
                nombre_original = result.name;

                let UUID     = generateUUIDv4();
                let UUID_ENC = uuidToBase64UrlRFC7515(UUID);

                let informacionFront = {
                    base64: base64,
                    base64_original: base64_original,
                    nombre_original: nombre_original,
                    extension: extension,
                    UUID: UUID,
                    UUID_ENC: UUID_ENC,
                };

                arregloArchivos.push(informacionFront);

                console.log(JSON.stringify(informacionFront));
                
                $(".card_container").append( generateCardHtml(
                        informacionFront
                    ) 
                );

                eventoEliminarDocumento();

                $(".file").val("");

                });
            });

            function cargarPrincipal()
            {
 
                $.ajax({
                    type: "POST",
                    url: URL_BASE + "tickets/admin/get-information-general-tickets",
                    //data: JSON.stringify(data),
                    contentType: "application/json", // Tipo de contenido JSON
                    success: function (response) {
        
                        try {
                            let info = JSON.parse(response);

                            if (info.type == "success") {

                                let customers              = info.list_customer || [];
                                partner_crm_administrativo = info.partner_crm_administrativo || "2";
                                CompanyName = info.CompanyName || "";

                                let options = '<option value="">Customer...</option>';
                                let p_cid = "";

                                for (let i = 0; i < customers.length; i++) {
                                    const cs = customers[i];
                                    const selected = (p_cid == cs.id) ? ' selected="selected"' : '';
                                    const emailPart = (cs.email !== '') ? ` - ${cs.email}` : '';
                                    
                                    options += `<option value="${cs.id}"${selected}>${cs.account}${emailPart}</option>`;
                                }

                                $(".htmlSelectedCID").html(options);

                                $(".showSelectCustomerIsAdminsCRMPartner").css("display", "none");
                                $(".showInputIsNotAdminCRMPartner").css("display", "none");

                                if(partner_crm_administrativo == 1)
                                {
                                    $(".showSelectCustomerIsAdminsCRMPartner").css("display", "");
                                }else{

                                    $(".showInputIsNotAdminCRMPartner").css("display", "");
                                    $(".showInputIsNotAdminCRMPartner").val(CompanyName);

                                }
                         
                                $(".cargando_pantalla").css("display", "none");
                                $(".pantalla_cargada").css("display", "");

                                $('#content').redactor(
                                    {
                                        minHeight: 200 // pixels
                                    }
                                );

                                let listDepartamentsTickets = info.listDepartamentsTickets || [];

                                options = '';
                                listDepartamentsTickets.forEach((data) =>
                                {
                                    let {
                                        id, 
                                        dname,
                                    } = data;

                                    options += `<option value="${id}">${dname}</option>`;
                                });
                                
                                $(".departmentHtml").html(options);

            
                            } else if (info.type == "error") {
                                Swal.fire({
                                    icon: "error",
                                    title: "Oops...",
                                    text: info.message,
                                });

                                //ventanaError("Opps there was an error", info.message);
                            }
                        } catch (error) {
                            Swal.fire({
                                icon: "error",
                                title: "Oops...",
                                text: error,
                            });

                            //ventanaError("Opps there was an error", error);
                        }


                    },
                    error: function (xhr, status, error) {
                        console.error("Error en la solicitud:", error);
                        // Manejar errores aquí
                        Swal.fire({
                           icon: "error",
                           title: "Oops...",
                           text: error,
                        });

                        //ventanaError("Opps there was an error", error);

                    },
                });

            }

            function getFileBase64AndExtension(inputSelector, callback) {
                const fileInput = $(inputSelector)[0];
                if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
                    callback({ error: "No file selected" });
                    return;
                }
                const file = fileInput.files[0];
                const reader = new FileReader();
                
                // Get file extension
                const fileName = file.name;
                const extension = fileName.split('.').pop().toLowerCase();
                reader.onload = function(e) {
                    const base64String = e.target.result; // Full data URL (e.g., "data:image/png;base64,...")
                    callback({
                            base64: base64String,
                            extension: extension,
                            name: file.name
                    });
                };

                reader.onerror = function() {
                    callback({ error: "Error reading file" });
                };
                reader.readAsDataURL(file);
            }

        });

    </script>
    {/literal}
{/block}
