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 tasa = rowDataObj["Tasa"];
    const c = rowDataObj["Comision"];
    const monto = rowDataObj["Monto"];
    const peri = parseFloat(rowDataObj["Periodicidad"]);
    const plzo = parseFloat(rowDataObj["Plazo"]);
    document.getElementById("plazodecredito").textContent = (plzo / 30) + " meses";
    const type = rowDataObj["Type"];
    const fecha_inicio= rowDataObj["Fecha de inicio"];
    console.log("Fecha de inicio:", fecha_inicio);

    let periodo;
    let n;
    let payment;
    let amountt;
    let interes;

    if(type == "SSII") {
        const interestic = parseFloat(tasa);
        console.log(interestic);
        const com = parseFloat(c);
        console.log(com);
        const amount = parseFloat(monto.replace("$", "").replace(/,/g, ""));
        document.getElementById("montominis").textContent = `$${amount.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
        console.log(amount);
        periodo = parseFloat(peri);
        console.log("Periodo:", periodo);
        const plazo = parseFloat(plzo);
        console.log("Plazo:", plazo);

        n = Math.floor(plazo / periodo); // Redondear hacia abajo
        console.log(n);
        localStorage.setItem('numperiodos', n);
      
        amountt = amount;
        let comision = com * 0.01;
        interes = interestic * 0.01 * (periodo / 360);
        console.log(interes);
        payment = amountt * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
      
        // Utilizar el valor redondeado de n en los cálculos
        payment = amountt * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
        let d = payment * n;
        let cost = (((d / amountt - 1) * 100) * 12) / ((plazo / 30) );
        
        var amort = [0];
        var int = [0];
        var saldo_inicial = [amountt * (1 + comision)];
        var saldo_final = [amountt * (1 + comision)];
        var pago = [0];
        var iva = [0];
  
        //Nuestro loop con ecuaciones en diferencia
        for (let i = 0; i <= n; i++) {
            pago[i + 1] = payment;
            int[i + 1] = saldo_final[i] * interes / 1.16;
            iva[i + 1] = int[i + 1] * 0.16;
            amort[i + 1] = payment - int[i + 1] - iva[i + 1];
            saldo_inicial[i + 1] = saldo_final[i] + int[i + 1] + iva[i + 1];
            saldo_final[i + 1] = saldo_final[i] - amort[i + 1];      
        }
          
    } else if(type == "Balloon") {
        const interestic = parseFloat(tasa);
        const com = parseFloat(c);
        const amount = parseFloat(monto);
        const residual = parseFloat(rowDataObj["Porcentaje balloon"]);
        periodo = parseFloat(peri);
        const plazo = parseFloat(plzo);
        n = Math.floor(plazo / periodo); // Redondear hacia abajo

        amountt = amount;
        let comision = com * 0.01;
        interes = interestic * 0.01 * (periodo / 360);
        const R = residual * 0.01 * amountt / Math.pow(1 + interes, n);
        payment = (amountt - R) * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));

        // Utilizar el valor redondeado de n en los cálculos
        payment = (amountt - R) * (1 + comision) * interes / (1 - Math.pow(1 + interes, -n));
        var amort = [0];
        var int = [0];
        var saldo_inicial = [amountt * (1 + comision)];
        var saldo_final = [amountt * (1 + comision)];
        var pago = [0];
        var iva = [0];

        //Nuestro loop con ecuaciones en diferencia
        for (let i = 0; i <= n; i++) {
            pago[i + 1] = payment;
            int[i + 1] = saldo_final[i] * interes / 1.16;
            iva[i + 1] = int[i + 1] * 0.16;
            amort[i + 1] = payment - int[i + 1] - iva[i + 1];
            saldo_inicial[i + 1] = saldo_final[i] + int[i + 1] + iva[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] - iva[n];
    }

    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)
    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);
    }

    //Otro loopsillo para añadir formato:    
    for (let 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, ",");
        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, ","); 
    }    
    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, ",");
    iva[0] = iva[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    int[0] = int[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    pago[0] = pago[0].toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    amort[0] = amort[0].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", "Interés", "I.V.A.", "Amortización", "Pago parcial", "Saldo Final", "Fecha"];
    var table = document.createElement("TABLE");  //makes a table element for the page
        
    for (let 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 = `$${iva[i]}`;
        row.insertCell(4).innerHTML = `$${amort[i]}`; 
        row.insertCell(5).innerHTML = `$${pago[i]}`;
        row.insertCell(6).innerHTML = `$${saldo_final[i]}`; 
        row.insertCell(7).innerHTML = fecha[i];       
    }

    var header = table.createTHead();
    var headerRow = header.insertRow(0);
    for (let 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;      
    
    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";
    }
    
    document.getElementById("display_bien1_folio").textContent = rowDataObj["Folio fiscal"];
    document.getElementById("display_bien1_descripcion").textContent = rowDataObj["Descripción"];
    document.getElementById("display_bien1_accesorios").textContent = rowDataObj["Accesorios"];
    document.getElementById("display_bien1_observaciones").textContent = rowDataObj["Observaciones"];
    document.getElementById("display_bien1_precio").textContent = rowDataObj["Precio"];
    document.getElementById("display_bien2_folio").textContent = rowDataObj["Folio fiscal Bien 2"];
    document.getElementById("display_bien2_descripcion").textContent = rowDataObj["Descripción Bien 2"];
    document.getElementById("display_bien2_accesorios").textContent = rowDataObj["Accesorios Bien 2"];
    document.getElementById("display_bien2_observaciones").textContent = rowDataObj["Observaciones Bien 2"];
    document.getElementById("display_bien2_precio").textContent = rowDataObj["Precio Bien 2"];
    
    
        /////Línea de crédito//////
////CALCULAR REVOLVENCIA//////////////////
let paymentRevol = amountt * interes / (1 - Math.pow(1 + interes, -n));
  amortRev = [0]
  intRev = [0]
  saldo_inicialRev = [amountt];
  saldo_finalRev = [amountt];
  pagoRev = [0]
  ivaRev = [0]
 for (i = 0; i<=n; i++){
    pagoRev[i+1] = paymentRevol;
    intRev[i+1] = saldo_finalRev[i]*interes/1.16;
    ivaRev[i+1] = intRev[i+1]*0.16;
    amortRev[i+1] = paymentRevol - intRev[i+1] - ivaRev[i+1];
    saldo_inicialRev[i+1] = saldo_finalRev[i] + intRev[i+1] + ivaRev[i+1];
    saldo_finalRev[i+1] = saldo_finalRev[i] - amortRev[i+1];      
    }

let revolvencia = 0;
for (let i = 0; i < fechasPasadas+1; i++) {
  revolvencia += amortRev[i];
}

    const lineaMax = parseFloat(rowDataObj["Linea autorizada "].replace(/[\$,]/g, ""));
    document.getElementById("linea_max").textContent = `$${lineaMax.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}` ;
    //const amount= parseFloat(rowDataObj["Monto"].replace("$", ""));
    //console.log(amount)
    saldoXliberar= amountt-revolvencia
    console.log(saldo_inicial[fechasPasadas+1])
    var saldo_Actual= parseFloat(saldo_inicial[fechasPasadas+1].replace(/[\$,]/g, ""))
    document.getElementById("amount_actual").textContent = `$${saldo_Actual.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}` ;
    document.getElementById("linea_liberar").textContent = `$${saldoXliberar.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}` ;
    const amount_disponible = lineaMax-saldoXliberar
    console.log(amount_disponible)
    document.getElementById("amount_dispo").textContent = `$${amount_disponible.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`
    
   
});
