/**
 * Exemple d’utilisation :
 * Récupère les loyers avec un nombre de lignes défini
 * @param {number} rows - Nombre de lignes à récupérer
 */

const Revenue = {
    GetXRevenues: "x_revenues",
    GetLastRevenues: "last_revenue",
    GetAllRevenues: "all_revenues",
    GetRevenueByID: "revenues_by_id",
    GetAdditionalRevenues: "additional_revenues"
};

const Expense = {
    GetRightExpenses: "last_expenses",
    GetExpenseByID: "expense_by_id"
}

var TotalRevenu = 0, TotalExpense = 0;

function loadRevenues() {
    return Promise.all([
        new Promise((resolve, reject) => {
            apiCall(Controller.Revenue, Revenue.GetXRevenues, { rows: 1 }, data => {
                document.getElementById('idRevenues').innerText = data[0].id;
                const loyer = document.getElementById('salaire');
                const salaire = parseFloat(data[0]?.salary || 0);
                if (loyer) loyer.innerText = `${toPriceFormat(salaire)}€`;
                resolve(salaire);
            }, reject);
        }),
        new Promise((resolve, reject) => {
            apiCall(Controller.Revenue, Revenue.GetAdditionalRevenues, {}, data => {
                const additionalRevenues = document.getElementById('additionalRevenues');
                const totalAR = data.reduce((acc, item) => acc + (parseFloat(item.amount) || 0), 0);
                if (additionalRevenues) additionalRevenues.innerText = `${toPriceFormat(totalAR)}€`;
                resolve(totalAR);
            }, reject);
        })
    ]).then(([salary, additional]) => {
        TotalRevenu = salary + additional;
    });
}

function loadExpenses() {
    return new Promise((resolve, reject) => {
        apiCall(Controller.Expense, Expense.GetRightExpenses, {}, data => {
            document.getElementById('idExpenses').innerText = data.id;

            const loyer = document.getElementById('loyer');
            const trash = document.getElementById('trash');
            const electricity = document.getElementById('electricity');
            const insurance = document.getElementById('insurance');
            const wifi = document.getElementById('wifi');
            const groceries = document.getElementById('groceries');
            const additionalSourcesExpense = document.getElementById('additionalSourcesExpense');
            const additionalExpensesSub = document.getElementById('additionalExpensesSub');
            const saving = document.getElementById('saving');

            if (loyer) loyer.innerText = `${toPriceFormat(data.rent)}€`;
            if (trash) trash.innerText = `${toPriceFormat(data.trash)}€`;
            if (insurance) insurance.innerText = `${toPriceFormat(data.insurance)}€`;
            if (electricity) electricity.innerText = `${toPriceFormat(data.electricity)}€`;
            if (wifi) wifi.innerText = `${toPriceFormat(data.wifi)}€`;
            if (groceries) groceries.innerText = `${toPriceFormat(data.groceries)}€`;
            if (saving) saving.innerText = `${toPriceFormat(data.saving)}€`;

            if (additionalSourcesExpense) {
                const totalAR = data.additionalSourcesExpense.reduce((acc, item) => acc + (parseFloat(item.amount) || 0), 0);
                additionalSourcesExpense.innerText = `${toPriceFormat(totalAR)}€`;
            }

            if (additionalExpensesSub) {
                const totalAR = data.additionalSourcesSub.reduce((acc, item) => acc + (parseFloat(item.amount) || 0), 0);
                additionalExpensesSub.innerText = `${toPriceFormat(totalAR)}€`;
            }

            TotalExpense = data.total;
            resolve();
        }, reject);
    });
}

// Lance automatiquement l’appel au chargement de la page
document.addEventListener('DOMContentLoaded', async () => {
    const result = document.getElementById('result');
    const monthDisplay = document.getElementById('monthOfToday');
    const cards = document.querySelectorAll('.cardDepense');

    monthDisplay.textContent = returnMonthOfToday();

    try {
        await Promise.all([loadExpenses(), loadRevenues()]);
        if (result) result.textContent = `${toPriceFormat(TotalRevenu - TotalExpense)}€`;
    } catch (error) {
        console.error("❌ Erreur de chargement :", error);
        if (result) result.textContent = "Erreur lors du calcul";
    }

    cards.forEach(card => {
        card.addEventListener('click', () => onClickInCard(card));
    });
});

function onClickInCard(card) {
    const label = document.getElementById("CRUDModalLabel");
    const idExpense = document.getElementById('idExpenses').innerText;

    if (label) label.textContent = card.id.replace(/_/g, ' ').toUpperCase();

    apiCall(Controller.Expense, Expense.GetExpenseByID, { id: idExpense }, data => {

        initExpensesTable(data);

        const modal = new bootstrap.Modal(document.getElementById('CRUDModal'));
        modal.show();
    });


}

/**
 * Initialise ou met à jour dynamiquement une table DataTables avec les données de dépenses.
 * 
 * - Si la table est déjà initialisée, elle est vidée et rechargée avec les nouvelles données.
 * - Sinon, la table est créée avec les colonnes correspondantes à l’objet Expense.
 *
 * @param {Array<Object>} data - Tableau d’objets de type Expense à afficher dans le tableau.
 * Chaque objet doit contenir : id, date, rent, electricity, trash, wifi, groceries, saving, insurance, userId.
 */
function initExpensesTable(data) {
    const tableId = '#expensesTable';
    const normalizedData = Array.isArray(data) ? data : [data];

    if ($.fn.DataTable.isDataTable(tableId)) {
        $(tableId).DataTable().clear().rows.add(normalizedData).draw();
        return;
    }

    $(tableId).DataTable({
        data: normalizedData,
        paging: false,
        searching: false,
        ordering: false,
        info: false,
        language: {
            url: "https://cdn.datatables.net/plug-ins/1.13.6/i18n/fr-FR.json"
        },
        columns: [
            { data: 'id', visible: false },        // ID caché
            {
                data: 'date',
                visible: false                     // Date cachée
            },
            {
                data: 'rent',
                title: 'Loyer',
                render: data => `${data} €`
            },
            {
                data: 'electricity',
                title: 'Électricité',
                render: data => `${data} €`
            },
            {
                data: 'trash',
                title: 'Poubelles',
                render: data => `${data} €`
            },
            {
                data: 'wifi',
                title: 'Wi-Fi',
                render: data => `${data} €`
            },
            {
                data: 'groceries',
                title: 'Courses',
                render: data => `${data} €`
            },
            {
                data: 'saving',
                title: 'Épargne',
                render: data => `${data} €`
            },
            {
                data: 'insurance',
                title: 'Assurance',
                render: data => `${data} €`
            },
            { data: 'userId', visible: false }     // Utilisateur caché
        ]
    });
}




/**
 * Retourne le nom du mois actuel en français avec la première lettre en majuscule.
 *
 * @returns {string} Le mois actuel, par exemple : "Août", "Mars", etc.
 */
function returnMonthOfToday() {
    const date = new Date();
    const moisActuel = date.toLocaleString('fr-FR', { month: 'long' });
    return moisActuel.charAt(0).toUpperCase() + moisActuel.slice(1);
}


