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);
    const interestic = parseFloat(rowDataObj["Tasa"]);
    const com = parseFloat(rowDataObj["Comision"]);
    console.log("Comisión:", com)
    const r = parseFloat(rowDataObj["Rentas en deposito"]);
    const b = parseFloat(rowDataObj["Backend"]);
    const amount = parseFloat(rowDataObj["Costo del equipo"]);
    console.log("Costo del equipo:", amount)
    const residual = parseFloat(rowDataObj["Residual"]);
    console.log("Residual:", residual)
    const accesorio = parseFloat(rowDataObj["Costo de accesorios"]);
    const periodo = parseFloat(rowDataObj["Periodicidad"]);
    const plazo = parseFloat(rowDataObj["Plazo"]);
    const fecha_inicio = rowDataObj["Fecha de inicio"];
    let n = Math.floor(plazo / periodo); // Redondear hacia abajo

    const amountt = 1 * amount;
    const subtotal = amountt/1.16;
    
    //const date = new Date();
   let comision = com * 0.01;
   let interes = interestic * 0.01 * (periodo / 360);
   const R=(residual*0.01)*amountt/Math.pow(1 + interes, n)
   const Rg = ((residual + b)*0.01)*amountt/Math.pow(1 + interes, n)
   console.log(Rg)
   console.log(R)
   let payment = (amountt-R) * interes / (1 - Math.pow(1 + interes, -n));
   let pg = (amountt-Rg) * (1+comision) * interes / (1 - Math.pow(1 + interes, -n));
   console.log(pg)
   console.log("Pago Renta:", payment)
   // Utilizar el valor redondeado de n en los cálculos
  
    let d = (payment/1.16)*n;
    let cost = ((payment*n+(amountt*(residual*0.01)))/amountt-1)*100;
    let rsdl = residual + b
    console.log(rsdl)
    
    amort = [0]
    amortg = [0]
    int = [0]
    intG=[0]
    ivaG=[0]
    saldo_inicial = [amountt];
    saldo_final = [amountt];
    saldo_finalG = [amountt]
    saldo_inicialG = [amountt];
    pago = [0]
    iva = [0]
  iva_ap=[0]
  renta = [0]
  total = [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;
    intG[i+1] = saldo_finalG[i]*interes/1.16;
    ivaG[i+1] = intG[i+1]*0.16;
    iva[i+1] = int[i+1]*0.16;
    amort[i+1] = payment - int[i+1] - iva[i+1];
    amortg[i+1] = pg- intG[i+1] - ivaG[i+1]
    saldo_inicial[i+1] = saldo_final[i] + int[i+1] + iva[i+1];
    saldo_inicialG[i+1] = saldo_finalG[i] + intG[i+1] + ivaG[i+1];
    saldo_final[i+1] = saldo_final[i] - amort[i+1];
    saldo_finalG[i+1] = saldo_finalG[i] - amortg[i+1];  
      }
      
  //saldo_inicial[1]=saldo_final[0] + int[1]*1.16    
  

//Último pago
   pago[n] = saldo_inicial[n]
   saldo_final[n] = 0
   amort[n] = pago[n] -int[n]-iva[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_inicialG[i+1] = saldo_inicialG[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, ",");
    saldo_finalG[i+1] = saldo_finalG[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, ",");
    }
    
  let pgAccs= [];
  const yP = Math.floor(360/periodo)
   for (let i = 0; i < Math.floor(n / yP); i++) {
    for (let j = 0; j < yP; j++) {
        let paymentsAccs = (accesorio * interes )/ (1 - Math.pow(1 + interes, -yP));
        pgAccs.push(paymentsAccs);
        }
    }

    let remaining = n % yP;
    if (remaining > 0) {
        for (let j = 0; j < remaining; j++) {
            let paymentsAccs = (accesorio * interes) / (1 - Math.pow(1 + interes, -remaining));
            pgAccs.push(paymentsAccs);
        }
    }

console.log('Pago de accesorio:',pgAccs);

    let pgAccsneto = [0];
    let saldo_inaccs = [accesorio];
    let saldo_finaccs = [accesorio];
    let intaccs = [0];
    let amortccs = [0];
    let ivaccs = [0];
    
    for (let i = 0; i <= n; i++) {
    pgAccsneto[i + 1] = pgAccs[i] / 1.16;
    renta[i+1] = payment/1.16
      iva_ap[i+1] = (renta[i+1] + pgAccsneto[i+1])*0.16
      total[i+1] = renta[i+1]+iva_ap[i+1]+pgAccsneto[i+1]
    intaccs[i + 1] = saldo_finaccs[i] * interes / 1.16;
    ivaccs[i + 1] = intaccs[i + 1] * 0.16;
    amortccs[i + 1] = pgAccs[i] - intaccs[i + 1] - ivaccs[i + 1];
    saldo_inaccs[i + 1] = saldo_finaccs[i] + intaccs[i + 1] + ivaccs[i + 1];
    saldo_finaccs[i + 1] = saldo_finaccs[i] - amortccs[i + 1];

    if (saldo_finaccs[i + 1] <= 0) {
        saldo_finaccs[i + 1] = accesorio; // Reset to accesorio if it reaches zero
    }
}
  
  saldo_inicialG[0]=saldo_inicialG[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")

    
    var hoy = new Date(fecha_inicio.replace(/-/g, '\/'));
    console.log("Hoy", hoy);
    var fecha = [hoy];
    var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    var inicio = [hoy.toLocaleDateString('es-ES', options)];
    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 (let 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
      console.log("Fecha vector:", fecha)
      
      
  //Ahora crearemos una tabla en HTML con la anterior información
    var headers = ["Periodo",
    "Renta", "Accesorios", "I.V.A.",  "Total", 
    "Vencimiento anticipado", "Vencimiento Anticipado Accesorios", "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 = `$${renta[i].toLocaleString(undefined, {maximumFractionDigits:2})}`;
        row.insertCell(2).innerHTML = `$${pgAccsneto[i].toLocaleString(undefined, {maximumFractionDigits:2})}`;
        row.insertCell(3).innerHTML = `$${iva_ap[i].toLocaleString(undefined, {maximumFractionDigits:2})}`;
        row.insertCell(4).innerHTML = `$${total[i].toLocaleString(undefined, {maximumFractionDigits:2})}`;        
        row.insertCell(5).innerHTML = `$${saldo_inicialG[i]}`;
        row.insertCell(6).innerHTML = `$${saldo_inaccs[i].toLocaleString(undefined, {maximumFractionDigits:2})}`;
        row.insertCell(7).innerHTML = fecha[i].toLocaleDateString('es-ES', options);
    }

    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)
    document.getElementById('tabla').innerHTML = myData.innerHTML;    
    
    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;
        
        // Flag to check if all dates have passed
        var allDatesPassed = true;
        
        // 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 at least one date hasn't passed, update the flag
            allDatesPassed = false;
            
            // If the current difference is smaller than the previous smallest difference, update nearest date
            if (difference < nearestDifference) {
                nearestDifference = difference;
                nearestDate = date;
            }
        }
        
        // If all dates have passed, return the last date in the array
        if (allDatesPassed) {
            return new Date(dates[dates.length - 1]);
        }
        
        // Return the nearest date
        return nearestDate;
    }

    // Example usage
    var nearestDate = findNearestDate(fecha.slice(1));
    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.slice(1)));
    console.log("Número de fechas pasadas: " + fechasPasadas);
    localStorage.setItem('fechasCounter', fechasPasadas);

    //Loop formato de fechas
    for (let i = 0; i <= n; i++) {
        fecha[i] = new Date(fecha[i]).toLocaleDateString('es-ES', options);
    }
    
    var periodicidad; // Declare the variable outside the if-else chain

    if (periodo == 7) {
        periodicidad = "Semanal";
    } else if (periodo == 30) {
        periodicidad = "Mensual";
    } else if (periodo == 15) {
        periodicidad = "Quincenal";
    } else if (periodo == 14) {
        periodicidad = "Catorcenal";
    } else {
        periodicidad = "Otro"; // Handle the case when none of the conditions are met
    }

    console.log(periodicidad);
    document.getElementById("periodicidad").textContent = periodicidad;
    
    // Unpack each variable
    const nombrePF = rowDataObj["Nombre de Acreditada"];
    document.getElementById("nombre").textContent = nombrePF.replace(/\,/g, ' ');
 
    document.getElementById("nocontrato").textContent = rowDataObj["No. Anexo"];
    const id = rowDataObj["No. Contrato Maestro"];
    document.getElementById("id").textContent = id;
    document.getElementById("noCM").textContent = id;
    const parcialidad = payment;
    document.getElementById("parcialidad").textContent = `$${parcialidad.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    
    var formattedfecha_inicio = new Date(fecha_inicio.replace(/-/g, '\/'));
    var fechaini = [formattedfecha_inicio.toLocaleDateString('es-ES', options)];
    document.getElementById("fecha_inicio").textContent = fechaini;
    
    const id_form = rowDataObj["id"];
    localStorage.setItem('id_form', id_form);
    
    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";

    function actualizarBarraDeProgreso() {
        // Calcular el porcentaje de progreso
        var progreso = (fechasPasadas / 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 = fechasPasadas;
    document.querySelector('#parcialidades').innerHTML = "/" + n;
    const fechaVenci = fecha[n];
    document.getElementById('fecha_final').textContent = fechaVenci;
    const fechasCounter = parseFloat(localStorage.getItem('fechasCounter'));

    const contratosigned = rowDataObj["Anexo firmado"];
    console.log("Contrato", contratosigned[0]);
    let signed = contratosigned[0];
    
    // 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";
    }
    
    const lineaMax = parseFloat(rowDataObj["Linea autorizada"].replace("$", "").replace(/,/g, ""));
    document.getElementById("linea_max").textContent = `$${lineaMax.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    document.getElementById("amount_actual").textContent = `$${amount.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    const amount_disponible = lineaMax - amount;
    console.log(amount_disponible);
    document.getElementById("amount_dispo").textContent = `$${amount_disponible.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    
});
