
let nomPdf = "";
let formattedStartDate = null;
let formattedEndDate = null;

function getMadridTimestamp() {
    return new Date().toLocaleString('en-GB', { timeZone: 'Europe/Madrid', hour12: true });
}

async function fetchLogs(url) {
    //let idPlus = document.getElementById("idPlus");
    if (url) {
        //idPlus.style = "display: none";
        nomPdf = url;
        let dateTmp = [];
        dateTmp = nomPdf.split("_");
        let numLength = dateTmp.length;
        //let startDateStr = dateTmp[numLength - 2]
        //console.info(startDateStr)
        // Convertir la fecha inicial del formato 20241018_140131 a DD/MM/YYYY
        //const year = startDateStr.substring(0, 4);
        //const month = startDateStr.substring(4, 6);
        //const day = startDateStr.substring(6, 8);
        //formattedStartDate = `${day}/${month}/${year}`;
        console.info(nomPdf)
    }
    else {
        //idPlus.style = "display: block";
        let url = localStorage.getItem("nameEjercicios");
        console.info(url)
        ///////////////////
        let nom1 = []
        nom1 = url.split(",");
        let nom2 = [];
        nom2 = nom1[0].split("?");
        let nom3 = [];
        nom3 = nom2[1].split("#"); //imagenes.split("?");
        console.info(nomPdf);
        console.log(nom3);
        console.log(nom3.length);
        if (nom3.length > 1) {
            nomPdf = nom3[1];
            let dateTmp = [];
            //dateTmp = nomPdf.split("_");
            //let numLength = dateTmp.length;
            //let startDateStr = dateTmp[numLength - 2]
            //console.info(startDateStr)
            // Convertir la fecha inicial del formato 20241018_140131 a DD/MM/YYYY
            //const year = startDateStr.substring(0, 4);
            //const month = startDateStr.substring(4, 6);
            //const day = startDateStr.substring(6, 8);
            //formattedStartDate = `${day}/${month}/${year}`;
            console.info(nomPdf)
        }
        else {
            nomPdf = nom2[1];
            //const today = new Date();
            //formattedStartDate = `${today.getDate().toString().padStart(2, '0')}/${(today.getMonth() + 1).toString().padStart(2, '0')}/${today.getFullYear()}`;
            //console.info(nomPdf)
        }

    }
    // Obtener la fecha actual y formatearla a DD/MM/YYYY
    const today = new Date();
    formattedEndDate = `${today.getDate().toString().padStart(2, '0')}/${(today.getMonth() + 1).toString().padStart(2, '0')}/${today.getFullYear()}`;

    await processLogs(nomPdf, formattedStartDate, formattedEndDate);

    if (navigator.onLine) {
        console.log("Tienes conexión a Internet.");

        try {
            const response = await fetch(servidorURL + `/php/logs/php_read_logs_pdf_encuesta.php?nomPdf=${encodeURIComponent(nomPdf)}&startDate=${encodeURIComponent(formattedStartDate)}&endDate=${encodeURIComponent(formattedEndDate)}&v=${new Date().getTime()}`);

            if (!response.ok) {
                throw new Error('Error fetching logs.');
            }
            const logs = await response.json();
            console.info(logs);
            //displayLogs(logs);
        } catch (error) {
            console.error('Error:', error);
        }
    } else {
        console.log("No tienes conexión a Internet.");
    }
}
//////////////////////
function displayLogs(logs) {
    console.info(logs)
    const logsContainer = document.getElementById('logs');
    console.info(logsContainer)
    logsContainer.innerHTML = ''; // Clear previous logs

    if (logs.status === 'error') {
        logsContainer.innerHTML = `<p>${logs.message}</p>`;
        return;
    }
    logs.forEach(log => {
        const logEntry = document.createElement('div');
        logEntry.classList.add('log-entryLogs');
        logEntry.innerHTML = `
                    <p><strong>Time MG.:</strong> ${log.timestamp}</p>
                    <p><strong>Uso:</strong> ${log.uso}. - <strong>Ocasional:</strong> ${log.ocasional}. </p>
                    <p><strong>Util:</strong> ${log.util}. - <strong>Clara:</strong> ${log.clara}. - <strong>Ayuda:</strong> ${log.ayuda}</p>
                    <p><strong>Comment:</strong> ${log.comment}</p>
                    `;
        logsContainer.appendChild(logEntry);
    });
}
///////////////////////
function processLogs(nomPdf, startDate, endDate) {
    const logsContainer = document.getElementById('logsUp');
    logsContainer.innerHTML = ''; // Limpiar los logs anteriores
    const logEntry = document.createElement('div');
    logEntry.classList.add('log-entry');
    logEntry.innerHTML = `
                <p><strong>PDF:</strong> ${nomPdf}</p>
            `;
    logsContainer.appendChild(logEntry);
}

/////////////////////
async function submitSurvey() {
    const form = document.getElementById('surveyForm');
    const formData = new FormData(form);
    let uso = formData.get('uso');
    let ocasional = formData.get('ocasional');
    let util = formData.get('util');
    let clara = formData.get('clara');
    let ayuda = formData.get('ayuda');
    let comment = formData.get('comment');
    const surveyData = {
        uniqueNumber: Date.now(),
        timestamp: getMadridTimestamp(),
        pdf_nom: nomPdf,
        comment: comment,
        uso: uso,
        ocasional: ocasional,
        util: util,
        clara: clara,
        ayuda: ayuda
    };

    ///////////////////////
    // Enviar los datos al servidor mediante fetch

    const response = fetch(servidorURL + '/php/logs/php_log_encuesta.php?t=' + new Date().getTime(), {
        //fetch('guardar_encuesta.php?t=' + new Date().getTime(), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify(surveyData)
    })
        .then(response => response.json())
        .then(data => {
            // Mostrar mensaje de éxito
            //document.getElementById('responseMessage').innerText = 
            alert('¡Gracias por tu respuesta!');
            fetchLogs(nomPdf, formattedStartDate, formattedEndDate)
            form.reset();
            if (lappEncuesta) window.open('./index.html', '_self');
            else window.open('./encuesta.html', '_self');
        })
        .catch(error => {
            console.error('Error al enviar la encuesta:', error);
            //document.getElementById('responseMessage').innerText = 
            alert('Hubo un error al enviar la encuesta. Inténtalo de nuevo.');
        });
}

