document.addEventListener("DOMContentLoaded", function() {
   var rowData= localStorage.getItem('rowData');
   
    // Parse the JSON string into a JavaScript object
    const rowDataObj = JSON.parse(rowData);

    console.log(rowDataObj)
    //////Variables para el cálulo///
    const kic = rowDataObj["kic"];
    console.log("kic:", kic)
    const kcv = rowDataObj["kcv"];
    console.log("kcv:", kcv)
    const tic = rowDataObj["tic"];
    console.log("tic:", tic)
    const monto = rowDataObj["Monto a Aportar"];
    console.log("Monto inversión:", monto)
    const tcv = parseFloat(rowDataObj["tcv"]);
    console.log("tcv:", tcv)
    const plzo= parseFloat(rowDataObj["Plazo de inversión"]);
    console.log("Plazo:", plzo)
    const modldd = rowDataObj["Modalidad de Inversión"];
    console.log(modldd)
    document.getElementById("modalidadinv").textContent = modldd
    const monto_inicial = rowDataObj["Monto Inicial a Aportar"];
    console.log("Monto inicial:", monto_inicial)
    const fechai= rowDataObj["Fecha de inicio"];
    console.log("Fecha de inicio:", fechai)
    
    
    const interest_ic = parseFloat(tic)
    const interest_cv = parseFloat(tcv)
    const amount = parseFloat(monto.replace(/,/g, ''));
    let amount_inicial
    console.log("Monto:", amount);
    if(modldd == "Mezcla de ambas"){
        const monto_inicial = parseFloat(rowDataObj["Monto Inicial a Aportar"].replace(/,/g, ''));
        console.log("Monto inicial:", monto_inicial)
        amount_inicial = monto_inicial;
    } else {
        amount_inicial = 0
    }
    console.log("Monto Inicial:", amount_inicial);
    const k_ic = parseFloat(kic)
    const k_cv = parseFloat(kcv)
    const months = parseFloat(plzo)
    console.log("Meses:", months);
    let fecha_inicio
    if(fechai === undefined){
        fechainicio = new Date()
        fecha_inicio = `${fechainicio.getFullYear()}-${fechainicio.getMonth() + 1}-${fechainicio.getDate()}`;
    } else {
        fecha_inicio = fechai
    } 
    const interestic = interest_ic*0.01/12;
    const interestcv = interest_cv*0.01/12;
    const amountt = 1*amount;
    
    let amounttotal;
    let pagostotal;
    let aportacion_ic;
    let aportacion_cv;
    let capital_ic;
    let capital_cv;
    let modalidad;
    
    if(modldd == "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
        modalidad = 1
    } else if(modldd == "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
        modalidad = 2
    }  else if(modldd == "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
        modalidad = 3
        
    }
    
    
    console.log("Modalidad numero:", modalidad)
    console.log("Donacion mensual IC:", capital_ic)
    console.log("Donacion mensual CV:",capital_cv)
    //const amounttotal = 1*(amount+amount_inicial); 
    //const date = new Date();
    const acciones = amount/1000;
    //et capital_ic = amountt*k_ic/100;
    //let capital_cv = amountt*k_cv/100;
    //let capital_ictotal = (amountt+amount_inicial)*k_ic/100;
    //let capital_cvtotal = (amount+amount_inicial)*k_cv/100;


const interest = interest_ic*0.01/12;
const plazo = months;
document.getElementById("plazodeinv").textContent = plazo +" meses";

const m = months
localStorage.setItem( 'totalnumeropagos', plazo);

// 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, '\/'));
  const inicio = [hoy.toLocaleDateString('es-ES', options)];
  var fecha = [hoy];
  var periodos = [0];
  
  // Creemos una función que nos permita sumar periodos
  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;
}


  // 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 pagop = [0];
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;
interes_g[i+1] = saldogl[i]*interestcv;
interes[i+1] = saldoord[i]*(interestic); 
    }

function findNearestDate(dates) {
    // Get the current date
    var currentDate = new Date();
    
    // Initialize variables to store the nearest date and its difference
    var nearestDate = null;
    var nearestDifference = Infinity;
    
    // Loop through each date in the array
    for (var i = 0; i < dates.length; i++) {
        // Convert the date string to a Date object
        var date = new Date(dates[i]);
        
        // Calculate the difference between the current date and the date in the array
        var difference = date - currentDate;
        
        // If the difference is negative, it means the date is in the past, so we ignore it
        if (difference < 0) {
            continue;
        }
        
        // If the current difference is smaller than the previous smallest difference, update nearest date
        if (difference < nearestDifference) {
            nearestDifference = difference;
            nearestDate = date;
        }
    }
    
    // Return the nearest date
    return nearestDate;
}

// Example usage
var nearestDate = findNearestDate(fecha);
console.log("Nearest upcoming date:", nearestDate);

function contarFechasPasadas(fechas) {
    let fechaActual = new Date();
    let contador = 0;

    for (let i = 0; i < fechas.length; i++) {
        let fecha = new Date(fechas[i]);
        if (fecha < fechaActual) {
            contador++;
        }
    }

    return contador;
}


let fechasPasadas = parseFloat(contarFechasPasadas(fecha));
console.log("Número de fechas pasadas: " + fechasPasadas);
localStorage.setItem( 'fechasCounter', fechasPasadas );

const numfila = fechasPasadas
const numerador = parseFloat(contarFechasPasadas(fecha.slice(1)))


 for (var i = 0; i <= m; i++) {
    fecha[i] = fecha[i].toLocaleDateString('es-ES', options)
  }   
 
 console.log(fecha)
 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
KmasR = saldototal[m-1]+interes[m] + result 
rendimientostotal = Ganancia.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
capitalrendimiento = KmasR.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById("totalrendi").textContent = `$${rendimientostotal}`;
document.getElementById("kmasr").textContent = `$${capitalrendimiento}`;

let pagoex = [];

if (modalidad === 1) {
     for (let i = 1; i <= m; i++) {
        pagoex[i]= 0+pagop[i];
    }
} else if (modalidad >= 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[0] = pagop[0].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, ",");
  interes_g[i] = interes_g[i].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, ",");

    


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];
}   
const myData = table
console.log(myData.innerHTML)
localStorage.setItem( 'tabla', myData.innerHTML );document.getElementById('tabla').innerHTML = myData.innerHTML;

let invactual
if(modalidad == 1){
        invactual =amount
    } else if(modalidad == 2){
        invactual = amount*(numfila)
    }  else if(modalidad == 3){
        invactual = amounttotal*(numfila)
    }

const invnow= invactual.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const yieldactual = parseFloat(saldototal[numfila].replace(/,/g, ''))+parseFloat(pagop[numfila]);
saldonow = yieldactual.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.querySelector('#invactual').innerHTML = `$${invnow}`;

suma_pagos = pagostotal.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById("totalinversion").textContent = `$${suma_pagos}`;
document.getElementById("saldoactual").textContent = `$${saldonow}`;

const pagosiguiente = pagoex[numfila]
document.querySelector('#sigpago').innerHTML = `$${pagosiguiente}`

    
    // Unpack each variable
    const nombrePF = rowDataObj["Nombre completo"].replace(/,/g, '');
    document.getElementById("nombre").textContent = nombrePF;
    const id = rowDataObj["RFC"];
    document.getElementById("id").textContent = id;
    document.getElementById("fecha_inicio").textContent = inicio;
  



// Example usage

let fechaDeHoy = new Date();

let fechaSigPago = nearestDate.toLocaleDateString('es-ES', options)
document.getElementById("fechaSigPago").textContent = fechaSigPago;

let diferenciaEnMilisegundos = nearestDate - fechaDeHoy;
let diferenciaEnDias = Math.floor(diferenciaEnMilisegundos / (1000 * 60 * 60 * 24));
document.getElementById("countDays").textContent = diferenciaEnDias + " días para la fecha de pago";

   fechahoy = new Date()
  document.getElementById('fechahoy').textContent  = fechahoy.toLocaleDateString('es-ES', options)
  
  function actualizarBarraDeProgreso() {
    // Calcular el porcentaje de progreso
    var progreso = (numerador/m) * 100;

    // Actualizar el valor de la barra de progreso
    var progressBar = document.getElementById("progressBar");
    progressBar.style.width = progreso + "%";
    progressBar.setAttribute("aria-valuenow", progreso);
    progressBar.textContent = progreso.toFixed() + "%";
  }
  
  // Llamar a la función para actualizar la barra de progreso inicialmente y cada vez que se actualicen las variables
  actualizarBarraDeProgreso(); 
  
  
   document.getElementById('fechasCounter').textContent  = numerador
  document.querySelector('#parcialidades').innerHTML = "/" + m
     const fechaVenci= fecha[m]
 document.getElementById('fecha_final').textContent  = fechaVenci
    
});