{extends file="layouts/base.tpl"}
{block name="head"}

    <style>
        @media (min-width: 992px){
            .clx-fixed-navigation:not(.clx-navigation-type-top):not(.nav-function-hidden):not(.nav-function-minify) .page-content-wrapper {
                padding-left: 0;
            }
        }
         #togglePassword:focus {
        border-color: #E5E5E5 !important;
    }


    </style>


    {if $config['recaptcha'] eq '1' && !empty($config['recaptcha_sitekey'])}
        <script src="https://www.google.com/recaptcha/api.js?render={$config['recaptcha_sitekey']}"></script>
    {/if}


    {*
    <script src="https://sandbox.web.squarecdn.com/v1/square.js"></script>
    
    *}

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

    

{/block}


{block name="content_body"}

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

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

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


    <div class="page-content-wrapper bg-transparent m-0">
        <div class="height-10 w-100 shadow-sm px-4 bg-brand-gradient">
            <div class="d-flex align-items-center container p-0">
                <div class="page-logo width-mobile-auto m-0 align-items-center justify-content-center p-0 bg-transparent bg-img-none shadow-0 height-9 border-0">
                    <a href="{APP_URL}" class="page-logo-link press-scale-down d-flex align-items-center">
                        {if isset($config['logo_square'])}
                            <img src="{{APP_URL}}/storage/system/{{$config['logo_square']}}" alt="{{$config['CompanyName']}}" aria-roledescription="logo">
                        {else}
                            <img src="{{APP_URL}}/storage/system/logo-512x512.png?v=2" alt="{{$config['CompanyName']}}" aria-roledescription="logo">
                        {/if}
                        {if isset($config['logo_text'])}
                            <span class="page-logo-text mr-1" style="color:black;">{$config['logo_text']}</span>
                        {else}
                            <span class="page-logo-text mr-1">CloudOnex</span>
                        {/if}
                    </a>
                </div>

                {if ($type == 'client_auth' || $type == 'client_password_reset') && $config['allow_customer_registration'] eq '1'}
                    <a href="{$_url}client/register/" class="btn-link text-white ms-auto">
                        {$_L['Dont have an account']} {$_L['Register']}
                    </a>

                {/if}


            </div>
        </div>
        <div class="flex-1">
            <div class="container py-4 py-lg-5 my-lg-5 px-4 px-sm-0">

                {if $type eq 'admin_auth'}

 
                    <div class="mx-auto ocultarLogin" style="max-width: 440px;">
                        <div class="card p-4">

                            <h1 class="mb-3 text-center">
                                {$_L['Login']}
                            </h1>

                            {if isset($notify)}
                                {$notify}
                            {/if}

                            <form method="post" id="form_admin_auth" class="mt-3" action="{$_url}login/post/{if isset($after)}{$after}/{/if}">
                                <div class="mb-3">
                                    <label class="form-label" for="username">{$_L['Email Address']}</label>
                                    <input id="username" name="username" class="form-control form-control-lg" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="password">{$_L['Password']}</label>
                                    {*
                                        <input type="password" id="password" name="password" class="form-control form-control-lg" required>
                                    
                                    *}

                                    <div class="input-group">
                                        <input type="password" id="password" name="password" class="form-control form-control-lg" required>
                                        <button type="button" class="btn btn-outline-secondary" id="togglePassword" style=" border-color: #E5E5E5; ">
                                            <i class="fas fa-eye" id="toggleIcon"></i>
                                        </button>
                                    </div>

                                </div>

                                <div class="mb-3">
                                    <button type="submit" id="btn_admin_auth" class="btn btn-primary btn-block btn-lg">{$_L['Sign in']}</button>
                                </div>
                            </form>

                            <div class="text-center mt-3">
                                <a href="{$_url}admin/forgot-pw/" id="to-recover" class="text-info">{$_L['Forgot password']}</a>
                            </div>




                        </div>
                    </div>

                {elseif $type eq 'admin_password_reset'}

                    <div class="mx-auto" style="max-width: 440px;">
                        <div class="card p-4">

                            {if isset($notify)}
                                {$notify}
                            {/if}

                            <form method="post" class="mt-3" action="{$_url}admin/forgot-pw-post/">
                                <div class="mb-3">
                                    <label class="form-label" for="username">{$_L['Email Address']}</label>
                                    <input id="username" name="username" class="form-control form-control-lg" required>
                                </div>

                                <div class="mb-3">
                                    <button type="submit" class="btn btn-primary btn-block btn-lg">{$_L['Reset Password']}</button>
                                </div>
                            </form>

                            <div class="mt-3 text-center">
                                <a href="{$_url}admin/">{$_L['Back To Login']}</a>
                            </div>

                        </div>
                    </div>

                    {elseif $type eq 'client_auth'}

                    <div class="row">
                        <div class="col col-md-6 col-lg-7">

                            {if isset($admin) && $admin}
                                <div class="my-3">
                                    <a href="javascript:;" id="btn_edit_content" class="btn btn-primary">{$_L['Edit']}</a>
                                    <a href="{$_url}dashboard" class="btn btn-primary">{$_L['Dashboard']}</a>
                                    <a href="{$_url}logout" class="btn btn-danger">{$_L['Logout']}</a>
                                </div>
                                <div class="hr-line-dashed"></div>
                            {/if}

                            <div style="font-size: 18px;" class="fw-300">

                                {Widget::getWidgetContent('client-auth-page-widget')}

                            </div>



                        </div>
                        <div class="col-sm-12 col-md-6 col-lg-5 col-xl-4 ms-auto">
                            <div class="card p-4" style="box-shadow: 1px 0 20px rgba(0, 0, 0, .08);">

                                <h1 class="fw-300 mb-3 text-center">
                                    {$_L['Login']}
                                </h1>

                                {if isset($notify)}
                                    {$notify}
                                {/if}

                                <form method="post" class="mt-3" id="form_client_auth" action="{$_url}client/auth/">
                                    <div class="mb-3">
                                        <label class="form-label" for="username">{$_L['Email Address']}</label>
                                        <input id="username" name="username" class="form-control form-control-lg" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label" for="password">{$_L['Password']}</label>
                                        <input type="password" id="password" name="password" class="form-control form-control-lg" required>
                                    </div>


                                    <div class="mb-3">
                                        <button type="submit" id="btn_client_auth" class="btn btn-primary btn-block btn-lg">{$_L['Login']}</button>
                                    </div>

                                    {if $config['allow_customer_registration'] eq '1'}
                                        <div class="mb-3 mb-0">
                                            <div class="col-sm-12 text-center">
                                                {$_L['Dont have an account']} <a href="{$_url}client/register/" class="text-info m-l-5"><b>{$_L['Register']}</b></a>
                                            </div>
                                        </div>
                                    {/if}

                                    <div class="text-center">
                                        <a href="{$_url}client/forgot_pw/" id="to-recover" class="text-info">{$_L['Forgot password']}</a>
                                    </div>



                                </form>




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


                {elseif $type eq 'client_password_reset'}
                    <div class="mx-auto" style="max-width: 440px;">
                        <div class="card p-4">

                            {if isset($notify)}
                                {$notify}
                            {/if}

                            <form method="post" class="mt-3" action="{$_url}client/forgot_pw_post/">
                                <div class="mb-3">
                                    <label class="form-label" for="username">{$_L['Email Address']}</label>
                                    <input id="username" name="username" class="form-control form-control-lg" required>
                                </div>

                                <div class="mb-3">
                                    <button type="submit" class="btn btn-primary btn-block btn-lg">{$_L['Reset Password']}</button>
                                </div>
                            </form>

                            {if $config['allow_customer_registration'] eq '1'}
                                <div class="mb-3 mt-3">
                                    <div class="col-sm-12 text-center">
                                        {$_L['Dont have an account']} <a href="{$_url}client/register/" class="text-info m-l-5"><b>{$_L['Register']}</b></a>
                                    </div>
                                </div>
                            {/if}




                        </div>
                    </div>

                {elseif $type eq 'client_register'}

                    <div class="mx-auto" style="max-width: 440px;">
                        <div class="card p-4">

                            {if isset($notify)}
                                {$notify}
                            {/if}

                            <form method="post" id="form_client_register" class="mt-3" action="{$_url}client/register_post/">

                                <div class="mb-3">
                                    <label class="form-label" for="fullname">{$_L['Full_Name']}</label>
                                    <input id="fullname" name="fullname" class="form-control form-control-lg" required>
                                </div>


                                <div class="mb-3">
                                    <label class="form-label" for="email">{$_L['Email Address']}</label>
                                    <input id="email" name="email" class="form-control form-control-lg" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label" for="password">{$_L['Password']}</label>
                                    <input type="password" id="password" name="password" class="form-control form-control-lg" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label" for="password2">{$_L['Confirm_Password']}</label>
                                    <input type="password" id="password2" name="password2" class="form-control form-control-lg" required>
                                </div>

                                {foreach $extra_fields as $field}

                                    <div class="mb-3">
                                        <label for="field_{$field['id']}" class="form-label">{$field['label']}</label>
                                        <input type="text" class="form-control form-control-lg" id="field_{$field['id']}" name="{$field['name']}">
                                    </div>

                                {/foreach}

                                <div class="mb-3">
                                    <button type="submit" id="btn_client_register" class="btn btn-primary btn-block btn-lg">{$_L['Register']}</button>
                                </div>
                            </form>

                            <div class="mb-3 mt-3">
                                <div class="col-sm-12 text-center">
                                    {$_L['Already registered']}  <a href="{$_url}client/login/" class="text-info m-l-5"><b>{$_L['Login']}</b></a>
                                </div>
                            </div>




                        </div>
                    </div>

                {/if}

                <!-- aqui el pago -->
                <div class="mx-auto panel pagarFactura" hidden style="max-width: 96%;">
                    <div class="panel-hdr">
                        
                        <h2>Bill Payment</h2>

                    </div>

                    <div class="panel-container show" id="ibox_form">

                        <div class="panel-content">

                            <h2 class="text-center"><span></span>Your trial time or subscription period has ended and you must make a payment</h2>
                            <p class="text-center"><span></span>Enter your payment information to renew your subscription:</p>
                            <br>

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

                                    <input type="text"  hidden  class="tener_id_pasarela_pago" value="{$sys_pg["id"]}"  disabled  >

                                    <div class="row">

                                    

                                        <div class="col-md-6 col-sm-12">
                                            <div class="mb-3 row">
                                                <label for="selectCard" class="col-sm-3"><span class="h6">Select a Card</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">                                  
                                                    <select id="selectCard" name="selectCard" class="form-control  tenerSelectCard" >
                                                        <option value="-1" selected>Select a card</option>
                                                        <option value="0">Card Creation</option>
                                                        {foreach $data as $ds}
                                                        <option value="{$ds['id']}"> {$ds['tipo_pasarela_pago']} - {$ds['titular_tarjeta']} - {$ds['numero_tarjeta']}</option>
                                                        {/foreach}
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

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

                                            <div class="mb-3 row">
                                                <label for="descripcion" class="col-sm-3"><span class="h6">Descriptions</span><span class="text-danger"></span></label>
                                                <div class="col-sm-9">                                  
                                                    <!-- <textarea id="descripcion" name="descripcion" class="form-control tenerDescripcion" rows="3" cols="50"> </textarea> -->
                                                    <input type="text" id="descripcion" name="descripcion" class="form-control tenerDescripcion">
                                                </div>
                                            </div>

                                        </div>

                                        {* formulario seleccion o creacion de tarjeta de credito *}
 
                                        <div class="col-md-12 col-sm-12">
                                        
                                            <div class="mb-3 row">
                                                <label for="tipoPasarelaPago" class="col-sm-3"><span class="h6">Payment method type</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">                                  
                                                    <select id="tipoPasarelaPago" name="tipoPasarelaPago" class="form-control tipoPasarelaPago" disabled>
                                                        
                                                        <option value="Stripe">Stripe</option>
                                                        <option value="Square">Square</option>
                                                    </select>
                                                </div>
                                            </div>

                                        </div>

                                        {*como estaba*}

                                        <div class="col-md-12 col-sm-12 MostrarSoloSquare"  style="display:none">
                                            <div class="MostrarSoloSquare"  style="display:none">
                                                <div id="card-container" ></div>
                                            </div>
                                        </div>

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

                                            <div class="mb-3 row">
                                                <label for="card_name" class="col-sm-3"><span class="h6">Card Name</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="card_name" name="card_name" class="form-control tenercard_name" disabled autofocus>
                                                </div>
                                            </div>
                
                                            <div class="mb-3 row OpcionesStripe">
                                                <label for="card_number" class="col-sm-3"><span class="h6">Card Number</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="card_number" name="card_number" class="form-control tenercard_number" disabled>
                                                </div>
                                            </div>

                                            <div class="mb-3 row mostrarCVV"  style="display: none">
                                                <label for="ccv_code" class="col-sm-3"><span class="h6">CCV code</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="ccv_code" name="ccv_code" class="form-control tenerccv_code" disabled autofocus>
                                                </div>
                                            </div>

                                            <div class="mb-3 row">
                                                <label for="pais_tarjeta_detalle" class="col-sm-3"><span class="h6">Country</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="text" autocomplete="off"  id="pais_tarjeta_detalle" name="pais_tarjeta_detalle" class="form-control tener_pais_tarjeta_detalle" disabled >                                        
                                                </div>
                                            </div> 

                                            <div class="mb-3 row">
                                                <label for="ciudad_tarjeta_detalle" class="col-sm-3"><span class="h6">City</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="text" autocomplete="off"  id="ciudad_tarjeta_detalle" name="ciudad_tarjeta_detalle" class="form-control tener_ciudad_tarjeta_detalle" disabled>                                        
                                                </div>
                                            </div> 

                                            <div class="mb-3 row">
                                                <label for="codigo_postal_tarjeta_detalle" class="col-sm-3"><span class="h6">Postal Code</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="text" autocomplete="off"  id="codigo_postal_tarjeta_detalle" name="codigo_postal_tarjeta_detalle" class="form-control tener_codigo_postal_tarjeta_detalle" disabled>                                        
                                                </div>
                                            </div>

                                            <div class="mb-3 row">
                                                <label for="address" class="col-sm-3"><span class="h6">{$_L['Address']} 1</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="text" autocomplete="off"  id="address" name="address" class="form-control teneraddress" disabled>                                        
                                                </div>
                                            </div>

        

                                        </div>

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

                                            <div class="mb-3 row OpcionesStripe">
                                                <label for="mes_expiracion" class="col-sm-3"><span class="h6">Expiration Month</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">                                  
                                                    <select id="mes_expiracion" name="mes_expiracion" class="form-control tener_mes_expiracion" disabled>
                                                        <option value="0" selected>Select Expiration Month</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="mb-3 row OpcionesStripe">
                                                <label for="ano_expiracion" class="col-sm-3"><span class="h6">Expiration Year</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">     
                                                                
                                                    <select id="ano_expiracion" name="ano_expiracion" class="form-control tener_ano_expiracion mostrarAnoStripe" disabled>
                                                        <option value="" disabled selected>YYYY</option>
                                                    </select>

                                                    <input type="text" id="ano_expiracion" name="ano_expiracion" class="form-control tener_ano_expiracion mostrarAnoSquare" disabled style="display: none;" >

                                                </div>
                                            </div>

                                            <div class="mb-3 row">
                                                <label for="nombre_tarjeta_detalle" class="col-sm-3"><span class="h6">Name</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">   
                                                    <input type="text" autocomplete="off"  id="nombre_tarjeta_detalle" name="nombre_tarjeta_detalle" class="form-control tener_nombre_tarjeta_detalle"   disabled>                                        
                                                </div>
                                            </div>     

                                            <div class="mb-3 row">
                                                <label for="correo_tarjeta_detalle" class="col-sm-3"><span class="h6">Email</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="email" autocomplete="off"  id="correo_tarjeta_detalle" name="correo_tarjeta_detalle" class="form-control tener_correo_tarjeta_detalle"  disabled>                                        
                                                </div>
                                            </div>     

                                            <div class="mb-3 row">
                                                <label for="telefono_tarjeta_detalle" class="col-sm-3"><span class="h6">Phone</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="text" autocomplete="off"  id="telefono_tarjeta_detalle" name="telefono_tarjeta_detalle" class="form-control tener_telefono_tarjeta_detalle" disabled >                                        
                                                </div>
                                            </div>   

                                            <div class="mb-3 row">
                                                <label for="direccion_tarjeta_detalle" class="col-sm-3"><span class="h6">{$_L['Address']} 2</span><span class="text-danger"></span> </label>
                                                <div class="col-sm-9">
                                                    <input type="text" autocomplete="off"  id="direccion_tarjeta_detalle" name="direccion_tarjeta_detalle" class="form-control tener_direccion_tarjeta_detalle"  disabled>                                        
                                                </div>
                                            </div>      

                                        </div> 
 

                                        <div class="col-md-12 col-sm-12">
                                            <div class="mb-3 row">
                                                <label for="monto" class="col-sm-3"><span class="h6">Amount to pay</span><span class="text-danger">*</span></label>
                                                <div class="col-sm-9">
                                                    <input type="text" id="monto" name="monto" class="form-control tenermonto" value="{number_format($total, 2, '.', ',')}" disabled autofocus>
                                                </div>
                                            </div>
                                        </div>
                                
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="mb-5">

                                                <button class="btn btn-primary mt-3 me-3 bottonPagarFactura" type="button" id="submit">Pay</button>

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


                                </form>
                            </div>

                        </div>



                    </div>
                </div>

                <!-- fin de aqui el pago -->


                <div class="position-absolute pos-bottom pos-left pos-right p-3 text-center">
                    &copy; {date('Y')} {$config['CompanyName']}
                </div>
            </div>
        </div>
    </div>
{/block}

{block name="script"}
    <script>

        //$(".ocultarLogin").hide();
        //$(".pagarFactura").removeAttr("hidden");
        //$(".pagarFactura").show();
        
        var idSelectCard = -1;
        var idSelectPaymentGateway = 0;
        var correo_electronico ="";
        var password = "";
        

        var BASE_DE_DATOS_GLOBAL = $("#DB_NAME").val();

        var databases_name_indexedDb = BASE_DE_DATOS_GLOBAL;

        const deleteRequest = window.indexedDB.deleteDatabase(databases_name_indexedDb);

        deleteRequest.onsuccess = () => {
           console.log("Base de datos eliminada con éxito");
           
        };

        deleteRequest.onerror = (error) => {
           console.error("Error al eliminar la base de datos: ", error);
         
        };

        deleteRequest.onblocked = () => {
           console.warn("Eliminación bloqueada, puede haber conexiones abiertas");
           
        };

        var selectMesExpiracion = $('.tener_mes_expiracion');

        const monthNames = [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ];

        for (var i = 1; i <= 12; i++) {
            var opcion = $('<option></option>').attr('value', i).text(monthNames[i - 1]);            
            selectMesExpiracion.append(opcion);
        }

        function generarAnios() {
            const currentYear = new Date().getFullYear();

            /*
            for (let i = -5; i <= 10; i++) {
                const year = currentYear + i;
                const value = year.toString().slice(-2); // Últimos 2 dígitos del año

                this.anios.push({ value, text: year });
            }
            */
   
            var selectAnoExpiracion = $('.tener_ano_expiracion');

            let concat = ""
            for (let i = 50; i >= -50; i--) {

                const year = currentYear + i;
                const value = year.toString().slice(-2); // Últimos 2 dígitos del año
 
                concat += "<option value=\"" + value + "\">" + year + "</option>";
            }

            selectAnoExpiracion.append(concat);

        }

        generarAnios();

        async function initializeCard(payments) {
            const card = await payments.card( );
            await card.attach("#card-container");
            return card;
        }

        async function tokenize(paymentMethod) {
            const tokenResult = await paymentMethod.tokenize();

            return tokenResult;

            console.log(tokenResult);
            console.log("tokenResult");

            if (tokenResult.status == "OK") {
                return tokenResult.token;
            } else {
                throw new Error(
                    "Tokenization failed: " + tokenResult.errors,
                );
            }
        }

        $(document).ready(function () {

            async function initializeSquare() {
        
                var aplicacion_id_square = $("#aplicacion_id_square").val();
                var location_id_square = $("#location_id_square").val();
                
                try {
                    // Initialize Square Payments SDK
                    const payments = window.Square.payments(
                        aplicacion_id_square,
                        location_id_square,
                    );

                    // Initialize card form (assuming initializeCard is defined)
                    const card = await initializeCard(payments);
                    return card;

                } catch (error) {
                    console.error('Error initializing Square:', error);
                    alert(error.message);
                    return null;
                }
            }

            card_datos_square = null;

            initializeSquare().then(card => {
                card_datos_square = card; // Store card instance for later use
                console.log('Square card initialized:', card_datos_square);
            });

            document.getElementById('togglePassword').addEventListener('click', function () {
                const passwordInput = document.getElementById('password');
                const toggleIcon = document.getElementById('toggleIcon');
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    toggleIcon.classList.remove('fa-eye');
                    toggleIcon.classList.add('fa-eye-slash');
                } else {
                    passwordInput.type = 'password';
                    toggleIcon.classList.remove('fa-eye-slash');
                    toggleIcon.classList.add('fa-eye');
                }
            });

        });

        var card_datos_square = null;

        $(function () {

            var $modal = $('#cloudonex_body');

            {if $type eq 'admin_auth'}
            let $form_admin_auth = $('#form_admin_auth');
            let $btn_admin_auth = $('#btn_admin_auth');


            $form_admin_auth.on('submit',function (e) {
                
                e.preventDefault();

                correo_electronico = $('#username').val();
                password = $('#password').val();

                $btn_admin_auth.disabled = true;

                {if $config['recaptcha'] eq '1' && !empty($config['recaptcha_sitekey'])}

                grecaptcha.ready(function() {
                    grecaptcha.execute('{$config['recaptcha_sitekey']}', { action: 'submit' }).then(function(token) {
                        $.post( "{$_url}login/post/{if isset($after)}{$after}/{/if}", {
                            username: $('#username').val(),
                            password: $('#password').val(),
                            token: token,
                        })
                            .done(function( data ) {
                                //window.location = data.redirect_url;

                                /*
                                if(data.descripcion == "bloqueado" && data.success == false)
                                {
                                    toastr.error("User is inactive");
                                }else{
                                    if(data.descripcion == "aprobado" && data.success == true)
                                    {
                                        //toastr.success("aprobado entrando al sistema");
                                        window.location = data.redirect_url;
                                    }else{
                                        if(data.descripcion == "invalido" && data.success == false)
                                        {
                                            //El correo electrónico o la contraseña son incorrectos.
                                            toastr.error("The email or password is incorrect.");
                                        }
                                    }
                                }
                                */

                                if(data.descripcion == "vencido" && data.success == false)
                                {
                                    //No se puede acceder al sistema. La versión que está utilizando ha expirado, porfavor comunicarse con administración
                                    toastr.error("Cannot access the system. The version you are using has expired, please contact administration");
                                }else{
                                    if(data.descripcion == "inactivo" && data.success == false)
                                    {
                                        //No se puede acceder al sistema. La versión que está utilizando esta inactiva, porfavor comunicarse con administración
                                        toastr.error("Cannot access the system. The version you are using is inactive, please contact administration");
                                    }else{
                                        if(data.descripcion == "invalido" && data.success == false)
                                        {
                                            //El correo electrónico o la contraseña son incorrectos.
                                            toastr.error("The email or password is incorrect.");
                                        }else{
                                            if(data.descripcion == "aprobado" && data.success == true)
                                            {
                                                //toastr.success("aprobado");
                                                window.location = data.redirect_url;
                                            }else{
                                                if(data.descripcion == "moroso" && data.success == false)
                                                {
                                                    //Tiene saldos pendientes por pagar
                                                    toastr.error("You have outstanding balances to pay");
                                                    $(".ocultarLogin").hide();
                                                    $(".pagarFactura").removeAttr("hidden");
                                                    $(".pagarFactura").show();
                                                }else{
                                                    if(data.descripcion == "bloqueado" && data.success == false)
                                                    {
                                                        toastr.error("User is inactive");
                                                    }else{

                                                        if(data.descripcion == "ip_invalida" && data.success == false)
                                                        {
                                                            toastr.error("Access denied, your IP is not on the allowed IP list.");
                                                        }
                                                        
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                            }).fail(function(data) {
                            $btn_admin_auth.disabled = false;
                            toastr.error(data.responseText);
                        });
                    });
                });

                {else}

                $.post( "{$_url}login/post/{if isset($after)}{$after}/{/if}", {
                    username: $('#username').val(),
                    password: $('#password').val(),
                })
                    .done(function( data ) {
                        //window.location = data.redirect_url;

                        /*
                        if(data.descripcion == "bloqueado" && data.success == false)
                        {
                            toastr.error("User is inactive");
                        }else{
                            if(data.descripcion == "aprobado" && data.success == true)
                            {
                                //toastr.success("aprobado entrando al sistema");
                                window.location = data.redirect_url;
                            }else{
                                if(data.descripcion == "invalido" && data.success == false)
                                {
                                    //El correo electrónico o la contraseña son incorrectos.
                                    toastr.error("The email or password is incorrect.");
                                }
                            }
                        }*/

                        if(data.descripcion == "vencido" && data.success == false)
                        {
                            //No se puede acceder al sistema. La versión que está utilizando ha expirado, porfavor comunicarse con administración
                            toastr.error("Cannot access the system. The version you are using has expired, please contact administration");
                        }else{
                            if(data.descripcion == "inactivo" && data.success == false)
                            {
                                //No se puede acceder al sistema. La versión que está utilizando esta inactiva, porfavor comunicarse con administración
                                toastr.error("Cannot access the system. The version you are using is inactive, please contact administration");
                            }else{
                                if(data.descripcion == "invalido" && data.success == false)
                                {
                                    //El correo electrónico o la contraseña son incorrectos.
                                    toastr.error("The email or password is incorrect.");
                                }else{
                                    if(data.descripcion == "aprobado" && data.success == true)
                                    {
                                        //toastr.success("aprobado");
                                        window.location = data.redirect_url;
                                    }else{
                                        if(data.descripcion == "moroso" && data.success == false)
                                        {
                                            //Tiene saldos pendientes por pagar
                                            toastr.error("You have outstanding balances to pay");
                                            $(".ocultarLogin").hide();
                                            $(".pagarFactura").removeAttr("hidden");
                                            $(".pagarFactura").show();
                                        }else{
                                            if(data.descripcion == "fallo_conectividad" && data.success == false)
                                            {
                                                //El correo electrónico o la contraseña son incorrectos.
                                                toastr.error("Database connectivity failure");
                                            }else{
                                                if(data.descripcion == "bloqueado" && data.success == false)
                                                {
                                                    toastr.error("User is inactive");
                                                }else{

                                                    if(data.descripcion == "ip_invalida" && data.success == false)
                                                    {
                                                        toastr.error("Access denied, your IP is not on the allowed IP list.");
                                                    }
                                                    
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }).fail(function(data) {
                    $btn_admin_auth.disabled = false;
                    toastr.error(data.responseText);
                });

                {/if}


            });

            {/if}

            {if $type eq 'client_auth'}

            let $form_client_auth = $('#form_client_auth');
            let $btn_client_auth = $('#btn_client_auth');

            $form_client_auth.on('submit',function (e) {
                e.preventDefault();

                $btn_client_auth.disabled = true;

                {if $config['recaptcha'] eq '1' && !empty($config['recaptcha_sitekey'])}

                grecaptcha.ready(function() {
                    grecaptcha.execute('{$config['recaptcha_sitekey']}', { action: 'submit' }).then(function(token) {
                        $.post( "{$_url}client/auth/", {
                            username: $('#username').val(),
                            password: $('#password').val(),
                            then: '{$then|default:''}',
                            token: token,
                            _token: '{csrf_token()}',
                        })
                            .done(function( data ) {
                                window.location = data.redirect_url;
                            }).fail(function(data) {
                            $btn_client_auth.disabled = false;
                            toastr.error(data.responseText);
                        });
                    });
                });

                {else}

                $.post( "{$_url}client/auth/", {
                    username: $('#username').val(),
                    password: $('#password').val(),
                    then: '{$then|default:''}',
                    _token: '{csrf_token()}',
                })
                    .done(function( data ) {
                        window.location = data.redirect_url;
                    }).fail(function(data) {
                    $btn_client_auth.disabled = false;
                    toastr.error(data.responseText);
                });

                {/if}


            });

            {if isset($admin) && $admin}

            $('#login_as_admin').on('click',function () {
                window.location = base_url + 'login/';
            });

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

                $.fancybox.open({
                    src  : base_url + 'settings/client-auth-page-widget',
                    type : 'ajax',
                    opts : {
                        afterShow : function( instance, current ) {
                            $('#edit_content').redactor();
                        },
                        modal: true,
                    }
                });

            });

            $modal.on('click', '.modal_submit', function(e){

                e.preventDefault();

                $.post( base_url + "settings/client-auth-page-widget-save/", $("#clx_modal_form").serialize())
                    .done(function( data ) {

                        if ($.isNumeric(data)) {

                            location.reload();

                        }

                        else {
                            toastr.error(data);
                        }

                    });

            });

            {/if}


            {/if}

            {if $type eq 'client_register'}

            let $form_client_register = $('#form_client_register');
            let $btn_client_register = $('#btn_client_register');

            $form_client_register.on('submit',function (e) {
                e.preventDefault();

                $btn_client_register.disabled = true;

                {if $config['recaptcha'] eq '1' && !empty($config['recaptcha_sitekey'])}

                grecaptcha.ready(function() {
                    grecaptcha.execute('{$config['recaptcha_sitekey']}', { action: 'submit' }).then(function(token) {
                        $.post( "{$_url}client/register_post/", {
                            fullname: $('#fullname').val(),
                            email: $('#email').val(),
                            password: $('#password').val(),
                            password2: $('#password2').val(),
                            then: '{$then}',
                            token: token,
                            _token: '{csrf_token()}',
                        })
                            .done(function( data ) {
                                window.location = data.redirect_url;
                            }).fail(function(data) {
                            $btn_client_register.disabled = false;
                            toastr.error(data.responseText);
                        });
                    });
                });

                {else}

                $.post( "{$_url}client/register_post/", {
                    fullname: $('#fullname').val(),
                    email: $('#email').val(),
                    password: $('#password').val(),
                    password2: $('#password2').val(),
                    then: '{$then|default:''}',
                    _token: '{csrf_token()}',
                })
                    .done(function( data ) {
                        window.location = data.redirect_url;
                    }).fail(function(data) {
                    $btn_client_register.disabled = false;
                    toastr.error(data.responseText);
                });

                {/if}


            });

            {/if}

        });

        $('.tenerSelectCard').change(function() {
            var selectedValue = $(this).val();

            $(".MostrarSoloSquare").css("display","none");

            if(selectedValue == 0 || selectedValue == -1)
            {

                $(".mostrarAnoSquare").css("display","none");
                $(".mostrarAnoStripe").css("display","");

                $(".mostrarCVV").css("display","");
                $(".OpcionesStripe").css("display","");

                $(".tenercard_name").val("");
                $(".tenerccv_code").val("");
                $(".teneraddress").val("");
                $(".tenercard_number").val("");
                $(".tener_nombre_tarjeta_detalle").val("");
                $(".tener_correo_tarjeta_detalle").val("");
                $(".tener_mes_expiracion").val(0);
                $(".tener_ano_expiracion").val("");
                $(".tener_nombre_tarjeta_detalle").val("");
                $(".tener_correo_tarjeta_detalle").val("");
                $(".tener_pais_tarjeta_detalle").val("");
                $(".tener_ciudad_tarjeta_detalle").val("");
                $(".tener_telefono_tarjeta_detalle").val("");
                $(".tener_codigo_postal_tarjeta_detalle").val("");
                $(".tener_direccion_tarjeta_detalle").val("");

                $(".tipoPasarelaPago").val("Stripe");

                //$('.tenercobro_automatico').prop('checked', false);

                idSelectCard = selectedValue;
                $(".tenerSelectCard").val(selectedValue);

                if(selectedValue != 0)
                {
                    $('.tenercard_name').attr('disabled', 'disabled');
                    $('.tenerccv_code').attr('disabled', 'disabled');
                    $('.teneraddress').attr('disabled', 'disabled');
                    $('.tenercard_number').attr('disabled', 'disabled');
                    $('.tener_mes_expiracion').attr('disabled', 'disabled');
                    $('.tener_ano_expiracion').attr('disabled', 'disabled');
                    $('.tener_nombre_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tener_correo_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tener_pais_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tener_ciudad_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tener_telefono_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tener_codigo_postal_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tener_direccion_tarjeta_detalle').attr('disabled', 'disabled');
                    $('.tipoPasarelaPago').attr('disabled', 'disabled');

 
                    //$('.tenercobro_automatico').attr('disabled', 'disabled');
                }else{
                    $('.tenercard_name').removeAttr('disabled');
                    $('.tenerccv_code').removeAttr('disabled');
                    $('.teneraddress').removeAttr('disabled');
                    $('.tenercard_number').removeAttr('disabled');
                    $('.tener_mes_expiracion').removeAttr('disabled');
                    $('.tener_ano_expiracion').removeAttr('disabled');
                    $('.tener_nombre_tarjeta_detalle').removeAttr('disabled');
                    $('.tener_correo_tarjeta_detalle').removeAttr('disabled');
                    $('.tener_pais_tarjeta_detalle').removeAttr('disabled');
                    $('.tener_ciudad_tarjeta_detalle').removeAttr('disabled');
                    $('.tener_telefono_tarjeta_detalle').removeAttr('disabled');
                    $('.tener_codigo_postal_tarjeta_detalle').removeAttr('disabled');
                    $('.tener_direccion_tarjeta_detalle').removeAttr('disabled');

                    $('.tipoPasarelaPago').removeAttr('disabled');

                    //$('.tenercobro_automatico').removeAttr('disabled');
                }

                return;
            }else{
                $(".mostrarCVV").css("display","none");
            }

            $('.tenercard_name').attr('disabled', 'disabled');
            $('.tenerccv_code').attr('disabled', 'disabled');
            $('.teneraddress').attr('disabled', 'disabled');
            $('.tenercard_number').attr('disabled', 'disabled');
            $('.tener_mes_expiracion').attr('disabled', 'disabled');
            $('.tener_ano_expiracion').attr('disabled', 'disabled');
            $('.tener_nombre_tarjeta_detalle').attr('disabled', 'disabled');
            $('.tener_correo_tarjeta_detalle').attr('disabled', 'disabled');     
            $('.tener_pais_tarjeta_detalle').attr('disabled', 'disabled');     
            $('.tener_ciudad_tarjeta_detalle').attr('disabled', 'disabled');     
            $('.tener_telefono_tarjeta_detalle').attr('disabled', 'disabled');     
            $('.tener_codigo_postal_tarjeta_detalle').attr('disabled', 'disabled');     
            $('.tener_direccion_tarjeta_detalle').attr('disabled', 'disabled'); 
            //$('.tenercobro_automatico').attr('disabled', 'disabled');
            $('.tipoPasarelaPago').attr('disabled', 'disabled');    

            idSelectCard = selectedValue;

            $.get(base_url + 'system/get_payment_method_by_id/'+selectedValue, function(data) {

                try {

                    var info = JSON.parse(data);
                    //console.log(info);

                    if(info.type == "success")
                    {
                        $(".OpcionesStripe").css("display","");

                        $(".tipoPasarelaPago").val(info.data.tipo_pasarela_pago);

                        $(".tenercard_name").val(info.data.titular_tarjeta);
                        $(".tenerccv_code").val(info.data.codigo_ccv);
                        $(".teneraddress").val(info.data.direccion);

                        let numero_tarjeta = "";

                        if(isEmpty(info.data.numero_tarjeta) == false)
                        {
                            numero_tarjeta = info.data.numero_tarjeta.slice(-4); 
                        }

                        $(".tenercard_number").val(numero_tarjeta);

                        //$(".tenercard_number").val(info.data.numero_tarjeta);

                        $(".tener_mes_expiracion").val(info.data.exp_month);

                        const year = info.data.exp_year;
                        const month = info.data.exp_month.toString().padStart(2, '0');
                        const day = '01';
                        
                        const momentFecha = moment(year+"-"+month+"-"+day, "YYYY-M-D");
                        const diasEnMes = momentFecha.daysInMonth();

                        const formattedDate = year+"-"+month+"-"+diasEnMes;

                        if(info.data.tipo_pasarela_pago == "Stripe")
                        {
                            $(".mostrarAnoStripe").css("display", "");
                            $(".mostrarAnoSquare").css("display", "none");
                        }else{
                            $(".mostrarAnoStripe").css("display", "none");
                            $(".mostrarAnoSquare").css("display", "");
                        }

                        $(".tener_ano_expiracion").val(year);

                        $(".tener_nombre_tarjeta_detalle").val(info.data.nombre_detalles);
                        $(".tener_correo_tarjeta_detalle").val(info.data.correo_detalles);
                        $(".tener_pais_tarjeta_detalle").val(info.data.pais_detalles);
                        $(".tener_ciudad_tarjeta_detalle").val(info.data.ciudad_detalles);
                        $(".tener_telefono_tarjeta_detalle").val(info.data.telefono_detalles);
                        $(".tener_codigo_postal_tarjeta_detalle").val(info.data.codigo_postal_detalles);
                        $(".tener_direccion_tarjeta_detalle").val(info.data.direccion_detalles);
        
                        //$('.tenercobro_automatico').prop('checked', info.data.cobro_automatico == 1? true:false);

                        //toastr.error(info.data);
                    }else{
                        toastr.error(info.data);
                        $(".tipoPasarelaPago").val("Stripe");
                        $(".tenercard_name").val("");
                        $(".tenerccv_code").val("");
                        $(".teneraddress").val("");
                        $(".tenercard_number").val("");
                        $(".tener_mes_expiracion").val(0);
                        $(".tener_ano_expiracion").val("");
                        $(".tener_nombre_tarjeta_detalle").val("");
                        $(".tener_correo_tarjeta_detalle").val("");
                        $(".tener_pais_tarjeta_detalle").val("");
                        $(".tener_ciudad_tarjeta_detalle").val("");
                        $(".tener_telefono_tarjeta_detalle").val("");
                        $(".tener_codigo_postal_tarjeta_detalle").val("");
                        $(".tener_direccion_tarjeta_detalle").val("");
       
                        //$('.tenercobro_automatico').prop('checked', false);

                        idSelectCard = -1;
                        $(".tenerSelectCard").val(idSelectCard);
                    }
                } catch (error) {
                    $(".tipoPasarelaPago").val("Stripe");
                    $(".tenercard_name").val("");
                    $(".tenerccv_code").val("");
                    $(".teneraddress").val("");
                    $(".tenercard_number").val("");
                    $(".tener_mes_expiracion").val(0);
                    $(".tener_ano_expiracion").val("");
                    $(".tener_nombre_tarjeta_detalle").val("");
                    $(".tener_correo_tarjeta_detalle").val("");
                    $(".tener_pais_tarjeta_detalle").val("");
                    $(".tener_ciudad_tarjeta_detalle").val("");
                    $(".tener_telefono_tarjeta_detalle").val("");
                    $(".tener_codigo_postal_tarjeta_detalle").val("");
                    $(".tener_direccion_tarjeta_detalle").val("");
                    //$('.tenercobro_automatico').prop('checked', false);
  
                    idSelectCard = -1;
                    $(".tenerSelectCard").val(idSelectCard);
                    toastr.error(error);
                }

            });
            
            //console.log('Selected value on change:', selectedValue);
        });

        $('.tipoPasarelaPago').change(function() {
            var selectedValue = $(this).val();
 
            if(selectedValue == "Stripe")
            {
                $(".OpcionesStripe").css("display", "");
                $(".MostrarSoloSquare").css("display", "none");
                $(".mostrarCVV").css("display", "");
            }else{
                $(".OpcionesStripe").css("display", "none");
                $(".MostrarSoloSquare").css("display", "");
                $(".mostrarCVV").css("display", "none");
    
            }
 
            //console.log('Selected value on change:', selectedValue);
        });
 
        $(".bottonPagarFactura").click(async function (e) {
            //e.preventDefault();
            
            idSelectPaymentGateway = $(".tener_id_pasarela_pago").val();

            var tener_mes_expiracion = "";
            var tener_ano_expiracion = "";
            var card_number = "";
            var cnon_tarjetas_square = "";

            var tipoPasarelaPago = $(".tipoPasarelaPago").val();

            if(idSelectCard <= -1)
            {
                toastr.error("Select a card");
                return;
            }
 
            //if(idSelectPaymentGateway <= 0)
            //{
            //    toastr.error("I can't pay, Contact administrator so I can enable a payment gateway in the option; setting > payment gateway");
            //    return;
            //}
            
            if(isEmpty(tipoPasarelaPago) == true)
            {
                toastr.error("!Payment method type is required¡");
                return;
            }

            if(isEmpty($(".tenercard_name").val()))
            {
                toastr.error("!Card name is required¡");
                return;
            }

            if(( idSelectCard == "0" || idSelectCard == 0) && tipoPasarelaPago == "Stripe" )
            {

                let number_card = $(".tenercard_number").val();

                if(isEmpty(number_card)){
                    toastr.error("!The card number is required¡");
                    return;
                }

                if(isEmpty($(".tenerccv_code").val()))
                {
                    toastr.error("!CCV code is required¡");
                    return;
                }

                if($('.tener_mes_expiracion').val() == 0 || $('.tener_mes_expiracion').val() == "0")
                {
                    toastr.error("!Select Expiration Month¡");
                    return;
                }
        
                if( isEmpty($('.tener_ano_expiracion').val())  )
                {
                    toastr.error("!Select a card expiration year¡");
                    return;
                }

                let fechaExpiracionAno = (
                    $('.tener_ano_expiracion').val()  || '0'
                ).padStart(2, '0');

                let fechaExpiracionMes = (
                $('.tener_mes_expiracion').val()  || '0'
                ).padStart(2, '0');

                const currentYear = (new Date().getFullYear() % 100)
                    .toString()
                    .padStart(2, '0'); // Últimos dos dígitos del año actual con dos dígitos

                const currentMonth = (new Date().getMonth() + 1)
                    .toString()
                    .padStart(2, '0'); // Mes actual con dos dígitos

                // Validación del año
                if (parseInt(fechaExpiracionAno, 10) < parseInt(currentYear, 10)) {
                    toastr.error("La fecha de expiración le año es inválida");
                    return;
                } else if (
                    parseInt(fechaExpiracionAno, 10) === parseInt(currentYear, 10)
                ) {
                    // El año es igual al actual, validar el mes
                    if (parseInt(fechaExpiracionMes, 10) < parseInt(currentMonth, 10)) {
                        // El mes es menor, la validación falla
                        toastr.error("La fecha de expiración el mes es inválida");
                        return;
                    }
                }
 
                tener_mes_expiracion = $(".tener_mes_expiracion").val();
                tener_ano_expiracion = $(".tener_ano_expiracion").val();

                card_number          = $(".tenercard_number").val();

            }

            if( ( idSelectCard == "0" || idSelectCard == 0) && tipoPasarelaPago == "Square" )
            {

                try {
                    //console.log("card");
                    //console.log(card_datos_square);

                    const token = await tokenize(card_datos_square);

                    if (token.status == "OK") {
                        console.log(token.token);

                        let details = token.details || {};
                        let card = details.card || {};

                        cnon_tarjetas_square = token.token;

                        //exp_month = card.expMonth;
                        //exp_year  = card.expYear;
                        //numero_tarjeta  = card.last4;

                        tener_mes_expiracion = card.expMonth;
                        tener_ano_expiracion = card.expYear;
                        card_number = card.last4;
 

                    } else {

                        if(Array.isArray(token.errors))
                        {

                            token.errors.forEach((data) => {
                                let {
                                    field,
                                    message,
                                    type,
                                } = data;

                                toastr.error(message);
                                return;
                            });

                            if(token.errors.length != 0)
                            {
                                return;
                            }

                        }

                    }

                    console.log("Payment Token:", token); // Use this token as source_id
                } catch (error) {
                    console.error(error);
                    toastr.error('Error: ' + error);
                    return;
                }

            }
 
            /*
            if( isEmpty($('.tener_nombre_tarjeta_detalle').val())  )
            {
                toastr.error("!Name is required¡");
                return;
            }

            if( isEmpty($('.tener_correo_tarjeta_detalle').val())  )
            {
                toastr.error("!Email is required¡");
                return;
            }

            if( isEmpty($('.tener_codigo_postal_tarjeta_detalle').val())  )
            {
                toastr.error("!Zip code is required¡");
                return;
            }

            if( isEmpty($('.tener_pais_tarjeta_detalle').val())  )
            {
                toastr.error("!Country is required");
                return;
            }

            if( isEmpty($('.tener_ciudad_tarjeta_detalle').val())  )
            {
                toastr.error("!City is required¡");
                return;
            }

            if( isEmpty($('.tener_telefono_tarjeta_detalle').val())  )
            {
                toastr.error("!Phone is required¡");
                return;
            }
            */

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

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

            //console.log(base_url + 'parnerts/add-parnert-post/');
            //console.log($( "#rform" ).serialize());
 
            var informacionEnviar = {
                card_id_select:idSelectCard,
                payment_gateway: idSelectPaymentGateway,
                payment_method:  "5",

                correo_electronico : correo_electronico,
                password : password,
                isLogin: true,
 
                //informacion de la tarjeta cuando card_id_select sea igual a 0
                card_name:      $(".tenercard_name").val(),
                ccv_code:       $(".tenerccv_code").val(),
                address:        $(".teneraddress").val(),
                card_number:    card_number,
                state:          $(".tenerestado").val(),
                descripcion:    $(".tenerDescripcion").val(),  
                //cobro_automatico:  $('.tenercobro_automatico').is(':checked'),

                mes_expiracion:  tener_mes_expiracion,
                ano_expiracion:  tener_ano_expiracion,

                //binding detalles
                nombre_tarjeta_detalle:         $(".tener_nombre_tarjeta_detalle").val(),
                correo_tarjeta_detalle:         $(".tener_correo_tarjeta_detalle").val(),
                codigo_postal_tarjeta_detalle:  $(".tener_codigo_postal_tarjeta_detalle").val(),
                pais_tarjeta_detalle:           $(".tener_pais_tarjeta_detalle").val(),
                ciudad_tarjeta_detalle:         $(".tener_ciudad_tarjeta_detalle").val(),
                telefono_tarjeta_detalle:       $(".tener_telefono_tarjeta_detalle").val(),
                direccion_tarjeta_detalle:      $(".tener_direccion_tarjeta_detalle").val(),

                cnon_tarjetas_square: cnon_tarjetas_square,
                tipoPasarelaPago:     tipoPasarelaPago,
            };
            
            console.log(JSON.stringify(informacionEnviar));
            //alert("return aqui abajo");
            //return;

            //console.log(base_url + 'system/payment-invoice-post/');
           
            $.post(base_url + 'system/payment-invoice-post-login', JSON.stringify(informacionEnviar)  ) //$( "#rform" ).serialize()
            .done(function (data) {

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

                    //window.location = base_url + 'parnerts/list_parnert/' + data;
                    //window.location = base_url + 'parnerts/list_parnert';

                }
                else {

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

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

                            toastr.success(info.data);

                            //window.location = info.redirect;

                            $(".pagarFactura").hide(); 
                            $(".ocultarLogin").removeAttr("hidden");

                            $(".ocultarLogin").show();

                            //$(".tenercard_name").val("");
                            //$(".tenerccv_code").val("");
                            //$(".teneraddress").val("");
                            //$(".tenercard_number").val("");

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

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

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

    </script>
{/block}
