function computeLoan(){
    const params = new URLSearchParams(document.location.search);
    const interestic = params.get("tic");
    const com = params.get("c");
    const amount = document.querySelector('#amount').value;
    const periodo = document.querySelector('#pago').value;
    const plazo = document.querySelector('#plazo').value;
    const fecha_inicio = document.querySelector('#fecha_inicio').value;
    let n = Math.floor(plazo / periodo); // Redondear hacia abajo
    
    const amountt = 1 * amount;
    //const date = new Date();
    let comision = com * 0.01;
    let interes = interestic * 0.01 * (periodo / 360);
    let payment = amountt * (1+comision) * interes / (1 - Math.pow(1 + interes, -n));
    
    // Utilizar el valor redondeado de n en los cálculos
    payment = amountt * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
    let d = payment*n
    let cost = (d/amountt-1)*100
    
   // Vectores que utilizaremos en el loop que genera la tabla
    var hoy = new Date(fecha_inicio);
    var fecha = [hoy.toLocaleDateString('es-ES', options)];
    var periodos = [0];

    // Creemos una función que nos permita sumar periodos
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    var numOfDays = periodo; // Número de días a sumar, puedes cambiarlo a lo que necesites.

    function addDays(numOfDays, date) {
      date.setDate(date.getDate() + numOfDays);
      return date.toLocaleDateString('es-ES', options);
    }

    // Un loopsillo de periodos y fechas. Lo separamos por obvias razones
    for (var i = 0; i <= n; i++) {
      periodos[i + 1] = periodos[i] + 1;
      fecha[i + 1] = addDays(numOfDays * (i + 1), new Date(hoy)); // Sumamos el total de días acumulados hasta el momento
    }

    amort = [0]
    int = [0]
    saldo_inicial = [amountt*(1+comision)];
    saldo_final = [amountt*(1+comision)];
    pago = [0]
    iva = [0]
    //Nuestro loop con ecuaciones en diferencia
    for (i = 0; i<=n; i++){
      pago[i+1] = payment;
      int[i+1] = saldo_final[i]*interes/1.16;
      iva[i+1] = int[i+1]*0.16;
      amort[i+1] = payment - int[i+1] - iva[i+1];
      saldo_inicial[i+1] = saldo_final[i] + int[i] + iva[i];
      saldo_final[i+1] = saldo_final[i] - amort[i+1];      
        }
    //Otro loopsillo para añadir formato:    
    for (i=0; i<=n; i++){
      saldo_inicial[i+1] = saldo_inicial[i+1].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      saldo_final[i+1] = saldo_final[i+1].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      int[i+1] = int[i+1].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      iva[i+1]  = iva[i+1].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      amort[i+1]  = amort[i+1].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      pago[i+1] = pago[i+1].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
          }    
    //Ahora crearemos una tabla en HTML con la anterior información
      var headers = ["Periodo",
      "Saldo Inicial", "Interés" , "I.V.A.",  "Amortización", "Pago parcial", 
      "Saldo Final", "Fecha"];
      var table = document.createElement("TABLE");  //makes a table element for the page
          
      for(var i = 0; i <= n; i++) {
          var row = table.insertRow(i);                       
          row.insertCell(0).innerHTML = periodos[i];
          row.insertCell(1).innerHTML = saldo_inicial[i];
          row.insertCell(2).innerHTML = int[i];
          row.insertCell(3).innerHTML = iva[i];
          row.insertCell(4).innerHTML = amort[i]; 
          row.insertCell(5).innerHTML = pago[i];
          row.insertCell(6).innerHTML = saldo_final[i]; 
          row.insertCell(7).innerHTML = fecha[i];       
      }

      var header = table.createTHead();
      var headerRow = header.insertRow(0);
      for(var i = 0; i < headers.length; i++) {
          headerRow.insertCell(i).innerHTML = headers[i];
      }
      
      const myData = table
      console.log(myData.innerHTML)
      localStorage.setItem( 'tabla', myData.innerHTML );document.getElementById('tabla').innerHTML = myData.innerHTML;      
      localStorage.setItem( 'fecha_inicio', fecha_inicio );document.getElementById('fecha_inicio').textContent = fecha_inicio
      console.log(fecha_inicio)
    /*
    let capital_c = [capital_ic];
    let capital_g = [capital_cv];
    let capital_t = [amount];
    let fechas = [0]
    for (i = 0; i<months; i++){
    fechas[i+1] = fechas[i] + 1 ;
        }
    console.log(fechas)    
    for (i = 0; i<=months; i++){
    capital_c[i+1] = capital_c[i]*(1+interestic);
    capital_g[i+1] = capital_g[i] //+ capital_cv*interestcv
    capital_t[i+1] = capital_c[i] + capital_g[i]
        }
    
    console.log(capital_t)

    
    x = pagos_totales - amount
    rentabilidad = (100*((payment_cv*months + capital_cv + capital_ic*(1+interestic)**(months))/amountt-1)).toFixed(2)
    */
    //regedit to add a comma after every three digits
    //payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); //\B looks for a word boundary, ? says what to look for, \d looks for 3 digits in a row
    payment = payment.toLocaleString(undefined, {maximumFractionDigits: 2});
    parcialidades = n.toLocaleString(undefined, {maximumFractionDigits: 2});
    desembolso = d.toLocaleString(undefined, {maximumFractionDigits: 2});
    linea = amountt.toLocaleString(undefined, {maximumFractionDigits: 2});
    costo = cost.toLocaleString(undefined, {maximumFractionDigits: 2});
    p = periodo.toLocaleString(undefined, {maximumFractionDigits: 0});
    term = plazo.toLocaleString(undefined, {maximumFractionDigits: 0});
    /*c_ic = capital_ic.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); //\B looks for a word boundary, ? says what to look for, \d looks for 3 digits in a row
    capitalcv = capital_cv.toFixed(2)
    c_cv = capitalcv.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); //\B looks for a word boundary, ? says what to look for, \d looks for 3 digits in a row
    pagofinal = pago_final.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    suma_pagos = pagos_totales.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    ganancia = x.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    rentab = rentabilidad.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    saldoic = (capital_ic*(1+interestic)**(months)).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    accion = acciones.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    inversion = (1000*acciones).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    */
    document.querySelector('#payment').innerHTML = `$${payment}`
    document.querySelector('#payment2').innerHTML = `$${payment}`
    document.querySelector('#payment3').innerHTML = `$${payment}`
    
    //document.querySelector('#suma_pagos').innerHTML = `$${suma_pagos}`

    document.querySelector('#parcialidades').innerHTML = `${n}`
    document.querySelector('#parcialidades2').innerHTML = `${n}`
    document.querySelector('#desembolso').innerHTML = `$${desembolso}`
    document.querySelector('#desembolso2').innerHTML = `$${desembolso}`
    document.querySelector('#linea').innerHTML = `$${linea}`
    document.querySelector('#costo').innerHTML = `${costo}%`
    document.querySelector('#periodo2').innerHTML = `${p}`
    document.querySelector('#plazo2').innerHTML = `${term}`
    localStorage.setItem( 'pago_parcial', payment );
    /*document.querySelector('#rentabilidad').innerHTML = `${rentab}%`
    localStorage.setItem( 'acciones', accion );
    localStorage.setItem( 'inversion', inversion );
    localStorage.setItem( 'capital_compuesto', c_ic );
    localStorage.setItem( 'capital_v', c_cv );
    localStorage.setItem( 'rentab', rentab );
    
    
    //document.querySelector('#rentabilidad').innerHTML = `Rentabilidad = ${rentab}%`
    //document.querySelector('#saldoic').innerHTML = `Valor futuro del interés compuesto = $${saldoic}`
   // document.querySelector('#icptg').innerHTML = `Rentabilidad = ${icptg}%`
    //let x = (payment_cv*months + capital_cv + payment_s*months + capital_ic*(1+interestic)**(months) + amount*0.1*interestd*months + 0.1*amount-amount).toFixed(2)
    //P*(1+tasa_comision)*interes/(1-(1+interes)**(-n))
    const ctx = document.getElementById('myChart');
    const pagos = document.getElementById('suma_pagos');
    //Ganancia = payment_cv*months + capital_cv + payment_s*months + capital_ic*(1+interestic)**(months) + amount*0.1*interestd*months + 0.1*amount-amount
    Ganancia = payment_cv*months + capital_cv + capital_ic*(1+interestic)**(months)-amount
    g = Ganancia.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    document.querySelector('#ganancia').innerHTML = `$${g}`
    document.querySelector('#ganancia2').innerHTML = `$${g}`
    Highcharts.chart('container', {
      chart: {
        type: 'column'
      },
      title: {
        text: 'Inversión vs. Ganancia'
      },
      subtitle: {
        text: 'A continuación se muestran inversión, ganancia y pago total:'
      },
      xAxis: {
        categories: [
          'Ganancia',
          'Inversión',
          'Pago Total'
        ],
        crosshair: true
      },
      yAxis: {
        title: {
          useHTML: true,
          text: 'Miles de pesos mexicanos, m.n.'
        }
      },
      tooltip: {
        headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
        pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
          '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
        footerFormat: '</table>',
        shared: true,
        useHTML: true
      },
      plotOptions: {
        column: {
          pointPadding: 0.2,
          borderWidth: 0
        }
      },
      series: [{
        name: 'Inversión',
        data: [parseFloat(amount)],
        
    
      }, {
        name: 'Ganancia',
        data: [x],
        
      }, {
        name: 'Pago Total',
        data: [pagos_totales],
        
    
      }]
    });
    
    Highcharts.chart('series', {

    title: {
        text: 'Capital y ganancias'
    },

    subtitle: {
        text: 'Comportamiento del capital y ganancias totales en el tiempo'
    },

    yAxis: {
        title: {
            text: 'Miles de pesos, m.n.'
        }
    },

    xAxis: {
        accessibility: {
            rangeDescription: 'Periodos en meses'
        }
    },

    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
    },

    plotOptions: {
        series: {
            label: {
                connectorAllowed: false
            },
            pointStart: -1
        }
    },

    series: [{
        name: 'Capital',
        data: capital_t
    }//, {
     //   name: 'Other',
     //   data: [21908, 5548, 8105, 11248, 8989, 11816, 18274,
     //       17300, 13053, 11906, 10073]
    //}
    ],

    responsive: {
        rules: [{
            condition: {
                maxWidth: 500
            },
            chartOptions: {
                legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom'
                }
            }
        }]
    }

});
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };  
    function addMonths(numOfMonths, date = new Date()) {
        date.setMonth(date.getMonth() + numOfMonths);
        return date.toLocaleDateString('es-ES', options);
    }  
        
const interest = params.get("tic")*0.01/12;

//const pago = parseFloat(document.querySelector('#pago').value);
//const monto = parseFloat(document.querySelector('#monto').value);
//const interestic = parseFloat(params.get("tic")/1200);  
//const interestcv = parseFloat(params.get("tcv")/1200);
const m = parseFloat(document.querySelector('#months').value);
//const m = month-1
localStorage.setItem( 'months', m );


//let fechas = [currentDate]
//let periodos = [0]
//let fechas = [new Date().toLocaleDateString('es-ES', options)]
let fecha = [new Date().toLocaleDateString('es-ES', options)]
monto = amount
let saldo = [capital_ic]
let periodos = [0]
let pagop = [0]
let interes = [0]
let interes_g =[0]
for (i = 0; i<m; i++){
periodos[i+1] = periodos[i] + 1 ;
fechas[i+1] = addMonths(i +1, new Date());

    }
console.log(fechas)    
for (i = 0; i<=m; i++){
//capital_c[i+1] = (capital_c[i]*(1+interestic));
saldo[i+1] = saldo[i]*(1+interestic) 
pagop[i+1] = capital_cv*interestcv
interes_g[i+1] = capital_cv*interestcv
interes[i+1] = saldo[i]*interestic 
    }
saldo[m] = saldo[m-1]*(1+interestic)  + capital_g[i]   
//pagop[m] = saldo[m]    
//pagop[m] = saldo[m] 
//saldonuevo = [saldo]
//for (i = 0; i<=m; i++){ 
//saldonuevo[i] = saldonuevo[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//pagop[i] = pagop[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

pagop[m] = saldo[m] + pagop[m-1]
for (i=1; i<=m; i++){
  saldo[i] = saldo[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  interes[i] = interes[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  pagop[i] = pagop[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  capital_g[i] = capital_g[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  interes_g[i] = interes_g[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      }
     

//fecha[i] = fechas[i].getUTCDay() + "/" + fechas[i].getUTCMonth()+1+"/"  + fechas[i].getUTCFullYear();
//fecha[i]= fechas[i];
    
var headers = ["Periodo",
"Rendimiento Ordinario", "Saldo Global" , "Rendimiento Global",  "Pago", "Saldo Ordinario", 
"Fecha"];
var table = document.createElement("TABLE");  //makes a table element for the page
    
for(var i = 0; i <= m; i++) {
    var row = table.insertRow(i);                       
    row.insertCell(0).innerHTML = periodos[i];
    row.insertCell(1).innerHTML = interes[i];
    row.insertCell(2).innerHTML = capital_g[i];
    row.insertCell(3).innerHTML = interes_g[i];
    row.insertCell(4).innerHTML = pagop[i]; 
    row.insertCell(5).innerHTML = saldo[i];
    row.insertCell(6).innerHTML = fechas[i];
    
    
}

var header = table.createTHead();
var headerRow = header.insertRow(0);
for(var i = 0; i < headers.length; i++) {
    headerRow.insertCell(i).innerHTML = headers[i];
}

//document.body.append(table);
//var myData = [header.innerHTML, row.innerHTML]
const myData = table
console.log(myData.innerHTML)
localStorage.setItem( 'tabla', myData.innerHTML );document.getElementById('tabla').innerHTML = myData.innerHTML;
*/

}


