{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;
    }    

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

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

         <input type="text" readonly hidden  class="form-control tener_url_base" value="{$url_base}">
         <input type="text" readonly hidden  class="form-control tener_id" value="{$data["id"]}">
         <input type="text" readonly hidden  class="form-control tener_status" value="{$data["status"]}">
         <input type="text" readonly hidden  class="form-control tener_zona_horaria" value="{$data["zona_horaria"]}">

         <input type="text" readonly hidden  class="form-control tener_existe_cuenta_whatsapp" value="{$existe_cuenta_whatsapp}">
         
 
        <div class="panel">
            <div class="panel-hdr">
                <h2><span></span>Update Config Whatsapp/SMS</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">

                                {* configuracion general*}
                                <div class="col-md-12 col-sm-12 p-0">
                                    <span class="h3">Config. General</span>
                                    <hr>
                                </div>

                                <div  class="col-md-12 col-sm-12">
                                
                                    <div class="mb-3 row">
                                        <label for="identificador" class="col-sm-3"><span class="h6">Identifier</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="identificador" name="identificador" class="form-control tener_identificador" autofocus value="{$data["identifier"]}" >
                                        </div>
                                    </div>
                                
                                </div>


                                {* fin configuracion general*}
                   

                                <div class="col-md-6 col-sm-6 p-0">
                                    {*
                                      <input class="form-check-input habilitarConfigWS me-2 h4" id="habilitarConfigWs" type="checkbox"  value="" {if $data["enable_whatsapp"] eq '1'}checked{/if} />
                                      <span class="h4" for="habilitarConfigWs">Enable and config Whatsapp</span>
                                    *}
                                   
                                    <div class="form-check" style="margin-left: 7px;">
                                        <input class="form-check-input habilitarConfigWS  h4" id="habilitarConfigWs" type="checkbox"  value="" {if $data["enable_whatsapp"] eq '1'}checked{/if}  {if $existe_cuenta_whatsapp eq false} disabled{/if}  />
                                        <label class="form-check-label h4" for="habilitarConfigWs"><span class="h6">Enable Whatsapp Settings</span></label>
                                    </div>
 
                                </div>


                                {if $existe_cuenta_whatsapp eq false}
                                
                                    <div class="col-md-6 col-sm-6 mb-3 quitar_btn_registro_insertado" style="display:flex; justify-content: end;"  >
                                        <button type="button" class="loglaunchWhatsAppSignup" style="background-color: #1877f2; border: 0; border-radius: 4px; color: #fff; font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: bold; height: 40px; padding: 0 24px;">
                                            Login for WhatsApp Business
                                        </button>
                                    </div>

                                {/if}

                                <div class="col-12">
                                    <hr style="margin-top: 0px; ">
                                </div>
 
                                {*WS*}
                                <div class="col-md-6 col-sm-12 ocultar_opcion_whatsapp" style="display:none;">

                                    {*
                                    <div class="mb-3 row">
                                        <label for="identificador" class="col-sm-3"><span class="h6">Identifier</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="identificador" name="identificador" class="form-control tener_identificador" value="{$data["identifier"]}" autofocus>
                                        </div>
                                    </div>
                                    *}

                                    <div class="mb-3 row">
                                        <label for="phone_ws" class="col-sm-3"><span class="h6">Phone</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="phone_ws" name="phone_ws" class="form-control tener_phone_ws" value="{$data["phone"]}" autofocus disabled>
                                        </div>
                                    </div>

                                     
                                    <div class="mb-3 row" style="display:none;">
                                        <label for="whatsapp_business_account_identifier" class="col-sm-3"><span class="h6">Whatsapp Business Account</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="whatsapp_business_account_identifier" name="whatsapp_business_account_identifier" value="{$data["whatsapp_business_account_identifier"]}" class="form-control tener_whatsapp_business_account_identifier" disabled>
                                        </div>
                                    </div>

                                    <div class="mb-3 row" style="display:none;">
                                        <label for="app_Identifier" class="col-sm-3"><span class="h6">App Identifier</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="app_Identifier" name="app_Identifier" value="{$whatsApp_app_identifier}" class="form-control tener_app_Identifier" disabled>
                                        </div>
                                    </div>
 
                                     

 
                                </div>

                                <div class="col-md-6 col-sm-12 ocultar_opcion_whatsapp" style="display:none;">
                                    <div class="mb-3 row">
                                        <label for="version_ws" class="col-sm-3"><span class="h6">Version</span><span class="text-danger">*</span> </label>
                                        <div class="col-sm-9">
                                     
                                            <select id="version_ws" name="version_ws" class="form-control tener_version_ws" disabled>
                                                <option value="v19.0" {if $version_api_whatsapp == 'v19.0'}selected{/if}>v19.0</option>
                                                <option value="v20.0" {if $version_api_whatsapp == 'v20.0'}selected{/if}>v20.0</option>
                                                <option value="v21.0" {if $version_api_whatsapp == 'v21.0'}selected{/if}>v21.0</option>
                                                <option value="v22.0" {if $version_api_whatsapp == 'v22.0'}selected{/if}>v22.0</option>
                                            </select>
                                           

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

                                <div class="col-md-6 col-sm-12 ocultar_opcion_whatsapp" style="display:none;">
                                
                                </div>

                                <div class="col-md-6 col-sm-12 ocultar_opcion_whatsapp"  style="display:none;">
                                     <a class="btn btn-primary btn-sm" style="float: inline-end; " id="crearLinkPago" >Manage payment method</a>
                                </div>


                                <div class="col-md-6 col-sm-12" style="display:none;">
                                    <div class="mb-3 row">
                                        <label for="token_ws" class="col-sm-3"><span class="h6">Token</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="token_ws" name="token_ws" value="{$data["token"]}" class="form-control tener_token_ws" autofocus disabled>
                                        </div>
                                    </div>

  
                                    <div class="mb-3 row">
                                        <label for="phone_identifier" class="col-sm-3"><span class="h6">Phone Identifier</span><span class="text-danger">*</span> </label>
                                        <div class="col-sm-9">
                                            <input type="text" id="phone_identifier" name="phone_identifier" value="{$data["phone_identifier"]}" class="form-control tener_phone_identifier" disabled>
                                        </div>
                                    </div>


                                     <div class="mb-3 row">
                                        <label for="secret_key_app" class="col-sm-3"><span class="h6">Secret key of the app</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="secret_key_app" name="secret_key_app" class="form-control tener_secret_key_app"  disabled value="{$whatsApp_app_secret_key}"  disabled>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="whatsapp_app_id_configuration" class="col-sm-3"><span class="h6">Configuration of the inserted record app</span><span class="text-danger">*</span> </label>
                                        <div class="col-sm-9">
                                            <input type="text" id="whatsapp_app_id_configuration" name="whatsapp_app_id_configuration" class="form-control tener_whatsapp_app_id_configuration" disabled value="{$whatsapp_app_id_configuration}" disabled>
                                        </div>
                                    </div>
 

                                    
                                </div>

                                {*Configuracion de SMS*}
                               <div class="col-md-12 col-sm-12 p-0">

                                    {*

                                    <input type="checkbox" class="form-check-input me-2 habilitarConfigSMS h4" id="habilitarConfigSMS" name="customer" value="" {if $data["enable_twilio"] eq '1'}checked{/if}>

                                    <label class="form-check-label h4" for="habilitarConfigSMS">Enable and config SMS</label>
                                    *}

                                    <div class="form-check" style="margin-left: 7px;">
                                        <input class="form-check-input habilitarConfigSMS  h4" id="habilitarConfigSMS" type="checkbox"  value="" {if $data["enable_twilio"] eq '1'}checked{/if}    />
                                        <label class="form-check-label h4" for="habilitarConfigSMS"><span class="h6">Enable Whatsapp Settings</span></label>
                                    </div>

                                    
                                    <hr>
                                </div>

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

                                    <div class="mb-3 row">
                                        <label for="sms_account_sid" class="col-sm-3"><span class="h6">Account Sid</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="sms_account_sid" name="sms_account_sid" value="{$data["sms_account_sid"]}" class="form-control tener_sms_account_sid" autofocus>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <label for="sms_phone_number" class="col-sm-3"><span class="h6">Phone Number</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="sms_phone_number" name="sms_phone_number"  value="{$data["sms_phone_number"]}" class="form-control tener_sms_phone_number" autofocus>
                                        </div>
                                    </div>

 

 
                                </div>


                                <div class="col-md-6 col-sm-12">
                                    <div class="mb-3 row">
                                        <label for="sms_auth_token" class="col-sm-3"><span class="h6">Auth Token</span><span class="text-danger">*</span></label>
                                        <div class="col-sm-9">
                                            <input type="text" id="sms_auth_token" name="sms_auth_token" value="{$data["sms_auth_token"]}" class="form-control tener_sms_auth_token" autofocus>
                                        </div>
                                    </div>

  
                                    <div class="mb-3 row">
                                        <label for="version_sms" class="col-sm-3"><span class="h6">Version</span><span class="text-danger"></span> </label>
                                        <div class="col-sm-9">
                                            <input type="text" id="version_sms" name="version_sms" value="{$data["version_sms"]}" class="form-control tener_version_sms">
                                        </div>
                                    </div>

    
                                </div>

                                {*Configuracion de zona horaria*}
                               <div class="col-md-12 col-sm-12 p-0">
                                    <span class="h3">Config. Time Zone</span>
                                    <hr>
                                </div>

                                <div class="mb-3 row">
                                    <label for="TimeZone" class="col-sm-3">
                                        <span class="h6">Time Zone</span>
                                        <span class="text-danger">*</span>
                                    </label>
                                    <div class="col-sm-9">
                                        <select id="TimeZone" name="TimeZone" class="form-select tenerTimeZone"  >
                                            <option value="" selected disabled>Select an option</option>
                                            <option value="America/Adak">America/Adak</option>
                                            <option value="America/Anchorage">America/Anchorage</option>
                                            <option value="America/Anguilla">America/Anguilla</option>
                                            <option value="America/Antigua">America/Antigua</option>
                                            <option value="America/Araguaina">America/Araguaina</option>
                                            <option value="America/Argentina/Buenos_Aires">America/Argentina/Buenos_Aires</option>
                                            <option value="America/Argentina/Catamarca">America/Argentina/Catamarca</option>
                                            <option value="America/Argentina/Cordoba">America/Argentina/Cordoba</option>
                                            <option value="America/Argentina/Jujuy">America/Argentina/Jujuy</option>
                                            <option value="America/Argentina/La_Rioja">America/Argentina/La_Rioja</option>
                                            <option value="America/Argentina/Mendoza">America/Argentina/Mendoza</option>
                                            <option value="America/Argentina/Rio_Gallegos">America/Argentina/Rio_Gallegos</option>
                                            <option value="America/Argentina/Salta">America/Argentina/Salta</option>
                                            <option value="America/Argentina/San_Juan">America/Argentina/San_Juan</option>
                                            <option value="America/Argentina/San_Luis">America/Argentina/San_Luis</option>
                                            <option value="America/Argentina/Tucuman">America/Argentina/Tucuman</option>
                                            <option value="America/Argentina/Ushuaia">America/Argentina/Ushuaia</option>
                                            <option value="America/Aruba">America/Aruba</option>
                                            <option value="America/Asuncion">America/Asuncion</option>
                                            <option value="America/Atikokan">America/Atikokan</option>
                                            <option value="America/Bahia">America/Bahia</option>
                                            <option value="America/Bahia_Banderas">America/Bahia_Banderas</option>
                                            <option value="America/Barbados">America/Barbados</option>
                                            <option value="America/Belem">America/Belem</option>
                                            <option value="America/Belize">America/Belize</option>
                                            <option value="America/Blanc-Sablon">America/Blanc-Sablon</option>
                                            <option value="America/Boa_Vista">America/Boa_Vista</option>
                                            <option value="America/Bogota">America/Bogota</option>
                                            <option value="America/Boise">America/Boise</option>
                                            <option value="America/Cambridge_Bay">America/Cambridge_Bay</option>
                                            <option value="America/Campo_Grande">America/Campo_Grande</option>
                                            <option value="America/Cancun">America/Cancun</option>
                                            <option value="America/Caracas">America/Caracas</option>
                                            <option value="America/Cayenne">America/Cayenne</option>
                                            <option value="America/Cayman">America/Cayman</option>
                                            <option value="America/Chicago">America/Chicago</option>
                                            <option value="America/Chihuahua">America/Chihuahua</option>
                                            <option value="America/Costa_Rica">America/Costa_Rica</option>
                                            <option value="America/Creston">America/Creston</option>
                                            <option value="America/Cuiaba">America/Cuiaba</option>
                                            <option value="America/Curacao">America/Curacao</option>
                                            <option value="America/Danmarkshavn">America/Danmarkshavn</option>
                                            <option value="America/Dawson">America/Dawson</option>
                                            <option value="America/Dawson_Creek">America/Dawson_Creek</option>
                                            <option value="America/Denver">America/Denver</option>
                                            <option value="America/Detroit">America/Detroit</option>
                                            <option value="America/Dominica">America/Dominica</option>
                                            <option value="America/Edmonton">America/Edmonton</option>
                                            <option value="America/Eirunepe">America/Eirunepe</option>
                                            <option value="America/El_Salvador">America/El_Salvador</option>
                                            <option value="America/Fort_Nelson">America/Fort_Nelson</option>
                                            <option value="America/Fortaleza">America/Fortaleza</option>
                                            <option value="America/Glace_Bay">America/Glace_Bay</option>
                                            <option value="America/Goose_Bay">America/Goose_Bay</option>
                                            <option value="America/Grand_Turk">America/Grand_Turk</option>
                                            <option value="America/Grenada">America/Grenada</option>
                                            <option value="America/Guadeloupe">America/Guadeloupe</option>
                                            <option value="America/Guatemala">America/Guatemala</option>
                                            <option value="America/Guayaquil">America/Guayaquil</option>
                                            <option value="America/Guyana">America/Guyana</option>
                                            <option value="America/Halifax">America/Halifax</option>
                                            <option value="America/Havana">America/Havana</option>
                                            <option value="America/Hermosillo">America/Hermosillo</option>
                                            <option value="America/Indiana/Indianapolis">America/Indiana/Indianapolis</option>
                                            <option value="America/Indiana/Knox">America/Indiana/Knox</option>
                                            <option value="America/Indiana/Marengo">America/Indiana/Marengo</option>
                                            <option value="America/Indiana/Petersburg">America/Indiana/Petersburg</option>
                                            <option value="America/Indiana/Tell_City">America/Indiana/Tell_City</option>
                                            <option value="America/Indiana/Vevay">America/Indiana/Vevay</option>
                                            <option value="America/Indiana/Vincennes">America/Indiana/Vincennes</option>
                                            <option value="America/Indiana/Winamac">America/Indiana/Winamac</option>
                                            <option value="America/Inuvik">America/Inuvik</option>
                                            <option value="America/Iqaluit">America/Iqaluit</option>
                                            <option value="America/Jamaica">America/Jamaica</option>
                                            <option value="America/Juneau">America/Juneau</option>
                                            <option value="America/Kentucky/Louisville">America/Kentucky/Louisville</option>
                                            <option value="America/Kentucky/Monticello">America/Kentucky/Monticello</option>
                                            <option value="America/Kralendijk">America/Kralendijk</option>
                                            <option value="America/La_Paz">America/La_Paz</option>
                                            <option value="America/Lima">America/Lima</option>
                                            <option value="America/Los_Angeles">America/Los_Angeles</option>
                                            <option value="America/Lower_Princes">America/Lower_Princes</option>
                                            <option value="America/Maceio">America/Maceio</option>
                                            <option value="America/Managua">America/Managua</option>
                                            <option value="America/Manaus">America/Manaus</option>
                                            <option value="America/Marigot">America/Marigot</option>
                                            <option value="America/Martinique">America/Martinique</option>
                                            <option value="America/Matamoros">America/Matamoros</option>
                                            <option value="America/Mazatlan">America/Mazatlan</option>
                                            <option value="America/Menominee">America/Menominee</option>
                                            <option value="America/Merida">America/Merida</option>
                                            <option value="America/Metlakatla">America/Metlakatla</option>
                                            <option value="America/Mexico_City">America/Mexico_City</option>
                                            <option value="America/Miquelon">America/Miquelon</option>
                                            <option value="America/Moncton">America/Moncton</option>
                                            <option value="America/Monterrey">America/Monterrey</option>
                                            <option value="America/Montevideo">America/Montevideo</option>
                                            <option value="America/Montserrat">America/Montserrat</option>
                                            <option value="America/Nassau">America/Nassau</option>
                                            <option value="America/New_York">America/New_York</option>
                                            <option value="America/Nipigon">America/Nipigon</option>
                                            <option value="America/Nome">America/Nome</option>
                                            <option value="America/Noronha">America/Noronha</option>
                                            <option value="America/North_Dakota/Beulah">America/North_Dakota/Beulah</option>
                                            <option value="America/North_Dakota/Center">America/North_Dakota/Center</option>
                                            <option value="America/North_Dakota/New_Salem">America/North_Dakota/New_Salem</option>
                                            <option value="America/Nuuk">America/Nuuk</option>
                                            <option value="America/Ojinaga">America/Ojinaga</option>
                                            <option value="America/Panama">America/Panama</option>
                                            <option value="America/Pangnirtung">America/Pangnirtung</option>
                                            <option value="America/Paramaribo">America/Paramaribo</option>
                                            <option value="America/Phoenix">America/Phoenix</option>
                                            <option value="America/Port-au-Prince">America/Port-au-Prince</option>
                                            <option value="America/Port_of_Spain">America/Port_of_Spain</option>
                                            <option value="America/Porto_Velho">America/Porto_Velho</option>
                                            <option value="America/Puerto_Rico">America/Puerto_Rico</option>
                                            <option value="America/Punta_Arenas">America/Punta_Arenas</option>
                                            <option value="America/Rainy_River">America/Rainy_River</option>
                                            <option value="America/Rankin_Inlet">America/Rankin_Inlet</option>
                                            <option value="America/Recife">America/Recife</option>
                                            <option value="America/Regina">America/Regina</option>
                                            <option value="America/Resolute">America/Resolute</option>
                                            <option value="America/Rio_Branco">America/Rio_Branco</option>
                                            <option value="America/Santarem">America/Santarem</option>
                                            <option value="America/Santiago">America/Santiago</option>
                                            <option value="America/Santo_Domingo">America/Santo_Domingo</option>
                                            <option value="America/Sao_Paulo">America/Sao_Paulo</option>
                                            <option value="America/Scoresbysund">America/Scoresbysund</option>
                                            <option value="America/Sitka">America/Sitka</option>
                                            <option value="America/St_Barthelemy">America/St_Barthelemy</option>
                                            <option value="America/St_Johns">America/St_Johns</option>
                                            <option value="America/St_Kitts">America/St_Kitts</option>
                                            <option value="America/St_Lucia">America/St_Lucia</option>
                                            <option value="America/St_Thomas">America/St_Thomas</option>
                                            <option value="America/St_Vincent">America/St_Vincent</option>
                                            <option value="America/Swift_Current">America/Swift_Current</option>
                                            <option value="America/Tegucigalpa" >America/Tegucigalpa</option>
                                            <option value="America/Thule">America/Thule</option>
                                            <option value="America/Thunder_Bay">America/Thunder_Bay</option>
                                            <option value="America/Tijuana">America/Tijuana</option>
                                            <option value="America/Toronto">America/Toronto</option>
                                            <option value="America/Tortola">America/Tortola</option>
                                            <option value="America/Vancouver">America/Vancouver</option>
                                            <option value="America/Whitehorse">America/Whitehorse</option>
                                            <option value="America/Winnipeg">America/Winnipeg</option>
                                            <option value="America/Yakutat">America/Yakutat</option>
                                            <option value="America/Yellowknife">America/Yellowknife</option>
                                        </select>
                                    </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 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: 50%;
                         
                        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;
                                                            ">
                                    No actualice ni cierre la ventana. Espere el mensaje de confirmación. No actualice ni cierre la ventana.                    
                        </div>
                </div>

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




{/block}

{block name="script"}
<script>

     var url_base   = $(".tener_url_base").val();
     var tener_id   = $(".tener_id").val();

      
     var tener_status   = $(".tener_status").val();
     var tener_zona_horaria   = $(".tener_zona_horaria").val();

     var CODE = "";

     var app_Identifier   = $(".tener_app_Identifier").val();

     var version_ws       = $(".tener_version_ws").val();

     var existe_cuenta_whatsapp       = $(".tener_existe_cuenta_whatsapp").val();
     


     console.log("existe_cuenta_whatsapp");
     console.log(existe_cuenta_whatsapp);
     
     console.log("app_Identifier");
     console.log(app_Identifier);

     console.log("version_ws");
     console.log(version_ws);
 
    //window.fbAsyncInit = function() {
    //
    //        FB.init({
    //            appId            : app_Identifier,
    //            autoLogAppEvents : true,
    //            xfbml            : true,
    //            version          : version_ws
    //        });
    //};
      
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "https://connect.facebook.net/en_US/sdk.js#version="+version_ws+"&appId="+app_Identifier+"&xfbml=true&autoLogAppEvents=true";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));


    $(".tener_status").val(tener_status);
    $(".tenerTimeZone").val(tener_zona_horaria);
  
    var baseImagen = "";

    $(document).ready(function () {

        if(existe_cuenta_whatsapp ==1)
        {
            $(".quitar_btn_registro_insertado").css("display", "none");
            $(".habilitarConfigWS").prop("disabled", false);
            $(".habilitarConfigWS").prop('checked', true);

            $(".ocultar_opcion_whatsapp").css("display", "");
            $(".tener_version_ws").prop("disabled", true);

            let whatsapp_business_account_identifier = $(".tener_whatsapp_business_account_identifier").val();

            $("#crearLinkPago").attr("href", "https://business.facebook.com/billing_hub/accounts/details/?asset_id=" + whatsapp_business_account_identifier + "&account_type=whatsapp-business-account");
            $("#crearLinkPago").attr("target", "_blank");

             
        }

        let checkbox_ws = document.getElementById('habilitarConfigWs');

        console.log("checkbox_ws.checked");
        console.log(checkbox_ws.checked);

        if(checkbox_ws.checked == true){
            toggleFields(true);

            /*
            $('.loglaunchWhatsAppSignup').css({
                'background-color': '#1877f2',
            });

            $('.loglaunchWhatsAppSignup').prop('disabled', false);
            */

        }else{
            toggleFields(false);

            /*
            $('.loglaunchWhatsAppSignup').css({
                'background-color': '',
            });

            $('.loglaunchWhatsAppSignup').prop('disabled', true);
            */
        }

        let checkbox_tw = document.getElementById('habilitarConfigSMS');

        if(checkbox_tw.checked == true){
            toggleSmsFields(true);
        }else{
            toggleSmsFields(false);
        }


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

            let tener_identificador     = $(".tener_identificador").val();
            let tener_phone_ws          = $(".tener_phone_ws").val();
            let tener_whatsapp_business_account_identifier = $(".tener_whatsapp_business_account_identifier").val();
            let tener_version_ws       = $(".tener_version_ws").val();
            let tener_token_ws         = $(".tener_token_ws").val();
            let tener_phone_identifier = $(".tener_phone_identifier").val();
            let tener_app_Identifier   = $(".tener_app_Identifier").val();

            let tener_secret_key_app   = $(".tener_secret_key_app").val();
            let tener_whatsapp_app_id_configuration   = $(".tener_whatsapp_app_id_configuration").val();

            let checkbox_ws = document.getElementById('habilitarConfigWs');
            
            let tener_sms_account_sid   = $(".tener_sms_account_sid").val();
            let tener_sms_phone_number   = $(".tener_sms_phone_number").val();
            let tener_sms_auth_token   = $(".tener_sms_auth_token").val();
            let tener_version_sms   = $(".tener_version_sms").val();
            let checkbox_tw = document.getElementById('habilitarConfigSMS');

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

            if(checkbox_ws.checked == true)
            {
                if(isEmpty(tener_identificador) == true)
                {
                    toastr.error("!The identifier is required¡");
                    return;
                }     

                if(isEmpty(tener_phone_ws) == true)
                {
                    toastr.error("!WhatsApp phone is required¡");
                    return;
                }      

                if(isEmpty(tener_whatsapp_business_account_identifier) == true)
                {
                    toastr.error("!The WhatsApp Business Account is required¡");
                    return;
                }   

                if(isEmpty(tener_version_ws) == true)
                {
                    toastr.error("!The WhatsApp version is required¡");
                    return;
                }   

                if(isEmpty(tener_token_ws) == true)
                {
                    toastr.error("!WhatsApp token is required¡");
                    return;
                } 

                if(isEmpty(tener_phone_identifier) == true)
                {
                    toastr.error("!WhatsApp phone identifier is required¡");
                    return;
                } 

                if(isEmpty(tener_app_Identifier) == true)
                {
                    toastr.error("!The WhatsApp app identifier is required¡");
                    return;
                } 

                if(isEmpty(tener_secret_key_app) == true)
                {
                    toastr.error("!The WhatsApp Secret key of the app is required¡");
                    return;
                } 

                if(isEmpty(tener_whatsapp_app_id_configuration) == true)
                {
                    toastr.error("!WhatsApp app configuration is required¡");
                    return;
                } 
            }

        
            if(checkbox_tw.checked == true)
            {
                if(isEmpty(tener_sms_account_sid) == true)
                {
                    toastr.error("!The sms account sid is required¡");
                    return;
                } 

                if(isEmpty(tener_sms_phone_number) == true)
                {
                    toastr.error("!SMS phone number is required¡");
                    return;
                } 

                if(isEmpty(tener_sms_auth_token) == true)
                {
                    toastr.error("!SMS Auth token is required¡");
                    return;
                } 

                if(isEmpty(tener_version_sms) == true)
                {
                    toastr.error("!The SMS version is required¡");
                    return;
                } 
            }

            if(isEmpty(tenerTimeZone) == true)
            {
                toastr.error("!The time zone is required¡");
                return;
            }

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

            $(".bloqueo_v1").removeAttr("hidden");
            $(".bloqueo_v2").removeAttr("hidden");
            $(".bloqueo_v3").removeAttr("hidden");
            
            //console.log(base_url + 'parnerts/add-parnert-post/');
            //console.log($( "#rform" ).serialize());
 
            var informacionEnviar = {
                identificador:             tener_identificador,
                phone_ws:                  tener_phone_ws,
                whatsapp_business_account_identifier:          tener_whatsapp_business_account_identifier,
                tener_version_ws:          tener_version_ws,
                token_ws:                  tener_token_ws,
                phone_identifier:          tener_phone_identifier,
                app_Identifier:            tener_app_Identifier,

                secret_key_app:            tener_secret_key_app,
                whatsapp_app_id_configuration: tener_whatsapp_app_id_configuration,
                habilitarConfigWs:         checkbox_ws.checked,
                //
                sms_account_sid:            tener_sms_account_sid,
                sms_phone_number:           tener_sms_phone_number,
                sms_auth_token:             tener_sms_auth_token,
                version_sms:                tener_version_sms,
                status:                     1,
                id:                         tener_id,
                habilitarConfigSMS:         checkbox_tw.checked,
                tenerTimeZone:              tenerTimeZone,
                
            }; 
    
    
            console.log(JSON.stringify(informacionEnviar));
            //console.log("ahi un return aqui abajo");
            //return;

            //return;

            $.post(url_base + 'social/update-add-config-whatsapp-sms/', JSON.stringify(informacionEnviar)  ) //$( "#rform" ).serialize()
            .done(function (data) {
                 
                    //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);

                            Swal.fire({
                            title: info.title,
                            text: info.message,
                            icon: "success",
                            backdrop: true,           // Muestra el fondo oscuro
                            allowOutsideClick: false, // Evita que se cierre al hacer clic fuera
                            allowEscapeKey: false,    // Opcional: Evita que se cierre con la tecla Escape
                            }).then((result) => {
                                if (result.isConfirmed) {

                                    window.location = info.redirect;
                                    
                                    //console.log("El usuario hizo clic en OK");
                                    
                                }
                            });
 
                           //setTimeout(function() {
                           //     window.location = info.redirect;
                           // }, 1000);
                        }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(error);
                        $("#emsg").show("slow");
                    }
            });
        });


    });

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

    document.getElementById('habilitarConfigWs').addEventListener('change', function(event) {
        if (this.checked) {
            //console.log('El checkbox está seleccionado');
            toggleFields(true);

            /*
            $('.loglaunchWhatsAppSignup').css({
                'background-color': '#1877f2',
            });

            $('.loglaunchWhatsAppSignup').prop('disabled', false);
            */

        } else {
            toggleFields(false);

            /*

            $('.loglaunchWhatsAppSignup').css({
                'background-color': '',
            });

            $('.loglaunchWhatsAppSignup').prop('disabled', true);
        */

        }
    });

    document.getElementById('habilitarConfigSMS').addEventListener('change', function(event) {
        if (this.checked) {
            //console.log('El checkbox está seleccionado');
            toggleSmsFields(true);
        } else {
            toggleSmsFields(false);
        }
    });

    function toggleFields(enable) {
        // Lista de clases de los campos que quieres habilitar/deshabilitar
        let fields = [
            //'.tener_identificador',
            //'.tener_phone_ws',
            //'.tener_whatsapp_business_account_identifier',
            //'.tener_version_ws',
            //'.tener_token_ws',
            //'.tener_phone_identifier',
            //'.tener_app_Identifier'
        ];

        // Recorrer cada clase y habilitar/deshabilitar los campos
        fields.forEach(function(selector) {
            $(selector).prop('disabled', !enable); // Si `enable` es true, habilitar; si es false, deshabilitar
        });
    }

    function toggleSmsFields(enable) {
        // Lista de clases de los campos SMS que quieres habilitar/deshabilitar
        let smsFields = [
            '.tener_sms_account_sid',
            '.tener_sms_phone_number',
            '.tener_sms_auth_token',
            '.tener_version_sms'
        ];

        // Recorrer cada clase y habilitar/deshabilitar los campos
        smsFields.forEach(function(selector) {
            $(selector).prop('disabled', !enable); // Si `enable` es true, habilitar; si es false, deshabilitar
        });
    }



 
    function validarSoloNumeros(input) {
        const number = parseInt(input, 10);
        return !isNaN(number) && number.toString() === input;
    }

    $('.loglaunchWhatsAppSignup').click(function() {
        
 
        //if ($(this).prop('disabled')) {
        //    //console.log("Botón deshabilitado, no se ejecuta la acción.");
        //    return; // Salir si está deshabilitado
        //}

        lanzarWhatsAppSignup();
       

       
    });

    function lanzarWhatsAppSignup() 
    {
        //console.log("se dio click");

       let configuracion_id = $(".tener_whatsapp_app_id_configuration").val();

       //console.log("configuracion_id");
       //console.log(configuracion_id);

       if(isEmpty(configuracion_id) == true)
       {
           toastr.error("!The WhatsApp app configuration is required¡");
           return;
       }

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

       //console.log("tener_app_Identifier"); 
       //console.log(tener_app_Identifier); 

       if(isEmpty(tener_app_Identifier) == true)
       {
           toastr.error("!The app identifier is required¡");
           return;
       }

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

       //console.log("tener_secret_key_app"); 
       //console.log(tener_secret_key_app); 

       if(isEmpty(tener_secret_key_app) == true)
       {
           toastr.error("!App secret key is required¡");
           return;
       }

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

       //console.log("tener_version_ws"); 
       //console.log(tener_version_ws); 

       //console.log("configuracion_id"); 
       //console.log(configuracion_id); 

        if(isEmpty(tener_version_ws) == true)
        {
            toastr.error("!The WhatsApp version is required¡");
            return;
        }

        var app_Identifier   = $(".tener_app_Identifier").val();

        var version_ws       = $(".tener_version_ws").val();
        
        console.log("app_Identifier");
        console.log(app_Identifier);

        console.log("version_ws");
        console.log(version_ws);

        var oldScript = document.getElementById('facebook-jssdk');
        if (oldScript) {
            oldScript.parentNode.removeChild(oldScript);
        }

        if (window.FB) {
            delete window.FB;
        }

        // Cargar el nuevo SDK con la versión seleccionada
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js#version=" + version_ws + "&appId=" + app_Identifier + "&xfbml=true&autoLogAppEvents=true";
            fjs.parentNode.insertBefore(js, fjs);

            // Esperar a que el SDK esté listo
            js.onload = function() {
                console.log("SDK cargado con versión: " + version_ws);
            };
        }(document, 'script', 'facebook-jssdk'));

        //return;
        //$(".bloqueo_v1").removeAttr("hidden");
        //$(".bloqueo_v2").removeAttr("hidden");
        //$(".bloqueo_v3").removeAttr("hidden");
        
        $(".bloqueo_v1").removeAttr("hidden");
        $(".bloqueo_v2").removeAttr("hidden");
        $(".bloqueo_v3").removeAttr("hidden");
         
         

        setTimeout(function() {
            FB.login(fbLoginCallback, {
                config_id: configuracion_id, // configuration ID goes here
                response_type: 'code', // must be set to 'code' for System User access token
                override_default_response_type: true, // when true, any response types passed in the "response_type" will take precedence over the default types
                extras: {
                setup: {},
                featureType: '',
                sessionInfoVersion: '2',
                }
            });
        }, 1000);    
    }

    const fbLoginCallback = (response) => {

      console.log(response);

      //aqui devuelve un code que me servira para sacar el TOKEN

      CODE = "";

      if (response.authResponse) {
            CODE = response.authResponse.code;

            let tener_version_ws     = $(".tener_version_ws").val();
            let tener_secret_key_app = $(".tener_secret_key_app").val();
            let tener_app_Identifier = $(".tener_app_Identifier").val();

            let waba_id              = $(".tener_whatsapp_business_account_identifier").val();

            var informacionEnviar = {
                app_id:             tener_app_Identifier,
                app_secret:         tener_secret_key_app,
                version:            tener_version_ws,
                code:               CODE,
                waba_id:            waba_id,
            }; 

            let informacion_json = JSON.stringify(informacionEnviar); 
 

            console.log("INFORMACION PARA TRAER TOKEN");
            console.log(informacion_json);

            $.post(url_base + 'social/token-procedimientos-registro-insertado/', informacion_json  )  
            .done(function (data) {
                 
                    console.log("data respuesta del backend")
                    console.log(data);
                    //console.log(data);
                    //return;

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

                    $(".tener_token_ws").val("");

                     try {
                         const info = JSON.parse(data);
                       
                        if( info.status == "success")
                        {
                          
                            //toastr.success(info.mensaje);

                            $(".tener_token_ws").val(info.token);
                            $(".tener_phone_ws").val(info.phone);

                            //VAMOS A COLOCAR TODO EL MERENQUE PARA EJECUTAR ESTO
                            modificarInformacionWhatsapp();
 
                        }else{
                            //$('#ibox_form').unblock();

                            var body = $("html, body");
                            body.animate({ scrollTop:0 }, '1000', 'swing');
                            $("#emsgbody").html(info.mensaje);
                            $("#emsg").show("slow");

                        }

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

             

      }else{
        $(".bloqueo_v1").attr("hidden", true);
        $(".bloqueo_v2").attr("hidden", true);
        $(".bloqueo_v3").attr("hidden", true);
      }
 
 
    }

    $('.tener_version_ws').change(function() {
        var selectedVersion = $(this).val(); // Obtener el valor seleccionado
        //console.log("Versión seleccionada: " + selectedVersion);

        // Ejemplo: Hacer algo con la versión seleccionada
        if (selectedVersion ) {
           var app_Identifier   = $(".tener_app_Identifier").val();

            var version_ws       = $(".tener_version_ws").val();
            
            console.log("app_Identifier");
            console.log(app_Identifier);

            console.log("version_ws");
            console.log(version_ws);

            window.fbAsyncInit = function() {

                    FB.init({
                        appId            : app_Identifier,
                        autoLogAppEvents : true,
                        xfbml            : true,
                        version          : version_ws
                    });
            };
        }
    });
 

    {literal}
    window.addEventListener('message', (event) => {
      if (event.origin !== "https://www.facebook.com" && event.origin !== "https://web.facebook.com") {
        return;
      }
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'WA_EMBEDDED_SIGNUP') {
          
          if (data.event === 'FINISH') {

            $(".bloqueo_v1").removeAttr("hidden");
            $(".bloqueo_v2").removeAttr("hidden");
            $(".bloqueo_v3").removeAttr("hidden");

            const {phone_number_id, waba_id} = data.data;

            //console.log("Phone number ID ", phone_number_id, " WhatsApp business account ID ", waba_id);

            console.log("CODE");
            console.log(CODE);

            console.log("phone_number_id");
            console.log(phone_number_id);

            console.log("waba_id");
            console.log(waba_id);

            $(".tener_phone_identifier").val(phone_number_id);
            $(".tener_whatsapp_business_account_identifier").val(waba_id);

 
          } else if (data.event === 'CANCEL') {
            const {current_step} = data.data;
            console.warn("Cancel at ", current_step);

            $(".bloqueo_v1").attr("hidden", true);
            $(".bloqueo_v2").attr("hidden", true);
            $(".bloqueo_v3").attr("hidden", true);
 
          } else if (data.event === 'ERROR') {
            const {error_message} = data.data;
            console.error("error ", error_message);
            
            $(".bloqueo_v1").attr("hidden", true);
            $(".bloqueo_v2").attr("hidden", true);
            $(".bloqueo_v3").attr("hidden", true);
          }
        }


        //document.getElementById("session-info-response").textContent = JSON.stringify(data, null, 2);
      } catch {
        console.log('Non JSON Responses', event.data);
      }
    });

    {/literal}

    function modificarInformacionWhatsapp()
    {

        let tener_identificador     = $(".tener_identificador").val();
        let tener_phone_ws          = $(".tener_phone_ws").val();
        let tener_whatsapp_business_account_identifier = $(".tener_whatsapp_business_account_identifier").val();
        let tener_version_ws       = $(".tener_version_ws").val();
        let tener_token_ws         = $(".tener_token_ws").val();
        let tener_phone_identifier = $(".tener_phone_identifier").val();
        let tener_app_Identifier   = $(".tener_app_Identifier").val();
        let tener_secret_key_app   = $(".tener_secret_key_app").val();
        let tener_whatsapp_app_id_configuration   = $(".tener_whatsapp_app_id_configuration").val();

        var informacionEnviar = {
            identificador:             tener_identificador,
            phone_ws:                  tener_phone_ws,
            whatsapp_business_account_identifier:          tener_whatsapp_business_account_identifier,
            tener_version_ws:          tener_version_ws,
            token_ws:                  tener_token_ws,
            phone_identifier:          tener_phone_identifier,
            app_Identifier:            tener_app_Identifier,
            secret_key_app:            tener_secret_key_app,
            whatsapp_app_id_configuration: tener_whatsapp_app_id_configuration,

            id:                         tener_id, //este le pertenece al id del todo
 
        }; 
    
        $(".bloqueo_v1").removeAttr("hidden");
        $(".bloqueo_v2").removeAttr("hidden");
        $(".bloqueo_v3").removeAttr("hidden");

        console.log("INFORMACION PARA TRAER TOKEN");
        console.log(JSON.stringify(informacionEnviar));

        $.post(url_base + 'social/update-only-whatsapp-configuration/', JSON.stringify(informacionEnviar)  ) 
            .done(function (data) {
                 
                //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);

                        $(".quitar_btn_registro_insertado").css("display", "none");
                        $(".habilitarConfigWS").prop("disabled", false);
                        $(".habilitarConfigWS").prop('checked', true);

                        $(".ocultar_opcion_whatsapp").css("display", "");
                        $(".tener_version_ws").prop("disabled", true);

                        let whatsapp_business_account_identifier = $(".tener_whatsapp_business_account_identifier").val();

                        $("#crearLinkPago").attr("href", "https://business.facebook.com/billing_hub/accounts/details/?asset_id=" + whatsapp_business_account_identifier + "&account_type=whatsapp-business-account");
                        $("#crearLinkPago").attr("target", "_blank");
                
                        Swal.fire({
                        title: info.title,
                        text: info.message,
                        icon: "success",
                        backdrop: true,           // Muestra el fondo oscuro
                        allowOutsideClick: false, // Evita que se cierre al hacer clic fuera
                        allowEscapeKey: false,    // Opcional: Evita que se cierre con la tecla Escape
                        }).then((result) => {
                            if (result.isConfirmed) {

                                //window.location = info.redirect;
                                
                                console.log("El usuario hizo clic en OK");
                                
                            }
                        });

    
                    }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(error);
                    $("#emsg").show("slow");

               

                }
            });


    }

 
 
</script>
{/block}