const ent_id_value = $.trim($("#ent_id_value").val());

// Declared in header.js
selectBranchByUserPermission(ent_id_value);

// ON CHANGE BRANCH ID
$(document).on("change", "#pos_id_value", async function () {
    let pos_id = $(this).val();
    let posInfo = await getBranchData(pos_id);
    jsStorePosInfo(posInfo);
    listDataToDatatable();
});

// Column selectors
const tbExpensesList = $('.expenses-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    order: [[0, "desc"]],
});

// Add New Enterprise
$(document).on("click", ".btnAddExpense", function () {

    $(".span-modal-title").text(translate.add_expense);

    $(".btnSaveExpense").show();
    $(".btnEditExpense").hide();

    document.getElementById("frmAddEditExpenseData").reset();
    $(".expenses-table-details tbody tr").html("");

    $("#exp_id").val("");
    $("#exp_ent_id").val($("#ent_id_value").val());
    $("#exp_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());

    $("#exp_total").val(0);
    $("#span_exp_total").text(0.00);

    let expenseType = "Daily";
    if (currentLocation === 'fixed-expense') expenseType = "Fixed";
    $("#exp_type").val(expenseType);
    showAmount();

    $('#expense-modal').modal('show');
});

// List All Enterprises on click btnRefresh
$(document).on("click", ".btnSearch", function () {
    let btnRefresh = "clicked";
    listDataToDatatable(btnRefresh);
});

// Get data from API
async function getDataFromAPI(props) {
    try {

        const url = `ajax/expenses.ajax.php?op=ajaxExpensesList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&fromDate=${props.fromDate}&toDate=${props.toDate}&exp_type=${props.exp_type}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const res = await response.json();
        return res;

    } catch (error) {
        console.log(error);
        return false;
    }
}

// List All data function
async function listDataToDatatable(btnRefresh = '') {

    // ── Helper: restore search button ─────────────────────────────────────────
    function resetSearchButton() {
        $('.btnSearch')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-magnifying-glass me-1"></i> ${translate.search}`);
    }

    // ── Lock button while loading ─────────────────────────────────────────────
    $('.btnSearch')
        .prop('disabled', true)
        .css('cursor', 'not-allowed')
        .html(translate.loading_icon_text);

    // ── Collect filter parameters ─────────────────────────────────────────────
    const [fromDate, toDate] = $.trim($('.dateSelected').val()).split(' / ');

    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
        pos_id: ($("#pos_id_value").val() || '').trim(),
        exp_type: currentLocation === 'fixed-expense' ? 'Fixed' : 'Daily',
        fromDate,
        toDate,
    };

    // ── Validate required props ───────────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([, value]) => value === '' || value === undefined)
        .map(([key]) => key);

    if (missingProps.length > 0) {
        resetSearchButton();
        await swalInit.fire(translate.please_fill_in_all_required_fields, missingProps.join(', '), 'warning');
        return;
    }

    const pos_info = JSON.parse(localStorage.getItem('pos_info'));
    const fmt = val => showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, val);
    let totalFinal = 0;

    try {
        const res = await getDataFromAPI(props);

        if (res.status === 'success') {

            if (btnRefresh === 'clicked') {
                fnSweetToast(translate.data_loaded_successfully, 'success', 2000);
            }

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    totalFinal += Number(item.exp_total);

                    // Delete button hidden for Waiters
                    const btnDelete = sess_user_profile !== 'Waiter'
                        ? `<div class="dropdown-divider"></div>
                           <button type="button" class="dropdown-item text-danger danger-on-hover"
                                   onclick='jsDeleteData(${item.exp_id})'>
                               <i class="ph-trash me-1"></i> ${translate.delete}
                           </button>`
                        : '';

                    const btnOptions = `
                        <button type="button" class="btn btn-indigo dropdown-toggle"
                                data-bs-toggle="dropdown">${translate.action}</button>
                        <div class="dropdown-menu dropdown-menu-theme">
                            <button type="button" class="dropdown-item light-warning-on-hover"
                                    onclick='jsEditData(${JSON.stringify(item)})'>
                                <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                            </button>
                            ${btnDelete}
                        </div>`;

                    return [
                        item.exp_id,
                        item.pos_name,
                        item.exp_date_formated,
                        item.exp_type === 'Fixed' ? translate.fixed : translate.daily,
                        item.general_description,
                        fmt(item.exp_total),
                        btnOptions,
                    ];
                });

                tbExpensesList.clear().rows.add(formattedData).draw();

            } else {
                tbExpensesList.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbExpensesList.clear().draw();

        } else {

            tbExpensesList.clear().draw();
            console.error('listDataToDatatable unexpected response:', res);
            await swalInit.fire(
                translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
                '',
                'error'
            );
        }

    } catch (error) {
        tbExpensesList.clear().draw();
        console.error('listDataToDatatable error:', error);
        await swalInit.fire(
            translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
            '',
            'error'
        );

    } finally {
        resetSearchButton();
        $('#total-amount').text(fmt(totalFinal));
    }
}


/*=============================================
SHOW CUSTOMER INFORMATIONS
=============================================*/
function jsEditData(data) {

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    $(".span-modal-title").text(translate.edit_expense);

    $(".btnSaveExpense").hide();
    $(".btnEditExpense").show();

    document.getElementById("frmAddEditExpenseData").reset();
    // Modal form
    $("#exp_id").val(data.exp_id);
    $("#exp_ent_id").val(data.exp_ent_id);
    $("#exp_pos_id").val(data.exp_pos_id);
    $("#exp_total").val(data.exp_total);
    $("#span_exp_total").text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, data.exp_total));
    $("#exp_date").val(data.exp_date);
    $("#exp_type").val(data.exp_type);
    $(".pos_description").text(data.pos_name);

    $("#expense-modal").modal("show");

    fnShowExpenseDetails(data.exp_id);
}


/*=============================================
DELETE INFORMATIONS
=============================================*/
function jsDeleteData(exp_id) {

    $("#txtTransactionId").val("");
    $("#txtTransactionId").val(exp_id);
    $("#txtCancellationReason").val("");
    $("#txtCancellationReason").focus();
    $("#modalTransactionCancelReason").modal('show');
}


$(document).on("click", ".btnConfirmCancellationReason", function () {

    var transactionId = $("#txtTransactionId").val();
    var reason = $("#txtCancellationReason").val();

    if (reason === "" || transactionId === "") {
        fnSweetToast(translate.please_write_the_reason_for_the_cancellation, "warning", 3000);
        $("#txtCancellationReason").css("border", "1px solid #d33 ");
        return false;
    }

    $("#txtCancellationReason").css("border", `1px solid ${borderColorValidated}`);
    $("#modalTransactionCancelReason").modal('hide');
    jsConfirmDeleteData(transactionId, reason);
});

/*=============================================
DELETE INFORMATIONS
=============================================*/
async function jsConfirmDeleteData(id, reason) {

    var cancelParameters = {
        id: id,
        reason: reason,
        csrf_token: csrf_token
    }

    if (sess_user_profile == 'ROOT' || sess_user_profile == 'Owner') {

        swalInit.fire({
            title: translate.are_you_sure,
            text: translate.confirm_that_you_want_to_perform_this_action,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: translate.yes,
            cancelButtonText: translate.no,
            buttonsStyling: false,
            customClass: {
                confirmButton: 'btn btn-success',
                cancelButton: 'btn btn-danger'
            }
        }).then(function (result) {
            if (result.value) {

                $.post("ajax/expenses.ajax.php?op=ajax_delete_item", cancelParameters, function (response) {
                    // console.log(response)
                    response = JSON.parse(response);
                    swalInit.fire(response.title, response.message, response.type).then(function (result) {
                        listDataToDatatable();
                    });

                });
            }
        });

    } else {

        let entInfo = await jsGetEnterpriseData();
        console.log(entInfo);
        swalInit.fire({
            title: translate.cancellation_code,
            input: 'password',
            showCancelButton: true,
            inputPlaceholder: "**********",
            inputAttributes: {
                'autocapitalize': 'off',
                'autocorrect': 'off'
            },
            preConfirm: (value) => {
                if (!value) {
                    swalInit.showValidationMessage(translate.you_must_enter_the_password);
                    return false;
                } else if (value !== entInfo.ent_cancel_password) {
                    swalInit.showValidationMessage(translate.incorrect_password_please_try_again);
                    return false;
                }
                return value;
            },
            allowOutsideClick: false,
            allowEscapeKey: false,
            stopKeydownPropagation: false
        }).then((result) => {
            if (result.isConfirmed) {
                // Do something with the result
                $.post("ajax/expenses.ajax.php?op=ajax_delete_item", cancelParameters, function (response) {
                    // console.log(response)
                    response = JSON.parse(response);
                    swalInit.fire(response.title, response.message, response.type).then(function (result) {
                        listDataToDatatable();
                    });
                });

            } else if (result.dismiss === swalInit.DismissReason.cancel) {
                // $("#expense-modal").modal("show");
            }
        });

    }

}


/*=============================================
SHOW EXPENSE DETAILS
=============================================*/
async function fnShowExpenseDetails(exp_id) {
    try {

        const url = `ajax/expenses.ajax.php?op=ajaxShowExpenseDetails&exp_id=${exp_id}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const apiData = await response.json();
        // console.log(apiData)
        // return;

        const tbExpenseBody = document.getElementById('tbExpenseBody');
        let html = '';

        if (apiData.status == "success") {

            if (apiData.data.length > 0) {

                apiData.data.forEach(item => {
                    html += `<tr>
                        <td><button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removeExpenseRowSaved"><i class="mi-close" style="text-align: center;"></i></button></td>
                        <td><input type="text" class="form-control form-control-lg" autocomplete="off" required name="exp_det_description[]" value="${item.exp_det_description}"></td>
                        <td><input type="number" class="form-control form-control-lg costoRow" required name="exp_det_cost[]" step="0.01" placeholder="0.00" value="${item.exp_det_cost}"></td>
                    </tr>`;
                });

            } else {
                html += `<tr class='text-center'><td colspan='3'>No expense was added</td></tr>`;
            }
        }

        tbExpenseBody.innerHTML = html;
        showAmount();

    } catch (error) {
        console.log(error);
    }
}

/*=============================================
SUMAR TODOS LOS PRECIOS
=============================================*/

async function showAmount() {

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    /*========== SUMAR TODAS LAS CANTITADES AGREGADAS PARA LA CATIDAD DE PIEZAS ==========*/
    var quantity = $(".costoRow");
    var arraySumaQuantity = [];
    for (var i = 0; i < quantity.length; i++) {
        arraySumaQuantity.push(Number($(quantity[i]).val()));
    }

    // Providing an initial value of 0 if sumaTotalQuantity is empty
    var sumaTotalQuantity = arraySumaQuantity.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    var total_cost_expending = parseFloat(sumaTotalQuantity);
    var amountTotalCurrency = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, total_cost_expending);

    $("#span_exp_total").text(amountTotalCurrency);
    $("#exp_total").val(total_cost_expending);
}


/*=============================================
VALIDATE INPUT FORM
=============================================*/
function validation() {

    var exp_det_description = document.getElementsByName("exp_det_description[]");
    var exp_det_cost = document.getElementsByName("exp_det_cost[]");

    for (var i = 0; i < exp_det_description.length; i++) {
        var desc = exp_det_description[i];
        var cost = exp_det_cost[i];

        if (desc.value == "") {
            fnSweetToast(translate.enter_the_description_of_the_expense, "error", 3500);
            desc.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            desc.setAttribute("style", "border:light-gray 1px solid;");
        }

        if (cost.value.trim() == "") {
            fnSweetToast(translate.enter_the_amount_of_the_expense, "error", 3500);
            cost.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            cost.setAttribute("style", "border:light-gray 1px solid;");
        }
    }
}

/*=============================================
FUNCTION TO ADD NEW EXPENSE ROW
=============================================*/
$(".btnAddNewExpense").click(function () {
    if (validation() == false) {
        return false;
    } else {
        fnAddNewExpenseRow();
    }
});


/*=============================================
ADD NEW EXPENS ROW 
=============================================*/
function fnAddNewExpenseRow() {

    $(".expenses-table-details tbody").prepend(`
        <tr>
            <td><button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removeExpenseRow"><i class="mi-close" style="text-align: center;"></i></button>
            <td><input type="text" class="form-control form-control-lg" autocomplete="off" required name="exp_det_description[]"></td>
            <td><input type="number" class="form-control form-control-lg costoRow" name="exp_det_cost[]" step="0.01" placeholder="0.00" required></td>
        </tr>
    `);

    showAmount();
}


/*=============================================
FUNCTION TO REMOVE ROW
=============================================*/
$(document).on("click", ".removeExpenseRow", function () {

    $(this).parent().parent().remove();
    fnSweetToast(translate.row_removed, "success", 2000);
    showAmount();
});


/*=============================================
FUNCTION TO REMOVE ROW
=============================================*/
$(document).on("click", ".removeExpenseRowSaved", async function () {

    let thisButton = $(this);

    if (sess_user_profile == 'ROOT' || sess_user_profile == 'Owner') {

        swalInit.fire({
            title: translate.are_you_sure,
            text: translate.confirm_that_you_want_to_perform_this_action,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: translate.yes,
            cancelButtonText: translate.no,
            buttonsStyling: false,
            customClass: {
                confirmButton: 'btn btn-success',
                cancelButton: 'btn btn-danger'
            }
        }).then(function (result) {
            if (result.value) {
                thisButton.parent().parent().remove();
                fnSweetToast(translate.row_removed, "success", 2000);
                showAmount();
            }
        });

    } else {

        let entInfo = await jsGetEnterpriseData();

        $("#expense-modal").modal("hide");

        swalInit.fire({
            title: translate.cancellation_password,
            input: 'password',
            showCancelButton: true,
            inputPlaceholder: "**********",
            inputAttributes: {
                'autocapitalize': 'off',
                'autocorrect': 'off'
            },
            preConfirm: (value) => {
                if (!value) {
                    swalInit.showValidationMessage(translate.you_must_enter_the_password);
                    return false;
                } else if (value !== entInfo.ent_cancel_password) {
                    swalInit.showValidationMessage(translate.incorrect_password_please_try_again);
                    return false;
                }
                return value;
            },
            allowOutsideClick: false,
            allowEscapeKey: false,
            stopKeydownPropagation: false
        }).then((result) => {
            if (result.isConfirmed) {
                // Do something with the result
                $("#expense-modal").modal("show");
                setTimeout(() => {
                    thisButton.parent().parent().remove();
                    fnSweetToast(translate.row_removed, "success", 2000);
                    showAmount();
                }, 500);
            } else if (result.dismiss === swalInit.DismissReason.cancel) {
                $("#expense-modal").modal("show");
            }
        });

    }

});


/*=============================================
ON COST ROW CHANGE SUM SUB_TOTAL
=============================================*/
$(document).on("change", ".costoRow", function () {

    if (Number($(this).val()) < 0) {
        $(this).val(1);
        showAmount();
        swalInit.fire(translate.the_expense_amount_cannot_be_empty_or_less_than_0, translate.add_a_correct_amount, "warning");
        return;
    }

    showAmount();

});


/*=============================================
VALIDATE INPUT FORM
=============================================*/
function validationToSaved(type) {

    if (type === "edit") {

        var exp_id = $("#exp_id").val();

        if ($.trim(exp_id) == "" && Number(exp_id <= 0)) {
            fnSweetToast(translate.no_data_was_selected_for_updating, "error", 3500);
            return false;
        }
    }

    var expenseTableSize = $('.expenses-table-details tbody tr').length;

    if (expenseTableSize <= 0) {
        fnSweetToast(translate.no_expense_have_been_added, "error", 3500);
        return false;
    }

    var exp_det_description = document.getElementsByName("exp_det_description[]");
    var exp_det_cost = document.getElementsByName("exp_det_cost[]");

    for (var i = 0; i < exp_det_description.length; i++) {
        var desc = exp_det_description[i];
        var cost = exp_det_cost[i];

        if (desc.value == "") {
            fnSweetToast(translate.enter_the_description_of_the_expense, "error");
            desc.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            desc.setAttribute("style", "border:light-gray 1px solid;");
        }

        if (cost.value.trim() == "" || Number(cost.value) <= 0) {
            fnSweetToast(translate.enter_the_amount_of_the_expense, "error");
            cost.setAttribute("style", "border:red 1px solid;");
            return false;
        } else {
            cost.setAttribute("style", "border:light-gray 1px solid;");
        }
    }
}

$(".btnSaveExpense").click(function () {
    if (validationToSaved("save") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});


$(".btnEditExpense").click(function () {
    if (validationToSaved("edit") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

// ── Helper: set all action buttons to a given state ───────────────────────
function setButtonStatus(state) {
    if (state === 'loading') {
        $('.btnSaveExpense, .btnEditExpense')
            .prop('disabled', true)
            .css('cursor', 'not-allowed')
            .html(translate.waiting_icon_text);
        return;
    }
    if (state === 'ready') {
        $('.btnSaveExpense, .btnEditExpense')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-floppy-disk me-1"></i> ${translate.save}`);
    }
}

/*=============================================
FUNCTION TO SAVE OR UPDATE DATA
=============================================*/
async function fnSaveUpdate() {

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmAddEditExpenseData")[0]);
    const apiUrl = 'ajax/expenses.ajax.php?op=ajaxSaveUpdate';

    // for (var pair of formPostData.entries()) {
    //     console.log(pair[0] + " - " + pair[1]);
    // }
    // return;

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            body: formPostData,
        });


        const res = await response.json();
        // console.log(res);

        if (res.status == "success") {

            setButtonStatus('ready');

            document.getElementById("frmAddEditExpenseData").reset();
            fnSweetAlert(res.message, "", res.status, 1500);
            $("#expense-modal").modal("hide");
            listDataToDatatable();

        } else {
            console.log(res);
            swalInit.fire(translate.data_could_not_be_saved, "", res.status).then(function (result) {
                $("#expense-modal").modal("hide");
                document.getElementById("frmAddEditExpenseData").reset();
                setButtonStatus('ready');
            });
        }

    } catch (error) {
        console.error('Error:', error);
        swalInit.fire(translate.data_could_not_be_saved, "", "error").then(function (result) {
            $("#expense-modal").modal("hide");
            document.getElementById("frmAddEditExpenseData").reset();
            setButtonStatus('ready');
        });
    }
}