document.addEventListener("DOMContentLoaded", function() {
  const tic= parseFloat(localStorage.getItem('tic'));
  const tcv = parseFloat(localStorage.getItem('tcv'));
  const monto = parseFloat(localStorage.getItem('monto').replace(/,/g, ''));
  const plzo = parseFloat(localStorage.getItem('plazo'));
  const kic = parseFloat(localStorage.getItem('kic'));
  const kcv = parseFloat(localStorage.getItem('kcv'));
  const fechai = localStorage.getItem('fechai');
  const monto_inicial = localStorage.getItem('monto_inicial'); 
  const modldd = localStorage.getItem('moda'); 
  
 if(modldd === 'Inversión Balloon'){
  var interestic = tic
  var amount = monto
  var residual = kic
  var periodo = kcv
  var plazo = plzo
  var fecha_inicio = fechai
  var n = Math.floor(plazo / periodo); // Redondear hacia abajo

  const amountt = 1 * amount;
    
  var months = plazo/30
  
  //const date = new Date();
  let interes = interestic * 0.01 * (periodo / 360);
  const R=residual*0.01*amountt/Math.pow(1 + interes, n)
  let payment = (amountt-R) * interes / (1 - Math.pow(1 + interes, -n));

  // Utilizar el valor redondeado de n en los cálculos
  payment = (amountt-R) * interes / (1 - Math.pow(1 + interes, -n));
  

 // Vectores que utilizaremos en el loop que genera la tabla
 var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
  var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
  var inicio = [hoy.toLocaleDateString('es-ES', options)];
  var fecha = [hoy];
  var periodos = [0];

  // Creemos una función que nos permita sumar periodos
  
  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;
  }

  // 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
  }
  fecha[0] = addDays(numOfDays * (0), new Date(hoy)); // Sumamos el total de días acumulados hasta el momento
  amort = [0]
  int = [0]
  saldo_inicial = [amountt];
  saldo_final = [amountt];
  pago = [0]
  

  //Nuestro loop con ecuaciones en diferencia
  for (i = 0; i<=n; i++){
    pago[i+1] = payment;
    int[i+1] = saldo_final[i]*interes;
    amort[i+1] = payment - int[i+1];
    saldo_inicial[i+1] = saldo_final[i] + int[i+1];
    saldo_final[i+1] = saldo_final[i] - amort[i+1];
      }
   pago[n] = saldo_inicial[n]
   saldo_final[n] = 0
   amort[n] = pago[n] -int[n]
  
  
  //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, ",");
    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, ",");
        }
    
  saldo_inicial[0] = saldo_inicial[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  saldo_final[0] = saldo_final[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");    
  
  

 for (var i = 0; i <= n; i++) {
    fecha[i] = fecha[i].toLocaleDateString('es-ES', options)
  }
  console.log(payment*(n-1));
  let d = payment*(n-1)+ parseFloat(saldo_inicial[n].replace(/,/g, ''));
  console.log(d);
  
  let cost = (d/amountt-1)*100;
  
  Ganancia = d-amount
    KmasR = d
    rendimientostotal = Ganancia.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    capitalrendimiento = KmasR.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", "Rendimiento", "Pago", "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 = `$${pago[i]}`;
        row.insertCell(4).innerHTML = `$${saldo_final[i]}`;
        row.insertCell(5).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;
    
   var aportacion_ic = amount
   var aportacion_cv = 0.00
   var pagos_totales = amount
   var capital_ic = amount
   var amounttotal = amount
    
    }
else{
    var interest_ic = tic;
    var interest_cv = tcv
    var amount = monto;
    var months = plzo;
    var k_ic= kic;
    var k_cv = kcv;
    var fecha_inicio = fechai; 
    var amount_inicial = monto_inicial;
    var modalidad = modldd
    const interestic = interest_ic*0.01/12;
    const interestcv = interest_cv*0.01/12;
    const amountt = 1*amount;
    
    var amounttotal;
    var pagostotal;
    var aportacion_ic;
    var aportacion_cv;
    var capital_ic;
    var capital_cv;
    var moda;
    
    if(modalidad == "Aportación única"){
        amounttotal = 1*amount
        pagostotal = 1*amount
        aportacion_ic= amounttotal*k_ic/100
        aportacion_cv = amounttotal*k_cv/100
        capital_ic = 0
        capital_cv = 0
        moda = 1
    } else if(modalidad == "Aportación mensual"){
        amounttotal = 1*amount
        pagostotal = 1*amount*months
        aportacion_ic= amounttotal*k_ic/100
        aportacion_cv = amounttotal*k_cv/100
        capital_ic = amounttotal*k_ic/100
        capital_cv = amounttotal*k_cv/100
        moda = 2
    }  else if(modalidad == "Mezcla de ambas"){
        amounttotal = 1*(amount+amount_inicial)
        pagostotal = 1*((amount*months)+amount_inicial)
        aportacion_ic= amounttotal*k_ic/100
        aportacion_cv = amounttotal*k_cv/100
        capital_ic = amount*k_ic/100
        capital_cv = amount*k_cv/100
        moda = 3
    }
    
    console.log("Donacion mensual IC:", capital_ic)
    console.log("Donacion mensual CV:",capital_cv)
    console.log(" IC:", aportacion_ic)
    console.log("CV:",aportacion_cv)
    
    
    let capital_cvtotal = (amount+amount_inicial)*k_cv/100;


    const interest = interestic*0.01/12;
    const plazo = months;
    
    const m = months
    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= [aportacion_ic];
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++){
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 = saldototal[m-1]+interes[m] + result - pagostotal

let pagoex = [];

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

saldoord[m] = 0;
saldogl[m] = 0;
saldototal[m] = 0;
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",
"Saldo Ordinario", "Rendimiento Ordinario", "Saldo Global", "Rendimiento mensual", "Pagos", "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 = `$${saldoord[i]}`;
    row.insertCell(2).innerHTML = `$${interes[i]}`;
    row.insertCell(3).innerHTML = `$${saldogl[i]}`;
    row.insertCell(4).innerHTML = `$${pagop[i]}`; 
    row.insertCell(5).innerHTML = `$${pagoex[i]}`; 
    row.insertCell(6).innerHTML = `$${saldototal[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];
}

//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;
    let capital_c = [aportacion_ic];
    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;
}
        
    const acciones = amount/1000;
    rentabilidad = parseFloat(tic)
    neta = rentabilidad + 0.5
    dividendo = 100*rentabilidad/(months*12)
    
    c_ic = aportacion_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
    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, ",");
    
    localStorage.setItem('fecha', fecha_inicio)
    localStorage.setItem('plazo', months)
    localStorage.setItem( 'tic', interest_ic);
    localStorage.setItem( 'tcv', interest_cv);
    localStorage.setItem( 'kic', k_ic);
    localStorage.setItem( 'kcv', k_cv);
    localStorage.setItem( 'mod', modldd);
    localStorage.setItem( 'cantidad', amounttotal);
    

    
    
    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)
    
    let textMasDe100000 = document.getElementById("text-mas-de-100000");
    let textMenosDe100000 = document.getElementById("text-menos-de-100000");
    
    if (amounttotal > 100000) {
        textMasDe100000.style.display = "block";
        textMenosDe100000.style.display = "none";
    } else {
        textMasDe100000.style.display = "none";
        textMenosDe100000.style.display = "block";
    }
    
    });