document.addEventListener("DOMContentLoaded", function() {
    // Retrieve the rowData from the session
    var rowData = sessionStorage.getItem('rowData');
    var rowDataObj = JSON.parse(rowData);
    // Log the rowDataObj to the console
    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"];
    localStorage.setItem( 'tic', tic);
    console.log("tic:", tic)
    const monto = rowDataObj["Monto a Aportar"];
    console.log("Monto inversión:", monto)
    const tcv = parseFloat(rowDataObj["tcv"]);
    localStorage.setItem( 'tcv', 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 fechai= rowDataObj["Fecha de inicio"];
    console.log("Fecha de inicio:", fechai)
    
if(modldd === 'Inversión Balloon'){
  const interestic = tic
  const amount = monto
  const residual = kic
  const periodo = kcv
  const plazo = plzo
  const fecha_inicio = fechai
  var n = Math.floor(plazo / periodo); // Redondear hacia abajo

  const amountt = 1 * amount;
    
  
    document.getElementById("plazodeinv").textContent = plazo/30 +" meses";
  //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]
  
  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
    console.log("fechas:", fecha)
    var numerador = parseFloat(contarFechasPasadas(fecha.slice(1)))
    console.log("Numerador:", numerador)

  //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, ",");
    document.getElementById("totalrendi").textContent = `$${rendimientostotal}`;
    document.getElementById("kmasr").textContent = `$${capitalrendimiento}`;

  //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;
    
    const invnow= amountt.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    const yieldactual = parseFloat(saldo_final[numfila].replace(/,/g, ''));
    saldonow = yieldactual.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    document.querySelector('#invactual').innerHTML = `$${invnow}`;
    
    suma_pagos = amountt.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    document.getElementById("totalinversion").textContent = `$${suma_pagos}`;
    document.getElementById("saldoactual").textContent = `$${saldonow}`;
    
    const pagosiguiente = pago[numfila]
    document.querySelector('#sigpago').innerHTML = `$${pagosiguiente}`
    
    }
else{
    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, '\/'));
      var 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
    var 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}`
    var n = months
}
    
    // Unpack each variable
    const typePerson= rowDataObj["Tipo de inversionista"];
    let nombrepf
    if(typePerson== "Persona moral"){
        nombrePF = rowDataObj["Razón social"]
    }
    else {
        nombrePF = rowDataObj["Nombre completo"]
    }
    document.getElementById("nombre").textContent = nombrePF.replace(/,/g, '');
    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/n) * 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 = "/" + n
     const fechaVenci= fecha[n]
 document.getElementById('fecha_final').textContent  = fechaVenci
    
    const contratosigned = rowDataObj["Contrato firmado"];
    console.log("Contrato",contratosigned[0])
    signed= contratosigned[0];
    
    const no_contrato = rowDataObj["ID"];
    document.getElementById("concepto_contrato").textContent = no_contrato;
    const idEnv = rowDataObj["id"];
   
    
    
        // Hide header and button if signed is undefined
    if (contratosigned.length === 0) {
        document.getElementById("headercontract").style.display = "none";
        document.getElementById("signedcontract").style.display = "none";
        document.getElementById("statact").style.display = "none";
    } else {
        // Set download URL for the button if URL is not null
        document.getElementById("signedcontract").addEventListener("click", function() {
            var link = document.createElement("a");
            link.href = signed;
            link.download = "contrato_firmado.pdf"; // Change filename accordingly
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });
        document.getElementById("statinact").style.display = "none";
    }
    
});