{extends file="$layouts_admin"}
{block name="head"}




{/block}

{block name="content"}

<style type="text/css">

    .list-group{
        max-height: 150px;
        margin-bottom: 10px;
        overflow:scroll;
        -webkit-overflow-scrolling: touch;
    }    

    .swal2-container {
        z-index: 9999;
    }


</style>

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

    <input
         type="text"
         value="{$id_user}"
         disabled
         hidden
         id="ID_USER"
    />

    <input
         type="text"
         value="{$data_form['customer_id']}"
         disabled
         hidden
         id="customer_id_backend"
    />

    <input
         type="text"
         value="{$data_form['question_mail_sent']}"
         disabled
         hidden
         id="question_mail_sent_backend"
    />

    <input
         type="text"
         value="{$data_form['email']}"
         disabled
         hidden
         id="email_backend"
    />

    <input
         type="text"
         value="{$data_form['access_code']}"
         disabled
         hidden
         id="tenerAccessCode_backend"
    />

    <input
         type="text"
         value="{$data_form['verification_code']}"
         disabled
         hidden
         id="verification_code_backend"
    />

    <input
         type="text"
         value="{$data_form['forms_category_id']}"
         disabled
         hidden
         id="forms_category_id_backend"
    />

    <input
         type="text"
         value="{$data_form['staff_id']}"
         disabled
         hidden
         id="staff_id_backend"
    />

    <input
         type="text"
         value="{$data_form['staff_id']}"
         disabled
         hidden
         id="staff_id_backend"
    />

    <input
         type="text"
         value="{$UUID_ENC}"
         disabled
         hidden
         id="UUID_ENC_backend"
    />

    <input
         type="text"
         value="{$url_dashboard}"
         disabled
         hidden
         id="url_dashboard"
    />
     
    <input
         type="text"
         value="{$roll_id}"
         disabled
         hidden
         id="roll_id"
    />

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

   <input type="text" id="url_modulo_api_direccion_smarty" name="url_modulo_api_direccion_smarty" class="form-control url_modulo_api_direccion_smarty" value="{$url_modulo_api_direccion_smarty}" disabled hidden >
   <input type="text" id="key_modulo_api_direccion_smarty" name="key_modulo_api_direccion_smarty" class="form-control key_modulo_api_direccion_smarty" value="{$key_modulo_api_direccion_smarty}" disabled hidden  >


<div class="row">

    <div class="col-md-12">

        <div class="panel">
            <div class="panel-hdr">
                <h2><span></span>New Forms</h2>

            </div>

            <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>

                        <div class="alert alert-success" id="emsgSuccess" style="display: none;">
                            <span id="emsgbodySuccess"></span>
                        </div>

                        <form id="rform">

                            <div class="row">
                                
                                {* informacion primera columna *}

                                <div class="col-md-6 col-sm-12">

                                    <div class="mb-3 row">
                                        <label for="Customers" class="col-sm-3"><span class="h6">Select a customer</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <select id="Customers" name="Customers" class="form-select tenerCustomers"  >
                                                <option value="" selected disabled>Select a Option</option>

                                                <option value="-100" >New Customers</option>
                                                {foreach $listado_clientes as $ds}
                                                    <option value="{$ds['id']}" data-email="{$ds['email']}" data-account="{$ds['account']}" >{$ds['account']}</option>
                                                {/foreach}
                                            </select>
                                        </div>
                                    </div>
 
                                    <div class="mb-3 row">
                                        <label for="name" class="col-sm-3"><span class="h6">Name</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="name" name="name" class="form-control tenerName" value="{$data_form['name_customer']}">
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="preguntaEnviarCorreo" class="col-sm-3"><span class="h6">Send by email?</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                             <select id="preguntaEnviarCorreo" name="preguntaEnviarCorreo" class="form-control tenerPreguntaEnviarCorreo" >
                                                <option value="1" >Yes</option>
                                                <option value="2">No</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="zip" class="col-sm-3"><span class="h6">Email</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="email" id="correoElectronico" name="correoElectronico" class="form-control tenerCorreoElectronico">
                                        </div>
                                    </div>

              
                                </div>

                                {* informacion segunda columna *}

                                <div class="col-md-6 col-sm-12">
                                    <div class="mb-3 row">
                                        <label for="accessCode" class="col-sm-3"><span class="h6">Access code</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="accessCode" name="accessCode" class="form-control tenerAccessCode"   readonly disabled>
                                        </div>
                                    </div>

  
                                    <div class="mb-3 row">
                                        <label for="VerificationCode" class="col-sm-3"><span class="h6">Verification code</span><span class="text-danger">*</span> </label>
                                        <div class="col-sm-9">
                                            <input type="text" id="VerificationCode" name="VerificationCode" class="form-control tenerVerificationCode" readonly disabled>
                                        </div>
                                    </div>


                                    <div class="mb-3 row">
                                        <label for="password" class="col-sm-3"><span class="h6">Select the form type</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <select id="tipoFormulario" name="tipoFormulario" class="form-select tenertipoFormulario" >
                                                <option value="" selected disabled>Select a Option</option>

                                                {foreach $listado_formulario as $ds}
                                                    <option value="{$ds['id']}" >{$ds['name']}</option>
                                                {/foreach}

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

                                    <div class="mb-3 row">
                                        <label for="AssignedStaff" class="col-sm-3"><span class="h6">Assigned staff</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <select id="AssignedStaff" name="AssignedStaff" class="form-select tenerAssignedStaff" {if $user["roleid"] eq 3}disabled{/if}>
                                                <option value="" selected disabled>Select a Option</option>
                                                
                                                {foreach $listado_staff as $ds}
                                                    <option value="{$ds['id']}" >{$ds['fullname']}</option>
                                                {/foreach}

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

                                    
  
                                </div>

                                <hr />

                                {* esta es una url de acceso *}
                                <div class="col-md-12 col-sm-12 mb-3">

                                    <div class="mb-3 row">
                                        <label for="Customers" class="col-sm-3"><span class="h6">Access URL:</span> </label>
                                        
                                        <div class="col-sm-9">
                                           <a href="{$URL_FORM_ISR}" class="cambiar_url_accesso" target="_blank"> <span class="h6">{$URL_FORM_ISR}</span></a>
                                        </div>

                                    </div>
                                    
                                </div>

                                {* esta es un campo 1*}
                                <div class="col-md-6 col-sm-12">

                                    <div class="mb-3 row">
                                        <label class="col-sm-3"><span class="h6">Last access by the client:</label>
                                        <div class="col-sm-9">
                                             <input type="text" class="form-control" value="{$data_form['update_date']}" readonly disabled>
                                        </div>
                                    </div>
 
                                </div>

                                {* esta es un campo 2*}
                                <div class="col-md-6 col-sm-12">

                                    <div class="mb-3 row">
                                        <label class="col-sm-3"><span class="h6">Form status:</label>
                                        <div class="col-sm-9">
                                             <input type="text" class="form-control" value="{$data_form['nombre_estado']}" readonly disabled>
                                        </div>
                                    </div>
 
                                </div>

                            <div class="row" style="margin:0px;">
                                <div class="col-md-12" style="padding:0px">
                                    <div class="mb-3" style='float: inline-end;'>
                                        
                                       {* {if $user["roleid"] eq 3}disabled{/if} *}  

                                        <button class="btn btn-primary mt-3 " type="button" id="submit">Save and Send</button>

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


                        </form>

                       
                    </div>

                  

                </div>
 
                <div class="block bloqueo_v1" style="display:none" hidden></div>
                <div class="block blockOverlay bloqueo_v2" hidden style="z-index: 1000; border: none; margin: 0px; padding: 0px; width: 100%; height: 100%; top: 0px; left: 0px; background-color: rgb(0, 0, 0); opacity: 0.6; cursor: wait; position: absolute;" ></div>
                <div
                    class="block blockMsg blockElement bloqueo_v3"
                    hidden
                    style="
                        z-index: 1011;
                        position: absolute;
                        padding: 0px;
                        margin: 0px;
                        width: 100%;
                        top: 370px;
                         
                        text-align: center;
                        color: rgb(0, 0, 0);
                        cursor: wait;
                    "
                    >
                     
                    <div class="md-preloader text-center">
                        <svg
                            xmlns="http://www.w3.org/2000/svg"
                            version="1.1"
                            height="32"
                            width="32"
                            viewBox="0 0 75 75"
                        >
                            <circle cx="37.5" cy="37.5" r="33.5" stroke-width="6"></circle>
                        </svg>
                    </div>

                     <div class="text-center mt-6" style="
                                                                color: white;
                                                                font-weight: 600;
                                                                font-size: 15px;
                                                            ">
                        This process may take up to 5 minutes. Please do not refresh or close the window.
                    </div>
                </div>

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


{* modal para agregar un nuevo formulario de customers *}

<div class="modal fade" id="addContacto" tabindex="-1" aria-labelledby="exampleModalLabel_" aria-hidden="true"  >
         <div class="modal-dialog modal-lg" style="width: 97%; max-width:97%;">
            <div class="modal-content" style="background-color:white">
               <div class="modal-header">
               <h5 class="modal-title" id="exampleModalLabel_">Add Contact</h5>
               <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></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>

                                          <form id="rform">

                                             <div class="row">
                                                <div class="col-md-6 col-sm-12">

                                                      <div class="mb-3 row">
                                                         <label for="account" class="col-sm-3"><span class="h6">{$_L['Full Name']}</span><span class="text-danger">*</span></label>
                                                         <div class="col-sm-9">
                                                            <input type="text" id="account" name="account" class="form-control" autofocus>
                                                         </div>
                                                      </div>


                                                      <div class="mb-3 row">
                                                         <label for="display_name" class="col-sm-3"><span class="h6">{$config['contact_extra_field']}</span><span class="text-danger"></span> </label>
                                                         <div class="col-sm-9">
                                                            <input type="text" id="display_name" name="display_name" class="form-control">
                                                         </div>
                                                      </div>

                                                     

 

                                                      <div class="mb-3 row">
                                                         <label for="country" class="col-sm-3"><span class="h6">{$_L['Country']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <select name="country" id="country" class="form-control">
                                                                  <option value=""><span></span>{$_L['Select Country']}</option>
                                                                  {$countries}
                                                            </select>
                                                         </div>
                                                      </div>


                                                   <!--   <div class="mb-3 row">
                                                         <label for="address" class="col-sm-3"><span class="h6">{$_L['Address']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" autocomplete="off"  id="address" name="address" class="form-control">
                                                            <ol class="list-group " id="browsers">
                                                            </ol>
                                                         </div>
                                                      </div>
                                                      -->

                                                      <div class="mb-3 row">
                                                         <label for="address" class="col-sm-3"><span class="h6">{$_L['Address']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" autocomplete="off"  id="address" name="address" class="form-control teneraddress">

                                                            <ol class="list-group-address" id="browsers">

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

                                                      <div class="mb-3 row">
                                                         <label for="city" class="col-sm-3"><span class="h6">{$_L['City']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" id="city" name="city" class="form-control">


                                                         </div>
                                                      </div>
 

                                                </div>
                                                <div class="col-md-6 col-sm-12">


                                                      <div class="mb-3 row">
                                                         <label for="email" class="col-sm-3"><span class="h6">{$_L['Email']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" id="email" name="email" class="form-control">

                                                         </div>
                                                      </div>
                                               
                                                      <div class="mb-3 row">
                                                         <label for="phone" class="col-sm-3"><span class="h6">{$_L['Phone']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" id="phone" name="phone" class="form-control" >

                                                         </div>
                                                      </div>
   

                                                      <div class="mb-3 row">
                                                         <label for="currency" class="col-sm-3"><span class="h6">{$_L['Currency']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <select id="currency" name="currency" class="form-control">

                                                                  {foreach $currencies as $currency}
                                                                  <option value="{$currency['id']}"
                                                                  {if $config['home_currency'] eq ($currency['cname'])}selected="selected" {/if}>{$currency['cname']}</option>
                                                                  {foreachelse}
                                                                  <option value="0">{$config['home_currency']}</option>
                                                                  {/foreach}

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

                                                      <div class="mb-3 row">
                                                         <label for="owner_id" class="col-sm-3"><span class="h6">{$_L['Owner']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <select class="form-select" name="owner_id" id="owner_id">
                                                                  {foreach $owners as $owner}
                                                                  <option value="{$owner->id}" {if $owner->id == $user->id}selected{/if} >{$owner->fullname}</option>
                                                                  {/foreach}
                                                            </select>
                                                         </div>
                                                      </div>


                                                   

                                                      <div class="mb-3 row">
                                                         <label for="state" class="col-sm-3"><span class="h6">{$_L['State Region']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" id="state" name="state" class="form-control">


                                                         </div>
                                                      </div>


                                                      <div class="mb-3 row">
                                                         <label for="zip" class="col-sm-3"><span class="h6">{$_L['ZIP Postal Code']}</span><span class="text-danger">*</span> </label>
                                                         <div class="col-sm-9">

                                                            <input type="text" id="zip" name="zip" class="form-control">
                                                         </div>
                                                      </div>

                                          
                                                </div>
                                             </div>


                                             <div class="row">
                                                <div class="col-md-12">
                                                      <div class="mb-3">
                                                         <button class="btn btn-primary mt-3 me-3" type="button" id="submit_addNewContact">{$_L['Save']}</button>
                                                      </div>
                                                </div>
                                             </div>


                                          </form>
                                    </div>

                                 </div>



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

{* modal para copia link de acceso a Formulario IRS *}
<div class="modal fade" id="modalFormIRS" tabindex="-1" aria-labelledby="modalFormIRS" aria-hidden="true"  data-bs-backdrop="static" >
         <div class="modal-dialog modal-lg" style="width: 80%; max-width: 80%;">
            <div class="modal-content" style="background-color:white">
               <div class="modal-header">
               <h5 class="modal-title" id="modalFormIRS">Form sent</h5>
               {* <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></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>

                                          <form id="rform">

                                             <div class="row">
                                             {* correo electronico *}
                                                <div class="col-md-12 col-sm-12">
                                                      <div class="mb-3 row">
                                                         <label class="col-sm-3"><span class="h6">El formulario ha sido enviado a la direccion de correo electronica</span></label>
                                                         <div class="col-sm-9">
                                                            <input type="text" class="form-control modal_correo" readonly disabled>
                                                         </div>
                                                      </div>
                                                </div>

                                                {* codigo de accesso *}
                                                <div class="col-md-12 col-sm-12">
                                                      <div class="mb-3 row">
                                                         <label  class="col-sm-3"><span class="h6">Código de acceso</span></label>
                                                         <div class="col-sm-9">
                                                            <input type="text" class="form-control modal_codigo_acceso" readonly disabled>
                                                         </div>
                                                      </div>
                                                </div>

                                                {* codigo de verificacion *}
                                                <div class="col-md-12 col-sm-12">
                                                      <div class="mb-3 row">
                                                         <label class="col-sm-3"><span class="h6">Código de verificación</span></label>
                                                         <div class="col-sm-9">
                                                            <input type="text" class="form-control modal_codigo_verificacion" readonly disabled>
                                                         </div>
                                                      </div>
                                                </div>

                                                {* esta es una url de acceso *}
                                                <div class="col-md-12 col-sm-12">
                                                      <div class="mb-3 row">

                                                         <label for="Customers" class="col-sm-3"><span class="h6">Access URL:</span> </label>

                                                         <div class="col-sm-9">
                                                            <a href="#" target="_blank" class="url_access"> <span class="h6">#</span></a>
                                                         </div>

                                                      </div>
                                                </div>

                                                <div class="col-md-12 col-sm-12"   >
                                                      <button class="btn btn-default mt-3" type="button" id="btn_copiar_hipervinculo" style=" float: inline-end; " >Copy URL</button>
                                                </div>

                                             </div>

                                             <hr>


                                             <div class="row">
                                                <div class="col-md-12">
                                                      <div class="mb-3" style="float: inline-end;">
                                                         <button class="btn btn-primary mt-3" type="button" id="submit_modal_confirmacion_correo" >Close</button>
                                                      </div>
                                                </div>
                                             </div>


                                          </form>
                                    </div>

                                 </div>



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



{/block}

{block name="script"}

{literal}
<script>

    var URL_BASE = $("#URL_BASE").val();
    var ID_USER = $("#ID_USER").val();
    var STAFF_ID_BACKEND = $("#staff_id_backend").val();
    var UUID_ENC_backend = $("#UUID_ENC_backend").val();

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

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

    $('.tenerPreguntaEnviarCorreo').val($("#question_mail_sent_backend").val());  
    $('.tenerCorreoElectronico').val($("#email_backend").val()); 

    $('.tenerAccessCode').val($("#tenerAccessCode_backend").val()); 
    $('.tenerVerificationCode').val($("#verification_code_backend").val()); 

    $("#country").select2({
       dropdownParent: $('#addContacto')  // Ajusta el modal donde aparece el select2
    }).on('select2:open', function() {
       $('.select2-container--open').css('z-index', 9999);  // Ajusta el z-index
    });

    $('.tenerCustomers').val($("#customer_id_backend").val());  

    $('.tenertipoFormulario').val($("#forms_category_id_backend").val());  

    $('.tenerAssignedStaff').val($("#staff_id_backend").val());  

    $(document).ready(function () {

 
        $(".progress").hide();
        $("#emsg").hide();
        $("#emsgSuccess").hide();

        var _url = '{$_url}';
    
        //para activar el customers
        $country = $("#Customers");
        $country.select2();

        $('#submit_modal_confirmacion_correo').on('click', function() {
            window.location = url_dashboard;    
        });
  
        $("#submit").click(function (e) {
            e.preventDefault();

            if(roll_id == 3)
            {
                if(ID_USER != STAFF_ID_BACKEND)
                {
                    toastr.error("!You do not have permission to perform this action¡");
                    return;
                }
            }

            //return;

            //$('.tenercard_name').attr('disabled', 'disabled');
 
            //tenerCustomers
            //tenerName
            //tenerPreguntaEnviarCorreo
            //tenerCorreoElectronico
            //tenerAccessCode
            //tenerVerificationCode
            //tenertipoFormulario
            //tenerAssignedStaff

            let tenerCustomers = $(".tenerCustomers").val();

            if(isEmpty(tenerCustomers))
            {
                toastr.error("!Select a customer¡");
                return;
            }

            let tenerName = $(".tenerName").val();

            if(isEmpty(tenerName))
            {
                toastr.error("!Customer name is requireds¡");
                return;
            }

            let tenerPreguntaEnviarCorreo = $(".tenerPreguntaEnviarCorreo").val();

            if(isEmpty(tenerPreguntaEnviarCorreo))
            {
                toastr.error("!Select an option if you want to send the email¡");
                return;
            }

            let tenerCorreoElectronico = $(".tenerCorreoElectronico").val();

            if(validateEmail(tenerCorreoElectronico) == false )
            {
                toastr.error("!Email is required¡");
                return;
            }

            let tenertipoFormulario = $(".tenertipoFormulario").val();

            if(isEmpty(tenertipoFormulario))
            {
                toastr.error("!Select a form type the field is required¡");
                return;
            }

            let tenerAssignedStaff = $(".tenerAssignedStaff").val();

            if(isEmpty(tenerAssignedStaff))
            {
                toastr.error("!Select a staff is required¡");
                return;
            }

            let tenerAccessCode = $(".tenerAccessCode").val();
            let tenerVerificationCode = $(".tenerVerificationCode").val();

            //$('#ibox_form').block({ message:block_msg });

            //$(".bloqueo_v1").removeAttr("hidden");
            //$(".bloqueo_v2").removeAttr("hidden");
            //$(".bloqueo_v3").removeAttr("hidden");
            
            $("#emsg").hide();
            $("#emsgSuccess").hide();

            //console.log(base_url + 'parnerts/add-parnert-post/');
            //console.log($( "#rform" ).serialize());

            //tenerCustomers
            //tenerName
            //tenerPreguntaEnviarCorreo
            //tenerCorreoElectronico
            //tenerAccessCode
            //tenerVerificationCode
            //tenertipoFormulario
            //tenerAssignedStaff

             $("#submit").prop("disabled", true); // Deshabilitar el botón
                
            var informacionEnviar = {
                tenerCustomers:                 $(".tenerCustomers").val(),
                tenerName:                      $(".tenerName").val(),
                tenerPreguntaEnviarCorreo:      $(".tenerPreguntaEnviarCorreo").val(),
                tenerCorreoElectronico:         $(".tenerCorreoElectronico").val(),
                tenerAccessCode:                $(".tenerAccessCode").val(),
                tenerVerificationCode:          $(".tenerVerificationCode").val(),
                tenertipoFormulario:            $(".tenertipoFormulario").val(),
                tenerAssignedStaff:             $(".tenerAssignedStaff").val(),

                //estado_formulario:              1,

                UUID_ENC:              UUID_ENC_backend,
            }; 
    
            console.log(JSON.stringify(informacionEnviar));
            //console.log("return aqui abajo")
            //return;

            //return;

            $.post(URL_BASE + 'forms/post-modify-forms/', JSON.stringify(informacionEnviar)  ) //$( "#rform" ).serialize()
            .done(function (data) {

                $("#submit").prop("disabled", false); // Deshabilitar el botón
                 
                    //console.log(data);
                    //console.log(data);
                    //return;

                    //$(".bloqueo_v1").attr("hidden", true);
                    //$(".bloqueo_v2").attr("hidden", true);
                    //$(".bloqueo_v3").attr("hidden", true);

                     try {
                        
                        const info = JSON.parse(data);
                       
                        if( info.type == "success")
                        {
                            //$('#ibox_form').unblock();
                            toastr.success(info.message);

                            /* var body = $("html, body");
                            body.animate({ scrollTop:0 }, '1000', 'swing'); 
                            $("#emsgbodySuccess").html(info.message);
                            $("#emsgSuccess").show("slow"); */
 
                            //window.location = info.redirect;
                            if(tenerPreguntaEnviarCorreo == 1)
                            {
                                $(".modal_correo").val(tenerCorreoElectronico);
                                $(".modal_codigo_acceso").val(tenerAccessCode);
                                $(".modal_codigo_verificacion").val(tenerVerificationCode);

                                let url_access = info.url_formulario_IRS;

                                $(".url_access").attr("href", url_access).find("span").text(url_access);

                                $("#modalFormIRS").modal("show");
                            }else{
                                window.location = info.redirect;    
                            }

                        }else{
                            //$('#ibox_form').unblock();
                            var body = $("html, body");
                            body.animate({ scrollTop:0 }, '1000', 'swing');
                            $("#emsgbody").html(info.message);
                            $("#emsg").show("slow");
                        }
                    } catch (error) {
                        //$('#ibox_form').unblock();
                        var body = $("html, body");
                        body.animate({ scrollTop:0 }, '1000', 'swing');
                        $("#emsgbody").html(data);
                        $("#emsg").show("slow");
                    }
            });
        });

        $('#tipoFormulario').on('change', function () {
            // Obtiene el valor seleccionado
            const selectedValue = $(this).val();
            
            // Realiza una acción, por ejemplo, mostrar el valor en consola
            //console.log('Seleccionaste la opción con valor:', selectedValue);

            let url_final = "";

            if (selectedValue === "3") {
               //W-7
               url_final = URL_FORM_ISR_original + "W-7/" + UUID_ENC_backend;
            } 

            if (selectedValue === "2") {
               //656
               url_final = URL_FORM_ISR_original + "433-A/" + UUID_ENC_backend;
            } 

            if (selectedValue === "1") {
               //656
               url_final = URL_FORM_ISR_original + "656/" + UUID_ENC_backend;
            } 


            $('.cambiar_url_accesso').attr('href', url_final);
            $('.cambiar_url_accesso span').text(url_final);

        });

      $('#btn_copiar_hipervinculo').click(function() {

         const url = $('.url_access').attr('href');

         navigator.clipboard.writeText(url)
            .then(() => {
                  alert('URL copied to clipboard: ' + url);  
            })
            .catch(err => {
                  console.error('Error copying URL: ', err);  
            });

 
      });


    });

  

    $('#Customers').on('change click', function() {
        const selectedValue = $(this).val(); // Captura el valor seleccionado
        let selectedOption = $(this).find('option:selected'); // Obtiene el <option> seleccionado
        console.log('Valor seleccionado:', selectedValue);


        //data-email="{$ds['email']}" data-account="{$ds['account']}"
        
        // Puedes agregar lógica adicional aquí
        if (selectedValue === "-100") {
            //alert('Seleccionaste New Customers');
            
            $("#account").val("");
            $("#display_name").val("");
            
            $("#address").val("");
            $("#city").val("");
            $("#email").val("");
            $("#phone").val("");
            //$("#currency").val("");
             
            $("#username").val("");
            $("#state").val("");
            $("#zip").val("");
            $("#phone").val("");

            $("#addContacto").modal("show");
        } else if (selectedValue) {
            //alert('Seleccionaste el cliente con ID: ' + selectedValue);

            // Acceder a los atributos data-* del <option> seleccionado
            let dataEmail = selectedOption.data('email'); // Accede a data-type
            let dataAccount = selectedOption.data('account'); // Accede a data-priority

            //console.log('Data-Email:', dataEmail);
            //console.log('Data-Account:', dataAccount);

            $(".tenerName").val(dataAccount);
            $(".tenerCorreoElectronico").val(dataEmail);

        }
    });

    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;
    }
 
    function validarSoloNumeros(input) {
        const number = parseInt(input, 10);
        return !isNaN(number) && number.toString() === input;
    }

    function validateEmail(email) {
       // Expresión regular para validar un formato de correo electrónico
       var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
       
       if (emailPattern.test(email)) {
          return true;  // Es un correo válido
       } else {
          return false;  // No es un correo válido
       }
    }

    $("#submit_addNewContact").click(function (e) {

            e.preventDefault();
            //$('#ibox_form').block({ message:block_msg });
 
            let account = $("#account").val();
            let display_name = $("#display_name").val();
            let country = $("#country").val();
            let address = $("#address").val();
            let city = $("#city").val();
            let email = $("#email").val();
            let phone = $("#phone").val();
            let currency = $("#currency").val();
            let owner_id = $("#owner_id").val();
            let username = $("#username").val();
            let state = $("#state").val();
            let zip = $("#zip").val();

            if (isEmpty(account)) {
               Swal.fire("The Full Name field is required.");
               return false;
            }

            /* if (isEmpty(display_name)) {
               Swal.fire("The Display Name field is required.");
               return false;
            } */

            if (isEmpty(country)) {
               Swal.fire("The Country field is required.");
               return false;
            }

            if (isEmpty(address)) {
               Swal.fire("The Address field is required.");
               return false;
            }

            if (isEmpty(city)) {
               Swal.fire("The City field is required.");
               return false;
            }

            if (isEmpty(email)) {
               Swal.fire("The Email field is required.");
               return false;
            }


            if (isEmpty(currency)) {
               Swal.fire("The Currency field is required.");
               return false;
            }

            if (isEmpty(owner_id)) {
               Swal.fire("The Owner ID field is required.");
               return false;
            }

            /* if (isEmpty(username)) {
               Swal.fire("The Username field is required.");
               return false;
            } */

            if (isEmpty(state)) {
               Swal.fire("The State field is required.");
               return false;
            }

            if (isEmpty(zip)) {
               Swal.fire("The ZIP field is required.");
               return false;
            }

            if (validateEmail(email) == false) {
               Swal.fire("The Email field is invalid.");
               return false;
            }

            let informacion = {
               account: account,
               display_name: display_name,
               country: country,
               address: address,
               city: city,
               email: email,
               currency: currency,
               owner_id: owner_id,
               username: username,
               state: state,
               zip: zip,
               staff_id: ID_USER,
            };

            //console.log(informacion);
            console.log(JSON.stringify(informacion));
            //console.log("return aqui abajo");
            //return;

            $("#submit_addNewContact").prop("disabled", true); // Deshabilitar el botón

            // Realizar la solicitud POST
            $.ajax({
               type: "POST",
               url: URL_BASE + "forms/agregar-custumers-contacto-chat",
               data: JSON.stringify(informacion), // Convertir datos a formato JSON
               contentType: "application/json", // Tipo de contenido JSON
               success: function (response) {
                  //console.log("Respuesta del servidor:", response);
                  // Hacer algo con la respuesta del servidor

                  $("#submit_addNewContact").prop("disabled", false); // Habilitar el botón

                  //console.log(response);

                  try {
                     let info = JSON.parse(response);

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

                        /* let {
                           id,
                           number,
                           custumer_id,
                           staff_id,
                           created_at,
                           nombre,
                           email_custumers,
                           phone_custumers,
                           company_custumers,
                           address_custumers,
                           fullname_staff,
                           username_staff,
                           user_type_staff,
                           phonenumber,
                           sys_users_config_whatsapp_other_id
                        } = info.contactos; */

                        let contacto_id = info.contact_id;

                        //console.log("el ultimo contacto fue:");
                        //console.log(contacto_id);

                        let texto = account;

                        //let nuevaOpcion = `<option value="${contacto_id}">${texto}</option>`;
                        let nuevaOpcion = `<option value="${contacto_id}" data-email="${email}" data-account="${account}">${texto}</option>`;


                        // Agregar la nueva opción al final del <select>
                        $('.tenerCustomers').append(nuevaOpcion);

                        $(".tenerName").val(account);
                        $(".tenerCorreoElectronico").val(email);

                        $('.tenerCustomers').val(contacto_id).trigger('change');  

                        Swal.fire({
                           title: "Contact added!",
                           text: "The contact has been added successfully!",
                           icon: "success"
                        });

                        $("#addContacto").modal("hide");

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

             
    });


    function serach_address(address,secundary,option = 1) {

      let url_modulo_api_direccion_smarty =  $(".url_modulo_api_direccion_smarty").val();
      let key_modulo_api_direccion_smarty =  $(".key_modulo_api_direccion_smarty").val();

      //console.log(url_modulo_api_direccion_smarty);
      //console.log(key_modulo_api_direccion_smarty);
 
      if(isEmpty(url_modulo_api_direccion_smarty) == true || isEmpty(key_modulo_api_direccion_smarty) == true)
      {
         return;
      }

    var country = $('#country').val();
    let x=address.trim();

    if (x.length > 2 && country === "United States") {
        var settings = {
        //"url": "https://us-autocomplete-pro.api.smarty.com/lookup?key=188805315395749398&search="+address+"&selected="+secundary+"&include_only_cities=&include_only_states=&include_only_zip_codes=&exclude_states=&prefer_cities=&prefer_states=&prefer_zip_codes=&source=all",
        "url": url_modulo_api_direccion_smarty + "/lookup?key=" + key_modulo_api_direccion_smarty + "&search="+address+"&selected="+secundary+"&include_only_cities=&include_only_states=&include_only_zip_codes=&exclude_states=&prefer_cities=&prefer_states=&prefer_zip_codes=&source=all",
        "method": "GET",
        "timeout": 0,
        "headers": {
            "Host": "us-autocomplete-pro.api.smarty.com",
            "Referer": "https://hispanosdeexitollc.com"
        },
    };

     

$('#browsers').html('');
$('#browsers').show();

$.ajax(settings).done(function (response) {

        $.each(response.suggestions, function (k, v) {
            let text=v.street_line+' '+v.secondary+' '+v.city+', '+v.state+' '+v.zipcode;
            let line=v.street_line+' '+v.secondary+' ('+v.entries+') '+v.city+', '+v.state+' '+v.zipcode;
            let line2=v.street_line+' '+v.secondary;
            let entries=(v.entries > 1) ? '<a href="#" data-data1="'+line+'" data-data2="'+line2+'" class="addresssec"><span class="badge bg-primary rounded-pill">+ '+v.entries+' Address</span></a>' : "" ;
            let option='<li class="list-group-item d-flex justify-content-between align-items-start "><div class="ms-2 me-auto address1" data-data1="'+v.city+'" data-data2="'+v.state+'" data-data3="'+v.zipcode+'" data-data4="'+v.street_line+' '+v.secondary+'"><div class="fw-bold">'+text+'</div></div>'+entries+'</li>';
            $('#browsers').append(option);
            x++;
        });
    });
}
}



$("input[name='address']").on('input', function(e){
  var address = $(this).val();
  var country = $('#country').val();
  let x=address.trim();
  if (x.length > 2 && country === "United States") {
    address = address.replace(/,/g, "");
    address = address.replace(/ /g, "+");
    address = address.replace(/#/g, "%23");
    serach_address(address,"",1);    
}
});


$(document).on('click', '.address1', function(e){
    e.preventDefault();
    $('#city').val($(this).data('data1'));
    $('#state').val($(this).data('data2'));
    $('#zip').val($(this).data('data3'));
    $('#address').val($(this).data('data4'));
    $('#browsers').hide();

});


$(document).on('click', '.addresssec', function(e){
    e.preventDefault();
    let address=$(this).data('data2');
    $('#address').val(address);
    let secundary=$(this).data('data1');
    secundary = secundary.replace(/,/g, "");
    secundary = secundary.replace(/ /g, "+");
    secundary = secundary.replace(/#/g, "%23");
    address = address.replace(/,/g, "");
    address = address.replace(/ /g, "+");
    address = address.replace(/#/g, "%23");
    serach_address(address,secundary,2);
});

</script>
{/literal}


{/block}