const text_color_button = "#F9F9F9";
const background_color_button =  "#000000";
const errores = {
    afinanciar:"El mínimo a financiar son 250 y el máximo permitido son 21.000",
    aportacion: "La aportación debe estar entre 0 y 21000",
    nombre:"El nombre es requerido",
    tel1:"El teléfono es requerido",
    correo:"El correo es requerido",
    acepto:"Debe aceptar los términos y condiciones"
}
const placeholders = {
    afinanciar:"Escriba el importe a financiar",
    aportacion: "Cuánto aportará",
    nombre:"Nombre y Apellidos del Paciente",
    tel1:"Teléfono del Paciente",
    correo:"Correo electrónico del Paciente",
    acepto:"Acepto la política de privacidad.",
}
const getConfiguration = token => {
    let data = {
        "id_cliente": 515,
        "id_tarifa": 146,
        "text1": "Calcula tu cuota",
        "text11": "(pulsa aquí)",
        "text2": "Gracias por su interés. Le hemos remitido un eMail con la simulación que ha solicitado.",
        "text3": "Si está interesado en iniciar el trámite para solicitar su financiación, debe indicárselo a su centro médico.",
        "url": "https:\/\/www.simuladortmf.com\/",
        "logo1": "https://www.tumedicinafinanciada.com/tmf/uploads/logo.png",
        "logo2": "https:\/\/simuladortmf.com\/applettmf\/logo.gif",
        "color1": "f9f9f9",
        "color2": "f9f9f9",
        "activo": 1
    };
    return data;
    /*
    const getConfiguration = async token => {
        let data = await fetch('https://www.simuladortmf.com/api/?token=ywkwBeKjYxL33czQAwhAF5tLFtremPpsnjbJkj8z&accion=applet')
              .then(response => response.json())
              .then(data => data);
        return data;
    }    
    */
}
const checkError = element => {
    let name = element.name;
    let texto_de_error = errores[name];
    let label = document.querySelector(".error_" + name);
    label.innerText = isValid(element) ? '' : texto_de_error;
}
const isValid = element => {
    let form = element.closest('form');
    return form[element.name].checkValidity();
}
const financiaOperacion = token => {
    let conf = getConfiguration(token);
    let elementos = `
        
        
            ${conf.text1 || 'financiar tu operacion?'}
            
        
        
     
    
    `;
    let div = document.createElement("div");
    div.id = "financiacion_1234";
    let body = document.querySelector("body");
    body.appendChild(div);
    document.getElementById('financiacion_1234').innerHTML = elementos;
}
const enviarPeticion = async element => {
    let form = element.closest('form');
    let inputs = form.querySelectorAll('input');
    let validated = true;
    let URL_PETICION = ''; //URL A LA QUE SE HARÁ LA PETICIÓN POR POST
    let data = {};
    inputs.forEach(element => {
        if (element.checkValidity() == false) {
            validated = false;
        }
        data[element.name] = element.value;
    });
    if (validated == false) {
        alert("Debe rellenar todos los campos de una forma válida");
        return false;
    }
    document.querySelector('.financia_form_1').style['display'] = 'none';
    document.querySelector('.financia_form_2').style['display'] = 'block';
    document.getElementById("financiacion_12345_enlace").innerText = 'CALCULANDO SIMULACIÓN...'
    let url = await fetch("https://simuladortmf.com/informe.php", {
        method:"POST",
        body:JSON.stringify(data)
    })
    .then(response => response.text())
    .then(response => {
        document.getElementById("financiacion_12345_enlace").setAttribute("data-href", response);
        document.getElementById("financiacion_12345_enlace").disabled = false;
        document.getElementById("financiacion_12345_enlace").innerText = 'VISUALIZAR SIMULACIÓN';
        return response
    })
    console.log(url);
    
}
const marcar = _ => {
    document.getElementById("acepto").checked = true;
}
const cambiarMini = _ => {
    let element = document.querySelector('.financia_1234');
    element.style.display = 'none';
    let element2 = document.querySelector('.financia_12345');
    element2.style.display = 'block';
}
const cambiarMega = _ => {
    let element = document.querySelector('.financia_1234');
    element.style.display = 'block';
    let element2 = document.querySelector('.financia_12345');
    element2.style.display = 'none';
}
const realizar_otra_simulacion = _ => {
    let form = document.querySelector('.financia_form_1');
    let inputs = form.querySelectorAll('input[type="text"], input[type="number"], input[type="email"]');
    inputs.forEach(element => {
        element.value = "";
    });
    document.querySelector('.financia_form_2').style['display'] = 'none';
    document.querySelector('.financia_form_1').style['display'] = 'block';
}
const visualizar_pdf = _ => {
    let enlace = document.querySelector('.financiacion_12345_enlace');
    let ruta = enlace.dataset.href;
    if (ruta.endsWith('/')) {
        ruta = ruta.slice(0, -1);
    }
    window.open(ruta, '_blank');
}
window.addEventListener("load", _ => financiaOperacion("ywkwBeKjYxL33czQAwhAF5tLFtremPpsnjbJkj8z"));
function validarRango() {
    const inputImporte = document.getElementById("afinanciar");
    const inputAportacion = document.getElementById("aportacion");
    const valorImporte = parseInt(inputImporte.value??0, 10);
    const valorAportacion = parseInt(inputAportacion.value??0, 10);
	const resultado= valorImporte - valorAportacion;
   		if (valorImporte < 250 || valorImporte > 21000) {
                alert("El número debe estar entre 250 y 21,000 €");
                inputImporte.value = "";
                inputAportacion.value = "";
        }
        if (resultado <= 0 ) {
                alert("La cantidad a financiar debe ser mayor a 0 €");
                inputImporte.value = "";  
                inputAportacion.value = "";
        }
	
}