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

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




{/block}

{block name="content"}

<style type="text/css">

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

    .quitar_margin_pading{
        padding: 0px;
        margin: 0px;
    }

       .btn-edit {
         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-edit:hover i,
   .btn-eliminar:hover i {
      color: white; /* Mantén el color blanco del icono en hover */
   }


</style>
<div class="row">

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

    <textarea disabled hidden class="tener_compania" value="{$companies_json}">
        {$companies_json}
    </textarea>

    <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  >
    <input type="text" id="host_modulo_api_direccion_smarty" name="host_modulo_api_direccion_smarty" class="form-control host_modulo_api_direccion_smarty" value="{$host_modulo_api_direccion_smarty}" disabled hidden  >
    <input type="text" id="referer_modulo_api_direccion_smarty" name="referer_modulo_api_direccion_smarty" class="form-control referer_modulo_api_direccion_smarty" value="{$referer_modulo_api_direccion_smarty}" disabled hidden  >

        <div class="panel">
            <div class="panel-hdr">
                <h2><span></span>{$_L['Add Contact']}</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>

                        <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="code" class="col-sm-3"><span class="h6">{$_L['Code']}</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="code" name="code" class="form-control" value="{$predict_customer_number}">
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="display_name" class="col-sm-3"><span class="h6">{$config['contact_extra_field']}</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="cid" class="col-sm-3"><span class="h6">{$_L['Company']}</span> </label>
                                            <div class="col-sm-9">
                                                <select id="cid" name="cid" class="form-control">
                                                    <option value="0">{$_L['None']}</option>
                                                    {foreach $companies as $company}
                                                    <option value="{$company['id']}" {if $c_selected_id eq ($company['id'])}selected{/if}>
                                                        {$company['company_name']}
                                                    </option>
                                                    {/foreach}
                                                </select>
                                            </div>
                                        </div>
                                    *}
                                    

                                    {if $config['show_business_number'] eq '1'}
                                    <div class="mb-3 row">
                                        <label for="business_number" class="col-sm-3"><span class="h6">{$config['label_business_number']}</span> </label>
                                        <div class="col-sm-9">
                                            <input type="text" id="business_number" name="business_number" class="form-control">
                                        </div>
                                    </div>


                                    {/if}

                                    <div class="mb-3 row">
                                        <label for="type" class="col-sm-3"><span class="h6">{$_L['Type']}</span> </label>
                                        <div class="col-sm-9">
                                            <div class="custom-control my-2 custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="defaultChecked" name="customer" value="Customer" {if $contact_type eq 'customer'}checked{/if}>
                                                <label class="custom-control-label" for="defaultChecked"><span class="h6">{$_L['Customer']}</span></label>
                                            </div>

                                            <div class="custom-control my-2 custom-checkbox">
                                                <input type="checkbox" class="custom-control-input" id="input_supplier" name="supplier" value="Supplier" {if $contact_type eq 'supplier'}checked{/if}>
                                                <label class="custom-control-label" for="input_supplier"><span class="h6">{$_L['Supplier']}</span></label>
                                            </div>

                                        </div>
                                    </div>


                                    {if $config['fax_field'] eq '1'}

                                    <div class="mb-3 row">
                                        <label for="fax" class="col-sm-3"><span class="h6">{$_L['Fax']}</span></label>
                                        <div class="col-sm-9">

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


                                        </div>
                                    </div>


                                    {/if}


                                    <div class="mb-3 row">
                                        <label for="country" class="col-sm-3"><span class="h6">{$_L['Country']}</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="nationality" class="col-sm-3"><span class="h6">Nationality</span> </label>
                                        <div class="col-sm-9">

                                            <select name="nationality" id="nationality" class="form-control nationality">
                                                <option value=""><span></span>Select Nationality</option>
                                                {$countries}
                                            </select>
                                        </div>
                                    </div>

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

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


                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="state" class="col-sm-3"><span class="h6">{$_L['State Region']}</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> </label>
                                        <div class="col-sm-9">

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







                                    {foreach $fs as $f}
                                    <div class="mb-3 row">
                                        <label class="form-label col-sm-3" for="cf{$f['id']}"><span class="h6">{$f['fieldname']}</span></label>
                                        {if ($f['fieldtype']) eq 'text'}


                                        <div class="col-sm-9">

                                            <input type="text" id="cf{$f['id']}" name="cf{$f['id']}" class="form-control">
                                            {if ($f['description']) neq ''}
                                            <p class="help-block mb-2">{$f['description']}</p>
                                            {/if}
                                        </div>


                                        {elseif ($f['fieldtype']) eq 'password'}

                                        <div class="col-sm-9">
                                            <input type="password" id="cf{$f['id']}" name="cf{$f['id']}" class="form-control">
                                            {if ($f['description']) neq ''}
                                            <p class="help-block mb-2">{$f['description']}</p>
                                            {/if}
                                        </div>



                                        {elseif ($f['fieldtype']) eq 'dropdown'}

                                        <div class="col-sm-9">
                                            <select id="cf{$f['id']}" name="cf{$f['id']}" class="form-control">
                                                {foreach explode(',',$f['fieldoptions']) as $fo}
                                                <option value="{$fo}">{$fo}</option>
                                                {/foreach}
                                            </select>
                                            {if ($f['description']) neq ''}
                                            <p class="help-block mb-2">{$f['description']}</p>
                                            {/if}
                                        </div>


                                        {elseif ($f['fieldtype']) eq 'textarea'}

                                        <div class="col-sm-9">
                                            <textarea id="cf{$f['id']}" name="cf{$f['id']}" class="form-control" rows="3"></textarea>
                                            {if ($f['description']) neq ''}
                                            <p class="help-block mb-2">{$f['description']}</p>
                                            {/if}
                                        </div>

                                        {/if}

                                    </div>
                                    {/foreach}

                                </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="secondary_email" class="col-sm-3"><span class="h6">{$_L['Secondary Email']}</span> </label>
                                        <div class="col-sm-9">

                                            <input type="text" id="secondary_email" name="secondary_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-12 col-sm-4">

                                            <select class="form-control form-control-sm" id="codigo_pais" name="codigo_pais" id="codigo_pais"></select>

                                        </div>

                                        <div class="col-12 col-sm-5">

                                            <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> </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="group" class="col-sm-3"><span class="h6">{$_L['Group']} </span> <span class="text-danger">*</span> </label>
                                        <div class="col-sm-9">

                                            <select class="form-select tener_grupo_seleccionado" name="group" id="group">
                                                <option value="0" selected disabled>Select an option</option>
                                                {foreach $gs as $g}
                                                <option value="{$g['id']}" {if $g_selected_id eq ($g['id'])}selected{/if}>{$g['gname']}</option>
                                                {/foreach}
                                            </select>
                                            <span class="help-block "><a href="#" id="add_new_group" class="text-info"> <span class="h6 text-info"><i class="fal fa-plus"></i> {$_L['Add New Group']}</a></span> </span>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="owner_id" class="col-sm-3"><span class="h6">{$_L['Owner']}</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>



                                    {if $config['customer_custom_username']}

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

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

                                    {/if}

                                    <div class="mb-3 row">
                                        <label for="password" class="col-sm-3"><span class="h6">{$_L['Password']}</span><span class="text-danger">*</span> </label>
                                        <div class="col-sm-9">
                                            <input type="password" id="password" name="password" class="form-control">
                                            <a href="javascript:;" id="generate_password"><span>{__('Generate Password')}</span></a>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="cpassword" class="col-sm-3"><span class="h6">{$_L['Confirm Password']}</span></label>
                                        <div class="col-sm-9">

                                            <input type="password" id="cpassword" name="cpassword" class="form-control">
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="send_client_signup_email" class="col-sm-3"><span class="h6">{$_L['Welcome Email']}</span></label>
                                        <div class="col-sm-9">
                                            <label class="switch s-icons s-outline s-outline-primary">
                                                <input type="checkbox" name="send_client_signup_email" value="on" id="send_client_signup_email" checked>
                                                <span class="slider round"></span>
                                            </label>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="position" class="col-sm-3"><span class="h6">Position</span></span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="position" name="position" class="form-control">
                                        </div>
                                    </div>

                                </div>
 

                                <div class="col-md-12 col-sm-12">
                                
                                    <div class="mb-3 row">
                                        <label for="notas" class="col-sm-3"><span class="h6">Note</span> </label>
                                        <div class="col-sm-9">

                                            <textarea class="form-control notas" id="notas" name="notas" rows="3" ></textarea>

                                        </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="submit" id="submit">{$_L['Save']}</button>

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

                        </form>
                    </div>

                </div>



            </div>
        </div>

        {**}

        {*informacion general*}
        <div class="col-md-12">
            <div class="panel">
                <div class="panel-hdr">
                    <h2>Add company</h2>
                </div>

                <div class="panel-container show" id="ibox_form" style=" border-radius: 18px; ">
                    <div class="panel-content" style=" padding-bottom: 0px; ">
                    
                        <form>
                            <div class="row">
                            
                                <div class="col-12 col-md-9 col-sm-9 col-lg-10">
                                    <div class="mb-3 row">
                                        <label
                                            for="tipo_identificacion_ig"
                                            class="col-sm-3"
                                            ><span class="h6">Company</span
                                            ><span class="text-danger">*</span></label
                                        >

                                        <div class="col-sm-9">
                                            <select id="compania" name="compania" class="form-control compania">
                                                <option value="">Select a company</option>
                                                {foreach $companies as $company}
                                                <option value="{$company['id']}" {if $c_selected_id eq ($company['id'])}selected{/if}>
                                                    {$company['company_name']}
                                                </option>
                                                {/foreach}
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12 col-md-3 col-sm-3 col-lg-2 quitar_margin_pading">
                                    <button
                                        type="button"
                                        class="btn btn-sm btn-success waves-effect waves-themed guardar_tabla_compania" 
                                        style=" float: inline-end; margin-right: 21px; margin-bottom: 10px; "
                                    >
                                        Add information
                                    </button>
                                </div>
 
                            </div>
                        </form>
        
                    </div>
 
                </div>

                <div class="row quitar_margin_pading">

                     

                    <div class="col-12 quitar_margin_pading">
                        <div class="table-responsive" style=" border-radius: 5px; ">
                            <table
                                class="table table-striped table-hover estilosTabla"
                                id="clx_datatable"
                                style="margin: 0px"
                            >
                                <thead>
                                <tr>
                                    <th class="centrar">Company</th>
                                
                                    <th class="centrar"></th>
                                </tr>
                                </thead>

                                <tbody class="tbody_envios_identificador">

                                <tr><th colspan="4" class="centrar " style=" text-align: center; "> No information</th></tr>
            
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                </div>
        

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


        {**}

        {*boton para guardar*}

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

                {*
                    <div class="panel-hdr">
                        <h2>Referenced by</h2>
                    </div>
                *}
                 
                <div class="panel-container show" id="ibox_form">
                    <div class="panel-content">
                        <div >
                            
                            <div class="row">
                                <div class="col-md-12">
                                    <div  style="float: inline-end">
                                        <button
                                            class="btn btn-primary waves-effect waves-themed guardar_siguiente"
                                            type="button"
                                            id="submit"
                                        >
                                            Save
                                        </button>

                                        <button
                                            class="btn btn-primary waves-effect waves-themed loading_guardar_siguiente"
                                            style="display: none"
                                            disabled
                                        >
                                            <div
                                                style="display: flex; align-items: center"
                                            >
                                                <span
                                                class="spinner-border spinner-border-sm"
                                                style="
                                                    height: 20px;
                                                    width: 20px;
                                                    margin-right: 5px;
                                                "
                                                role="status"
                                                aria-hidden="true"
                                                ></span>
                                                Save
                                            </div>
                                        </button>
                                    </div>
                                </div>
                            </div>

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

        {**}

    </div>
</div>




{/block}

{block name="script"}

{literal}
<script>
function generateUUIDv4() {
    // Generar un prefijo único basado en microsegundos
    const time_low = Date.now().toString(16).padStart(8, '0') + Math.random().toString(16).slice(2, 6);

    // Generar 8 bytes aleatorios
    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 = [
        time_low.slice(0, 8),
        time_low.slice(8, 12),
        '4' + extra_bytes.slice(0, 3),
        ((parseInt(extra_bytes.slice(3, 7), 16) & 0x3fff) | 0x8000).toString(16),
        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;
}
</script>
{/literal}

<script>

    function isEmpty(value) {

            // Verificar si es nulo o indefinido
            if (value === null || value === undefined) return true;

            // Verificar si es una cadena
            if (typeof value === 'string') {
               return value.trim().length === 0;
            }

            // Verificar si es un arreglo
            if (Array.isArray(value)) {
               return value.length === 0;
            }

            // Verificar si es un objeto
            if (typeof value === 'object') {
               return Object.keys(value).length === 0;
            }

            // Para otros tipos (número, booleano, función), ajusta según tus necesidades
            return false;
 
            // Verifica si el valor es nulo, indefinido, o una cadena vacía (después de eliminar espacios)
            //return value === null || value === undefined || value === "";
    }

    let paisesConCodigos = [
        {
           pais: 'United States',
           codigo: '1',
           flag: 'https://flagcdn.com/w20/us.png',
        },
        { pais: 'Honduras', codigo: '504', flag: 'https://flagcdn.com/w20/hn.png' },
        {
           pais: 'Afghanistan',
           codigo: '93',
           flag: 'https://flagcdn.com/w20/af.png',
        },
        { pais: 'Albania', codigo: '355', flag: 'https://flagcdn.com/w20/al.png' },
        { pais: 'Algeria', codigo: '213', flag: 'https://flagcdn.com/w20/dz.png' },
        { pais: 'Andorra', codigo: '376', flag: 'https://flagcdn.com/w20/ad.png' },
        { pais: 'Angola', codigo: '244', flag: 'https://flagcdn.com/w20/ao.png' },
        {
           pais: 'Antigua and Barbuda',
           codigo: '1-268',
           flag: 'https://flagcdn.com/w20/ag.png',
        },
        { pais: 'Argentina', codigo: '54', flag: 'https://flagcdn.com/w20/ar.png' },
        { pais: 'Armenia', codigo: '374', flag: 'https://flagcdn.com/w20/am.png' },
        { pais: 'Australia', codigo: '61', flag: 'https://flagcdn.com/w20/au.png' },
        { pais: 'Austria', codigo: '43', flag: 'https://flagcdn.com/w20/at.png' },
        {
           pais: 'Azerbaijan',
           codigo: '994',
           flag: 'https://flagcdn.com/w20/az.png',
        },
        {
           pais: 'Bahamas',
           codigo: '1-242',
           flag: 'https://flagcdn.com/w20/bs.png',
        },
        { pais: 'Bahrain', codigo: '973', flag: 'https://flagcdn.com/w20/bh.png' },
        {
           pais: 'Bangladesh',
           codigo: '880',
           flag: 'https://flagcdn.com/w20/bd.png',
        },
        {
           pais: 'Barbados',
           codigo: '1-246',
           flag: 'https://flagcdn.com/w20/bb.png',
        },
        { pais: 'Belarus', codigo: '375', flag: 'https://flagcdn.com/w20/by.png' },
        { pais: 'Belgium', codigo: '32', flag: 'https://flagcdn.com/w20/be.png' },
        { pais: 'Belize', codigo: '501', flag: 'https://flagcdn.com/w20/bz.png' },
        { pais: 'Benin', codigo: '229', flag: 'https://flagcdn.com/w20/bj.png' },
        { pais: 'Bhutan', codigo: '975', flag: 'https://flagcdn.com/w20/bt.png' },
        { pais: 'Bolivia', codigo: '591', flag: 'https://flagcdn.com/w20/bo.png' },
        {
           pais: 'Bosnia and Herzegovina',
           codigo: '387',
           flag: 'https://flagcdn.com/w20/ba.png',
        },
        { pais: 'Botswana', codigo: '267', flag: 'https://flagcdn.com/w20/bw.png' },
        { pais: 'Brazil', codigo: '55', flag: 'https://flagcdn.com/w20/br.png' },
        { pais: 'Brunei', codigo: '673', flag: 'https://flagcdn.com/w20/bn.png' },
        { pais: 'Bulgaria', codigo: '359', flag: 'https://flagcdn.com/w20/bg.png' },
        {
           pais: 'Burkina Faso',
           codigo: '226',
           flag: 'https://flagcdn.com/w20/bf.png',
        },
        { pais: 'Burundi', codigo: '257', flag: 'https://flagcdn.com/w20/bi.png' },
        {
           pais: 'Cabo Verde',
           codigo: '238',
           flag: 'https://flagcdn.com/w20/cv.png',
        },
        { pais: 'Cambodia', codigo: '855', flag: 'https://flagcdn.com/w20/kh.png' },
        { pais: 'Cameroon', codigo: '237', flag: 'https://flagcdn.com/w20/cm.png' },
        { pais: 'Canada', codigo: '1', flag: 'https://flagcdn.com/w20/ca.png' },
        {
           pais: 'Central African Republic',
           codigo: '236',
           flag: 'https://flagcdn.com/w20/cf.png',
        },
        { pais: 'Chad', codigo: '235', flag: 'https://flagcdn.com/w20/td.png' },
        { pais: 'Chile', codigo: '56', flag: 'https://flagcdn.com/w20/cl.png' },
        { pais: 'China', codigo: '86', flag: 'https://flagcdn.com/w20/cn.png' },
        { pais: 'Colombia', codigo: '57', flag: 'https://flagcdn.com/w20/co.png' },
        { pais: 'Comoros', codigo: '269', flag: 'https://flagcdn.com/w20/km.png' },
        {
           pais: 'Congo (Brazzaville)',
           codigo: '242',
           flag: 'https://flagcdn.com/w20/cg.png',
        },
        {
           pais: 'Congo (Kinshasa)',
           codigo: '243',
           flag: 'https://flagcdn.com/w20/cd.png',
        },
        {
           pais: 'Costa Rica',
           codigo: '506',
           flag: 'https://flagcdn.com/w20/cr.png',
        },
        { pais: 'Croatia', codigo: '385', flag: 'https://flagcdn.com/w20/hr.png' },
        { pais: 'Cuba', codigo: '53', flag: 'https://flagcdn.com/w20/cu.png' },
        { pais: 'Cyprus', codigo: '357', flag: 'https://flagcdn.com/w20/cy.png' },
        {
           pais: 'Czech Republic',
           codigo: '420',
           flag: 'https://flagcdn.com/w20/cz.png',
        },
        { pais: 'Denmark', codigo: '45', flag: 'https://flagcdn.com/w20/dk.png' },
        { pais: 'Djibouti', codigo: '253', flag: 'https://flagcdn.com/w20/dj.png' },
        {
           pais: 'Dominica',
           codigo: '1-767',
           flag: 'https://flagcdn.com/w20/dm.png',
        },
        {
           pais: 'Dominican Republic',
           codigo: '1-809',
           flag: 'https://flagcdn.com/w20/do.png',
        },
        { pais: 'Ecuador', codigo: '593', flag: 'https://flagcdn.com/w20/ec.png' },
        { pais: 'Egypt', codigo: '20', flag: 'https://flagcdn.com/w20/eg.png' },
        {
           pais: 'El Salvador',
           codigo: '503',
           flag: 'https://flagcdn.com/w20/sv.png',
        },
        {
           pais: 'Equatorial Guinea',
           codigo: '240',
           flag: 'https://flagcdn.com/w20/gq.png',
        },
        { pais: 'Eritrea', codigo: '291', flag: 'https://flagcdn.com/w20/er.png' },
        { pais: 'Estonia', codigo: '372', flag: 'https://flagcdn.com/w20/ee.png' },
        { pais: 'Eswatini', codigo: '268', flag: 'https://flagcdn.com/w20/sz.png' },
        { pais: 'Ethiopia', codigo: '251', flag: 'https://flagcdn.com/w20/et.png' },
        { pais: 'Fiji', codigo: '679', flag: 'https://flagcdn.com/w20/fj.png' },
        { pais: 'Finland', codigo: '358', flag: 'https://flagcdn.com/w20/fi.png' },
        { pais: 'France', codigo: '33', flag: 'https://flagcdn.com/w20/fr.png' },
        { pais: 'Gabon', codigo: '241', flag: 'https://flagcdn.com/w20/ga.png' },
        { pais: 'Gambia', codigo: '220', flag: 'https://flagcdn.com/w20/gm.png' },
        { pais: 'Georgia', codigo: '995', flag: 'https://flagcdn.com/w20/ge.png' },
        { pais: 'Germany', codigo: '49', flag: 'https://flagcdn.com/w20/de.png' },
        { pais: 'Ghana', codigo: '233', flag: 'https://flagcdn.com/w20/gh.png' },
        { pais: 'Greece', codigo: '30', flag: 'https://flagcdn.com/w20/gr.png' },
        {
           pais: 'Grenada',
           codigo: '1-473',
           flag: 'https://flagcdn.com/w20/gd.png',
        },
        {
           pais: 'Guatemala',
           codigo: '502',
           flag: 'https://flagcdn.com/w20/gt.png',
        },
        { pais: 'Guinea', codigo: '224', flag: 'https://flagcdn.com/w20/gn.png' },
        {
           pais: 'Guinea-Bissau',
           codigo: '245',
           flag: 'https://flagcdn.com/w20/gw.png',
        },
        { pais: 'Guyana', codigo: '592', flag: 'https://flagcdn.com/w20/gy.png' },
        { pais: 'Haiti', codigo: '509', flag: 'https://flagcdn.com/w20/ht.png' },
        { pais: 'Hungary', codigo: '36', flag: 'https://flagcdn.com/w20/hu.png' },
        { pais: 'Iceland', codigo: '354', flag: 'https://flagcdn.com/w20/is.png' },
        { pais: 'India', codigo: '91', flag: 'https://flagcdn.com/w20/in.png' },
        { pais: 'Indonesia', codigo: '62', flag: 'https://flagcdn.com/w20/id.png' },
        { pais: 'Iran', codigo: '98', flag: 'https://flagcdn.com/w20/ir.png' },
        { pais: 'Iraq', codigo: '964', flag: 'https://flagcdn.com/w20/iq.png' },
        { pais: 'Ireland', codigo: '353', flag: 'https://flagcdn.com/w20/ie.png' },
        { pais: 'Israel', codigo: '972', flag: 'https://flagcdn.com/w20/il.png' },
        { pais: 'Italy', codigo: '39', flag: 'https://flagcdn.com/w20/it.png' },
        {
           pais: 'Jamaica',
           codigo: '1-876',
           flag: 'https://flagcdn.com/w20/jm.png',
        },
        { pais: 'Japan', codigo: '81', flag: 'https://flagcdn.com/w20/jp.png' },
        { pais: 'Jordan', codigo: '962', flag: 'https://flagcdn.com/w20/jo.png' },
        { pais: 'Kazakhstan', codigo: '7', flag: 'https://flagcdn.com/w20/kz.png' },
        { pais: 'Kenya', codigo: '254', flag: 'https://flagcdn.com/w20/ke.png' },
        { pais: 'Kiribati', codigo: '686', flag: 'https://flagcdn.com/w20/ki.png' },
        { pais: 'Kuwait', codigo: '965', flag: 'https://flagcdn.com/w20/kw.png' },
        {
           pais: 'Kyrgyzstan',
           codigo: '996',
           flag: 'https://flagcdn.com/w20/kg.png',
        },
        { pais: 'Laos', codigo: '856', flag: 'https://flagcdn.com/w20/la.png' },
        { pais: 'Latvia', codigo: '371', flag: 'https://flagcdn.com/w20/lv.png' },
        { pais: 'Lebanon', codigo: '961', flag: 'https://flagcdn.com/w20/lb.png' },
        { pais: 'Lesotho', codigo: '266', flag: 'https://flagcdn.com/w20/ls.png' },
        { pais: 'Liberia', codigo: '231', flag: 'https://flagcdn.com/w20/lr.png' },
        { pais: 'Libya', codigo: '218', flag: 'https://flagcdn.com/w20/ly.png' },
        {
           pais: 'Liechtenstein',
           codigo: '423',
           flag: 'https://flagcdn.com/w20/li.png',
        },
        {
           pais: 'Lithuania',
           codigo: '370',
           flag: 'https://flagcdn.com/w20/lt.png',
        },
        {
           pais: 'Luxembourg',
           codigo: '352',
           flag: 'https://flagcdn.com/w20/lu.png',
        },
        {
           pais: 'Madagascar',
           codigo: '261',
           flag: 'https://flagcdn.com/w20/mg.png',
        },
        { pais: 'Malawi', codigo: '265', flag: 'https://flagcdn.com/w20/mw.png' },
        { pais: 'Malaysia', codigo: '60', flag: 'https://flagcdn.com/w20/my.png' },
        { pais: 'Maldives', codigo: '960', flag: 'https://flagcdn.com/w20/mv.png' },
        { pais: 'Mali', codigo: '223', flag: 'https://flagcdn.com/w20/ml.png' },
        { pais: 'Malta', codigo: '356', flag: 'https://flagcdn.com/w20/mt.png' },
        {
           pais: 'Marshall Islands',
           codigo: '692',
           flag: 'https://flagcdn.com/w20/mh.png',
        },
        {
           pais: 'Mauritania',
           codigo: '222',
           flag: 'https://flagcdn.com/w20/mr.png',
        },
        {
           pais: 'Mauritius',
           codigo: '230',
           flag: 'https://flagcdn.com/w20/mu.png',
        },
        { pais: 'Mexico', codigo: '52', flag: 'https://flagcdn.com/w20/mx.png' },
        {
           pais: 'Micronesia',
           codigo: '691',
           flag: 'https://flagcdn.com/w20/fm.png',
        },
        { pais: 'Moldova', codigo: '373', flag: 'https://flagcdn.com/w20/md.png' },
        { pais: 'Monaco', codigo: '377', flag: 'https://flagcdn.com/w20/mc.png' },
        { pais: 'Mongolia', codigo: '976', flag: 'https://flagcdn.com/w20/mn.png' },
        {
           pais: 'Montenegro',
           codigo: '382',
           flag: 'https://flagcdn.com/w20/me.png',
        },
        { pais: 'Morocco', codigo: '212', flag: 'https://flagcdn.com/w20/ma.png' },
        {
           pais: 'Mozambique',
           codigo: '258',
           flag: 'https://flagcdn.com/w20/mz.png',
        },
        { pais: 'Myanmar', codigo: '95', flag: 'https://flagcdn.com/w20/mm.png' },
        { pais: 'Namibia', codigo: '264', flag: 'https://flagcdn.com/w20/na.png' },
        { pais: 'Nauru', codigo: '674', flag: 'https://flagcdn.com/w20/nr.png' },
        { pais: 'Nepal', codigo: '977', flag: 'https://flagcdn.com/w20/np.png' },
        {
           pais: 'Netherlands',
           codigo: '31',
           flag: 'https://flagcdn.com/w20/nl.png',
        },
        {
           pais: 'New Zealand',
           codigo: '64',
           flag: 'https://flagcdn.com/w20/nz.png',
        },
        {
           pais: 'Nicaragua',
           codigo: '505',
           flag: 'https://flagcdn.com/w20/ni.png',
        },
        { pais: 'Niger', codigo: '227', flag: 'https://flagcdn.com/w20/ne.png' },
        { pais: 'Nigeria', codigo: '234', flag: 'https://flagcdn.com/w20/ng.png' },
        {
           pais: 'North Korea',
           codigo: '850',
           flag: 'https://flagcdn.com/w20/kp.png',
        },
        {
           pais: 'North Macedonia',
           codigo: '389',
           flag: 'https://flagcdn.com/w20/mk.png',
        },
        { pais: 'Norway', codigo: '47', flag: 'https://flagcdn.com/w20/no.png' },
        { pais: 'Oman', codigo: '968', flag: 'https://flagcdn.com/w20/om.png' },
        { pais: 'Pakistan', codigo: '92', flag: 'https://flagcdn.com/w20/pk.png' },
        { pais: 'Palau', codigo: '680', flag: 'https://flagcdn.com/w20/pw.png' },
        { pais: 'Panama', codigo: '507', flag: 'https://flagcdn.com/w20/pa.png' },
        {
           pais: 'Papua New Guinea',
           codigo: '675',
           flag: 'https://flagcdn.com/w20/pg.png',
        },
        { pais: 'Paraguay', codigo: '595', flag: 'https://flagcdn.com/w20/py.png' },
        { pais: 'Peru', codigo: '51', flag: 'https://flagcdn.com/w20/pe.png' },
        {
           pais: 'Philippines',
           codigo: '63',
           flag: 'https://flagcdn.com/w20/ph.png',
        },
        { pais: 'Poland', codigo: '48', flag: 'https://flagcdn.com/w20/pl.png' },
        { pais: 'Portugal', codigo: '351', flag: 'https://flagcdn.com/w20/pt.png' },
        { pais: 'Qatar', codigo: '974', flag: 'https://flagcdn.com/w20/qa.png' },
        { pais: 'Romania', codigo: '40', flag: 'https://flagcdn.com/w20/ro.png' },
        { pais: 'Russia', codigo: '7', flag: 'https://flagcdn.com/w20/ru.png' },
        { pais: 'Rwanda', codigo: '250', flag: 'https://flagcdn.com/w20/rw.png' },
        {
           pais: 'Saint Kitts and Nevis',
           codigo: '1-869',
           flag: 'https://flagcdn.com/w20/kn.png',
        },
        {
           pais: 'Saint Lucia',
           codigo: '1-758',
           flag: 'https://flagcdn.com/w20/lc.png',
        },
        {
           pais: 'Saint Vincent and the Grenadines',
           codigo: '1-784',
           flag: 'https://flagcdn.com/w20/vc.png',
        },
        { pais: 'Samoa', codigo: '685', flag: 'https://flagcdn.com/w20/ws.png' },
        {
           pais: 'San Marino',
           codigo: '378',
           flag: 'https://flagcdn.com/w20/sm.png',
        },
        {
           pais: 'Saudi Arabia',
           codigo: '966',
           flag: 'https://flagcdn.com/w20/sa.png',
        },
        { pais: 'Senegal', codigo: '221', flag: 'https://flagcdn.com/w20/sn.png' },
        { pais: 'Serbia', codigo: '381', flag: 'https://flagcdn.com/w20/rs.png' },
        {
           pais: 'Seychelles',
           codigo: '248',
           flag: 'https://flagcdn.com/w20/sc.png',
        },
        {
           pais: 'Sierra Leone',
           codigo: '232',
           flag: 'https://flagcdn.com/w20/sl.png',
        },
        { pais: 'Singapore', codigo: '65', flag: 'https://flagcdn.com/w20/sg.png' },
        { pais: 'Slovakia', codigo: '421', flag: 'https://flagcdn.com/w20/sk.png' },
        { pais: 'Slovenia', codigo: '386', flag: 'https://flagcdn.com/w20/si.png' },
        {
           pais: 'Solomon Islands',
           codigo: '677',
           flag: 'https://flagcdn.com/w20/sb.png',
        },
        { pais: 'Somalia', codigo: '252', flag: 'https://flagcdn.com/w20/so.png' },
        {
           pais: 'South Africa',
           codigo: '27',
           flag: 'https://flagcdn.com/w20/za.png',
        },
        {
           pais: 'South Korea',
           codigo: '82',
           flag: 'https://flagcdn.com/w20/kr.png',
        },
        {
           pais: 'South Sudan',
           codigo: '211',
           flag: 'https://flagcdn.com/w20/ss.png',
        },
        { pais: 'Spain', codigo: '34', flag: 'https://flagcdn.com/w20/es.png' },
        { pais: 'Sri Lanka', codigo: '94', flag: 'https://flagcdn.com/w20/lk.png' },
        { pais: 'Sudan', codigo: '249', flag: 'https://flagcdn.com/w20/sd.png' },
        { pais: 'Suriname', codigo: '597', flag: 'https://flagcdn.com/w20/sr.png' },
        { pais: 'Sweden', codigo: '46', flag: 'https://flagcdn.com/w20/se.png' },
        {
           pais: 'Switzerland',
           codigo: '41',
           flag: 'https://flagcdn.com/w20/ch.png',
        },
        { pais: 'Syria', codigo: '963', flag: 'https://flagcdn.com/w20/sy.png' },
        { pais: 'Taiwan', codigo: '886', flag: 'https://flagcdn.com/w20/tw.png' },
        {
           pais: 'Tajikistan',
           codigo: '992',
           flag: 'https://flagcdn.com/w20/tj.png',
        },
        { pais: 'Tanzania', codigo: '255', flag: 'https://flagcdn.com/w20/tz.png' },
        { pais: 'Thailand', codigo: '66', flag: 'https://flagcdn.com/w20/th.png' },
        {
           pais: 'Timor-Leste',
           codigo: '670',
           flag: 'https://flagcdn.com/w20/tl.png',
        },
        { pais: 'Togo', codigo: '228', flag: 'https://flagcdn.com/w20/tg.png' },
        { pais: 'Tonga', codigo: '676', flag: 'https://flagcdn.com/w20/to.png' },
        {
           pais: 'Trinidad and Tobago',
           codigo: '1-868',
           flag: 'https://flagcdn.com/w20/tt.png',
        },
        { pais: 'Tunisia', codigo: '216', flag: 'https://flagcdn.com/w20/tn.png' },
        { pais: 'Turkey', codigo: '90', flag: 'https://flagcdn.com/w20/tr.png' },
        {
           pais: 'Turkmenistan',
           codigo: '993',
           flag: 'https://flagcdn.com/w20/tm.png',
        },
        { pais: 'Tuvalu', codigo: '688', flag: 'https://flagcdn.com/w20/tv.png' },
        { pais: 'Uganda', codigo: '256', flag: 'https://flagcdn.com/w20/ug.png' },
        { pais: 'Ukraine', codigo: '380', flag: 'https://flagcdn.com/w20/ua.png' },
        {
           pais: 'United Arab Emirates',
           codigo: '971',
           flag: 'https://flagcdn.com/w20/ae.png',
        },
        {
           pais: 'United Kingdom',
           codigo: '44',
           flag: 'https://flagcdn.com/w20/gb.png',
        },
        { pais: 'Uruguay', codigo: '598', flag: 'https://flagcdn.com/w20/uy.png' },
        {
           pais: 'Uzbekistan',
           codigo: '998',
           flag: 'https://flagcdn.com/w20/uz.png',
        },
        { pais: 'Vanuatu', codigo: '678', flag: 'https://flagcdn.com/w20/vu.png' },
        {
           pais: 'Vatican City',
           codigo: '379',
           flag: 'https://flagcdn.com/w20/va.png',
        },
        { pais: 'Venezuela', codigo: '58', flag: 'https://flagcdn.com/w20/ve.png' },
        { pais: 'Vietnam', codigo: '84', flag: 'https://flagcdn.com/w20/vn.png' },
        { pais: 'Yemen', codigo: '967', flag: 'https://flagcdn.com/w20/ye.png' },
        { pais: 'Zambia', codigo: '260', flag: 'https://flagcdn.com/w20/zm.png' },
        { pais: 'Zimbabwe', codigo: '263', flag: 'https://flagcdn.com/w20/zw.png' },
    ];


    var arrCompania = [];
    var arrCompaniaBackend = [];

    $(document).ready(function () {

        const tomarContactos = $('.tener_compania').text();
        //console.log(tomarContactos);

        try {
            
            if(!isEmpty(tomarContactos))
            {
                let parsearContacto = JSON.parse(tomarContactos);

                if (Array.isArray(parsearContacto)) {
                    arrCompania = parsearContacto || [];

                    //console.log("arrCompania");
                    //console.log(arrCompania);
                }
            }

        } catch (error) {
            console.error('Error al parsear los compania:', error);
        }

        var compania_ = $('.compania');
        compania_.select2();

        let options = '';

        for (const pais of paisesConCodigos) {
            options += '<option value="' + pais.codigo + '" data-icon="' + pais.flag + '">' + pais.pais + ' (+' + pais.codigo + ')</option>';
        }

        // Formatear la opción para mostrar la bandera y el nombre del país
        function formatOption(option) {
            if (!option.id) {
                return option.text; // Placeholder o texto por defecto
            }
            const $option = $(
                '<span>' +
                '<img src="' + option.element.dataset.icon + '" class="img-flag" style="width: 20px; margin-right: 8px; vertical-align: middle;" />' +
                option.text +
                '</span>'
            );
            return $option;
        }

        // Función para permitir búsqueda por nombre del país
        function matchCustom(params, data) {
           if (!params.term || params.term.trim() === '') {
              return data;
           }
           const term = params.term.toLowerCase();
           if (data.text.toLowerCase().indexOf(term) > -1) {
              return data;
           }
           return null;
        }

        $('#codigo_pais').html(options);

        $('#codigo_pais').select2({
        templateResult: formatOption,
        templateSelection: formatOption,
        matcher: matchCustom,
        dropdownParent: $('#codigo_pais').parent() // Asegura que el dropdown se alinee con el contenedor padre
        }).on('select2:open', function() {
        $('.select2-container--open .select2-dropdown').css('z-index', '1060'); // Ajusta este valor según el z-index del modal
        });

 
        $(".progress").hide();
        $("#emsg").hide();
        var _url = '{$_url}';
 

        $('#tags').select2({
            tags: true,
            tokenSeparators: [','],
            theme: "bootstrap"
        });

        var $cid = $('#cid');

        $cid.select2();

        $country = $("#country");

        $country.select2();

        $nationality = $("#nationality");

        $nationality.select2();

            //
        $("#submit").click(function (e) {
            e.preventDefault();

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

            if(isEmpty(nationality)){

                var body = $("html, body");
                body.animate({ scrollTop:0 }, '1000', 'swing');
                $("#emsgbody").html('Please select a nationality');
                $("#emsg").show("slow");
                return;
            }

            let valor_grupo =  $(".tener_grupo_seleccionado").val();
 
            if(isEmpty(valor_grupo)){

                var body = $("html, body");
                body.animate({ scrollTop:0 }, '1000', 'swing');
                $("#emsgbody").html('Please select a group');
                $("#emsg").show("slow");
                return;
            }

            let codigo_pais =  $("#codigo_pais").val();
 
            if(isEmpty(codigo_pais)){

                var body = $("html, body");
                body.animate({ scrollTop:0 }, '1000', 'swing');
                $("#emsgbody").html('Select a phone area');
                $("#emsg").show("slow");
                return;
            }

            if(valor_grupo == 0 || valor_grupo == "0")
            {
                var body = $("html, body");
                body.animate({ scrollTop:0 }, '1000', 'swing');
                $("#emsgbody").html('Please select a group');
                $("#emsg").show("slow");
                return;
            }

            var formData = $("#rform").serializeArray();
            formData.push({
                name: "companies",
                value: JSON.stringify( arrCompaniaBackend )
            });

            //console.log("valor_grupo");
            //console.log($( "#rform" ).serialize());
            //console.log("formData");
            //console.log($.param(formData));
            //return;

            $('#ibox_form').block({ message:block_msg });
            $.post(base_url + 'contacts/add-post/', $.param(formData))
            //$.post(base_url + 'contacts/add-post/', $( "#rform" ).serialize())
            .done(function (data) {

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

                var sbutton = $("#submit");
                if ($.isNumeric(data)) {

                    window.location = base_url + 'contacts/view/' + data;
                }
                else {
                    $('#ibox_form').unblock();
                    var body = $("html, body");
                    body.animate({ scrollTop:0 }, '1000', 'swing');
                    $("#emsgbody").html(data);
                    $("#emsg").show("slow");
                }
            });
        });

 
        {if $config['show_business_number'] eq '1'}


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

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

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

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

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



        function getBusinessDetails() {

            if($cid.val() === '0'){
                   // $business_number.val('');
                return;
            }

            $.getJSON( base_url + "contacts/get_company_details/" +  $cid.val(), function( data ) {

                console.log(data);

                if(data.success === false){

                }
                else{

                    $business_number.val(data.business_number);

                    $address.val(data.address1);

                    $city.val(data.city);

                    $state.val(data.state);

                    $zip.val(data.zip);

                    $country.val(data.country).trigger('change');

                }

            });
        }

        getBusinessDetails();


        $cid.change(function () {

            getBusinessDetails();


        });


        {/if}


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

            e.preventDefault();

            (async () => {

                const { value: group_name } = await Swal.fire({
                    title: '{$_L['Add New Group']}',
                    input: 'text',
                    inputLabel: '{$_L['Group Name']}',
                    inputPlaceholder: '{$_L['Group Name']}',
                })

                if (group_name) {
                    $.post(  _url + "contacts/add_group/", { group_name: group_name })
                    .done(function( data ) {

                        if ($.isNumeric(data)) {

                            window.location = _url + 'contacts/add/customer/' + data + '/' + $cid.val();

                        }

                        else {
                            Swal.fire({
                                title: '{__('Error')}',
                                text: data,
                                type: 'error',
                                confirmButtonText: '{$_L['Close']}'
                            })
                        }

                    });
                }

            })()


        });

        $(".guardar_tabla_compania").click(function(e){

            
            const selectedValue = $('#compania').val();
            const selectedText = $('#compania option:selected').text();

            // Verificar que se haya seleccionado una opción válida
            if (!isEmpty(selectedValue)) {
                //console.log('Valor:', selectedValue);
                //console.log('Texto:', selectedText);

                const findCompany = arrCompania.find((data) => data.id == selectedValue  )

                //console.log(arrCompania)
               
                if(findCompany)
                {
                    let existeData = arrCompaniaBackend.find((data) => data.idCompany == selectedValue  );

                    if(existeData)
                    {
                        toastr.error(
                            "The company has already been added to the table",
                        );   
                        return;
                    }

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

                    const informacion = {
                        UUID:UUID,
                        UUID_ENC:UUID_ENC,
                        idCompany: selectedValue,
                        nameCompany: findCompany.company_name,
                    };

                    arrCompaniaBackend.push(informacion);

                    $(".tbody_envios_identificador").html(tabla_html_identificador(arrCompaniaBackend));
                    eventosTablaIdentificador();

                    $('#compania').val("").trigger("change");

                    //console.log("informacion");
                    //console.log(informacion);
                }

               return;
            }

            toastr.error(
                "The company field is required",
                "Select a company",
            );

        });

        function tabla_html_identificador(arreglo) {
            let html = "";
            
            arreglo.forEach(function (element) {

                let {
                    UUID,
                    UUID_ENC,
                    idCompany,
                    nameCompany,
                } = element;
        
                
               

                html +=
                    "<tr>" +
                    "<td class='centrar'>" + nameCompany + "</td>" +
         
                    "<td class='centrar'>" +
                    "<div class='row'>" +
                    "<div class='col-12 centrar-botones'>" +
         
                    "<button class='btn btn-sm btn-eliminar waves-effect waves-themed' data-id='" + UUID_ENC + "'>" +
                    "<i class='fas fa-trash tamano-icono' aria-hidden='true'></i>" +
                    "</button>" +
                    "</div>" +
                    "</div>" +
                    "</td>" +

                    "</tr>";
            });

            return html;
        }

        function eventosTablaIdentificador()
        {
            $('.btn-eliminar').off('click');

            $('.btn-eliminar').on('click', function() {
                var dataId = $(this).data('id');
                console.log('ID de la referencia:', dataId);
        
                Swal.fire({
                    title: "You are sure?",
                    text: "Are you sure you want to delete a record?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Delete',
                    cancelButtonText: 'Close'
                }).then((result) => {
                    if (result.isConfirmed) {
                        console.log('producto eliminado');     
                        
                        arrCompaniaBackend = arrCompaniaBackend.filter((data) => data.UUID_ENC != dataId);

                        $(".tbody_envios_identificador").html(tabla_html_identificador(arrCompaniaBackend));
                        eventosTablaIdentificador();

                    }
                });
 
            });
            

        }

         

        function generatePassword() {
            let length = 10,
            charset = "abcdefghijklmnopqrstuvwxyz@#ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            retVal = "";
            for (let i = 0, n = charset.length; i < length; ++i) {
                retVal += charset.charAt(Math.floor(Math.random() * n));
            }

                // Check if password contains at least one number
            if (!/\d/.test(retVal)) {
                retVal = generatePassword();
            }

            return retVal;

        }

        const generate_password = document.getElementById('generate_password');
        generate_password.addEventListener('click', function (e) {
            e.preventDefault();
            const password = generatePassword();
            document.getElementById('password').value = password;
            document.getElementById('cpassword').value = password;

                //Show password
            document.getElementById('password').type = 'text';
            document.getElementById('cpassword').type = 'text';

        });

    });

 

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();
    let host_modulo_api_direccion_smarty =  $(".host_modulo_api_direccion_smarty").val();
    let referer_modulo_api_direccion_smarty =  $(".referer_modulo_api_direccion_smarty").val();
 
    //console.log("url_modulo_api_direccion_smarty");
    //console.log(url_modulo_api_direccion_smarty);
    //console.log("key_modulo_api_direccion_smarty");
    //console.log(key_modulo_api_direccion_smarty);
    //console.log("host_modulo_api_direccion_smarty");
    //console.log(host_modulo_api_direccion_smarty);
    //console.log("referer_modulo_api_direccion_smarty");
    //console.log(referer_modulo_api_direccion_smarty);
 
    if(isEmpty(url_modulo_api_direccion_smarty) == true || 
        isEmpty(key_modulo_api_direccion_smarty) == true ||  
        isEmpty(host_modulo_api_direccion_smarty) == true || isEmpty(referer_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"
        "Host": host_modulo_api_direccion_smarty,
        "Referer": referer_modulo_api_direccion_smarty
    },
};

$('#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>
{/block}


