document.addEventListener("DOMContentLoaded", function() {  
    const interest_ic = localStorage.getItem('tic');
    //const interest_cv = params.get("tcv");
    const amount = parseFloat(localStorage.getItem('monto').replace(/,/g, ''));
    console.log("Monto:", amount);
    const amount_inicial = parseFloat(localStorage.getItem('monto_inicial').replace(/,/g, ''));
    const modalidad= localStorage.getItem('moda');
    console.log("Modalidad:", modalidad)
    const months = parseFloat(localStorage.getItem('months'));
    console.log("Meses:", months);
    const fecha_inicio = localStorage.getItem('fechai');
    const interestic = interest_ic*0.01/12;
    //const interestcv = interest_cv*0.01/12;
    const amountt = 1*amount;
    
    let amounttotal;
    let pagostotal;
    let capital_ic;
    let moda;
    
    if(modalidad == "Aportación única"){
        amounttotal = 1*amount
        pagostotal = 1*amount
        capital_ic = 0
        moda = 1
    } else if(modalidad == "Aportación mensual"){
        amounttotal = 1*amount
        pagostotal = 1*amount*months
        capital_ic = amountt
        moda = 2
    }  else if(modalidad == "Mezcla de ambas"){
        amounttotal = 1*(amount+amount_inicial)
        pagostotal = 1*((amount*months)+amount_inicial)
        capital_ic = amountt
        moda = 3
        
    }
    
    console.log("Donacion mensual IC:", capital_ic);
    const acciones = amount/1000;


const interest = interest_ic*0.01/12;
const plazo = months;

const m = months;
//const m = month-1
localStorage.setItem( 'months', m );
// Vectores que utilizaremos en el loop que genera la tabla
  var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
  var inicio = [hoy.toLocaleDateString('es-ES', options)];
  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 numOfMonth = 1; // Número de días a sumar, puedes cambiarlo a lo que necesites.
  console.log(numOfMonth)
  
  
  //Function que solo añade meses a la fecha
  function addMonths(originalDate, monthsToAdd) {
  // Make a copy of the original date to avoid modifying it directly
  const newDate = new Date(originalDate);

  // Calculate the new month
  const currentMonth = newDate.getMonth();
  newDate.setMonth(currentMonth + monthsToAdd);

  return newDate.toLocaleDateString('es-ES', options);
}


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



let saldoord= [amounttotal];
//let saldogl = [aportacion_cv];
//let periodos = [0]
let pagop = [0];
//let pagoex = [-amountt];
//let saldototal = [amounttotal];
let interes = [0];
//let interes_g =[0];
//for (i = 0; i<m; i++){
//periodos[i+1] = periodos[i] + 1 ;
//fecha[i+1] = addMonths(i +1, new Date());  }
   
for (i = 0; i<=m; i++){
//capital_c[i+1] = (capital_c[i]*(1+interestic));
saldoord[i+1] = saldoord[i]*(1+interestic) + capital_ic;
//saldogl[i+1] = saldogl[i]+ capital_cv;
//saldototal[i+1] = saldoord[i+1]+saldogl[i+1];
//pagop[i+1] = saldogl[i]*interestcv;
//pagoex[i+1] = pagoex[i];
//interes_g[i+1] = saldogl[i]*interestcv;
interes[i+1] = saldoord[i]*(interestic); 
    }
    
 var pagosmensuales = pagop.slice(1, -1)
 let result = 0;
for (let i = 0; i < pagosmensuales.length; i++) {
  result += pagosmensuales[i];
}
console.log(result)
Ganancia = saldoord[m-1]+interes[m] - pagostotal

let pagoex = [];

if (moda === 1) {
    for (let i = 1; i <= m; i++) {
        pagoex.push(0);
    }
} else if (moda >= 2) {
    for (let i = 1; i <= m; i++) {
        pagoex.push(-amountt);
    }
}
console.log(pagoex)
pagoex[0]= -amounttotal
pagoex[m] = saldoord[m-1]+interes[m]

saldoord[m] = 0;
//saldogl[m] = 0;
//saldototal[m] = 0;
//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++){
  saldoord[i] = saldoord[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //saldogl[i] = saldogl[i].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //saldototal[i] = saldototal[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, ",");
  pagoex[i] = pagoex[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, ",");
      }
  //capital_g[0] = capital_g[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");  
  saldoord[0] = saldoord[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //saldogl[0] = saldogl[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //saldototal[0] = saldototal[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  pagoex[0] = pagoex[0].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", "Pagos", "Rendimiento", "Saldo Total", 
"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 = `$${pagoex[i]}`;
    row.insertCell(2).innerHTML = `$${interes[i]}`; 
    row.insertCell(3).innerHTML = `$${saldoord[i]}`;
    row.insertCell(4).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];
}

//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;
document.getElementById('tabla2').innerHTML = myData.innerHTML;
    let capital_c = [amounttotal];
    //let capital_g = [aportacion_cv];
    //let capital_t = [amounttotal];
    //let intg = [0]
    //let intord =[0]
    //let fechas = [0]
    //for (i = 0; i<months; i++){
    //fechas[i+1] = fechas[i] + 1 ;
      //  }
    //console.log(fechas)    
    for (i = 0; i<m; i++){
    capital_c[i+1] = capital_c[i]*(1+interestic)+capital_ic;
    //capital_g[i+1] = capital_g[i] + capital_cv//+ capital_cv*interestcv
    //capital_t[i+1] = capital_c[i] + capital_g[i]
        }
    
    

    
    pagos_totales = Ganancia + pagostotal
    x = pagos_totales - amountt*months + amount_inicial;
    y = pagostotal;
    //rentabilidad = (((pago_final/(amountt*months))-1)*100).toFixed(2)
    rentabilidad = parseFloat(interest_ic)
    neta = rentabilidad + 0.5
    dividendo = 100*rentabilidad/(months*12)
    //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
    
    c_ic = pagostotal.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)
    dividendo = dividendo.toFixed(2);
    //c_cv = aportacion_cv.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
    
    suma_pagos = pagos_totales.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    ganancia = Ganancia.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    rentab = rentabilidad.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    neta = neta.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, ",");
    aptotal = y.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //let icptg = (k_ic).toFixed(2)
    //icptg = icptg.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //const noproyecto = params.get("proyecto");
    //localStorage.setItem( 'proyecto', noproyecto );
    //const teso = params.get("tesoreria");
    //localStorage.setItem( 'tesoreria', teso );
    //document.querySelector('#payment').innerHTML = `$${payment}`
    //document.querySelector('#capital_saldos').innerHTML = `$${c_saldos}`
    //document.querySelector('#capital_ic').innerHTML = `$${c_ic}`
    //document.querySelector('#capital_cv').innerHTML = `$${c_cv}`
    //document.querySelector('#dividendo').innerHTML = `Dividendo = ${dividendo}`
    //document.querySelector('#pago_final').innerHTML = `$${pagofinal}`
    
  
    localStorage.setItem( 'cantidad', pagostotal);
    
    //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
    g = Ganancia.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //document.querySelector('#ganancia').innerHTML = `$${g}`
    //document.querySelector('#ganancia2').innerHTML = `$${g}`
    
    document.querySelector('#capital_v').innerHTML = `$${c_ic}`
    //document.querySelector('#capital_compuesto').innerHTML = `$${c_cv}`
    
    
    document.getElementById('acciones').textContent = accion;
    document.getElementById('acciones2').textContent = accion;
    document.getElementById('inversion').textContent = inversion;
    document.getElementById('capital').textContent = inversion;
    document.getElementById('inv').textContent = inversion;
    
    document.getElementById('dividendo').textContent = dividendo;
    document.getElementById('rentab').textContent = rentab;
    document.getElementById('tic').textContent = interest_ic;
    document.getElementById('months').textContent = months;
    console.log(dividendo)
});
    