async function queryGET(ctr, filter, fields, cb) {
    const queryString = new URLSearchParams({
        filter: JSON.stringify(filter),
        fields: fields ? fields : null
    }).toString();

    try {
        const response = await fetch(`./controllers/${ctr}.php?${queryString}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        const data = await response.json();
        // const responseText = await response.text();
        // console.log(responseText);
        cb(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

async function queryPOST(ctr, data, cb) {
    const params = new URLSearchParams(data).toString();

    try {
        const response = await fetch(`./controllers/${ctr}.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: params
        });
        const data = await response.json();
        cb(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

async function maintainer(table, filter, fields, cb) {
    const queryString = new URLSearchParams({
        table: JSON.stringify(table),
        filter: JSON.stringify(filter),
        fields: fields ? JSON.stringify(fields) : null
    }).toString();

    try {
        const response = await fetch(`./controllers/maintainer.php?${queryString}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        // const responseText = await response.text();
        // console.log(responseText);
        const data = await response.json();
        cb(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

function setCurrentDateTimeForAll() {
    const now = new Date();
    const formattedDateTime = now.toISOString().slice(0, 16);

    document.querySelectorAll('input[type="datetime-local"]').forEach(input => {
        input.value = formattedDateTime;
    });
}

function dateToTxt(fechaString) {
    const fecha = new Date(fechaString);
    const diasSemana = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
    const meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
    const diaSemana = diasSemana[fecha.getDay()];
    const dia = fecha.getDate();
    const mes = meses[fecha.getMonth()];
    const año = fecha.getFullYear();
    const horas = fecha.getHours();
    const minutos = String(fecha.getMinutes()).padStart(2, '0');
    return `${diaSemana} ${dia} de ${mes} ${año} - ${horas}:${minutos}`;
}

function formatDateTime(dateString) {
    const months = ['ENE', 'FEB', 'MAR', 'ABR', 'MAY', 'JUN', 'JUL', 'AGO', 'SEP', 'OCT', 'NOV', 'DIC'];
    const date = new Date(dateString);

    const month = months[date.getMonth()];
    const day = date.getDate();
    const hour = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');

    return {
        month: `${month} `,
        day: day.toString().padStart(2, '0'),
        hour: hour,
        minutes: minutes
    };
}

function getUrlParams(url) {
    const params = new URL(url).searchParams;
    return Array.from(params.entries()).reduce((obj, [key, value]) => {
        if (value) obj[key] = value;
        return obj;
    }, {});
}

function getTimeDifference(date1, date2) {
    const d1 = new Date(date1);
    const d2 = new Date(date2);

    // Diferencia en milisegundos
    const diffMs = Math.abs(d2 - d1); // Usa Math.abs para evitar valores negativos

    // Convertir milisegundos a horas y minutos
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    let diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

    // Asegurar que los minutos tengan dos dígitos
    diffMinutes = diffMinutes.toString().padStart(2, '0');

    return {
        hours: diffHours,
        minutes: diffMinutes
    };
}

function statusMsg(title, msg) {
    console.log(
        `%c${title || ''}\n%c${msg}`,
        'font-weight: bold; color: #0dd8d8; text-decoration: underline;',
        'color: #ceb73f;'
    );

    console.table({
        'Time Stamp': new Date().getTime(),
        'OS': navigator.platform,
        'Browser': navigator.appCodeName,
        'Language': navigator.language,
        'Used memory': `${(performance.memory.usedJSHeapSize / 1048576).toFixed(2)}MB`,
        'Total memory': `${(performance.memory.totalJSHeapSize / 1048576).toFixed(2)}MB`,
        'Max memory': `${(performance.memory.jsHeapSizeLimit / 1048576).toFixed(2)}MB`
    });
}

setTimeout(() => {
    statusMsg("Padel Sunset Arena", "Status & Info");
}, 10000); // 3000 milisegundos = 3 segundos
export { queryGET, queryPOST, maintainer, setCurrentDateTimeForAll, dateToTxt, formatDateTime, getTimeDifference, getUrlParams, statusMsg };