listDataToDatatable();

// Column selectors
const tbTaxReceiptList = $('.tax-receipt-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'
            }
        ]
    }
});

// Column selectors
const tbTaxReceiptRequestHistory = $('.tax-receipt-request-history-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", ".btnAddNew", function () {

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

    $(".btnSave").show();
    $(".btnEdit").hide();

    document.getElementById("frmAddTaxReceipt").reset();

    $("#fis_rec_id").val("");
    $("#fis_rec_ent_id").val($("#ent_id_value").val());

    $('#myModalAddTaxReceipt').modal('show');
});

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

$(document).on("change", "#sale_type_add_tax", function () {
    if ($(this).val() <= 0) $(this).val(0);
});

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

        const url = `ajax/tax-receipt.ajax.php?op=ajaxTaxReceiptList&ent_id=${props.ent_id}`;
        const response = await fetch(url);

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

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

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

// List All Enterprises 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}`);
    }

    // ── Helper: build a toggle switch ─────────────────────────────────────────
    function buildToggle(isOn, handlerFn, id, onValue, offValue) {
        const [nextVal, state, label] = isOn
            ? [onValue, 'checked', translate.enabled]
            : [offValue, 'unchecked', translate.disabled];

        return `
            <div class="form-check form-switch mb-2">
                <input type="checkbox"
                       class="form-check-input form-check-input-success"
                       onclick="${handlerFn}(${id},'${nextVal}',this,'${state}')"
                       ${isOn ? 'checked' : ''}>
                <label class="form-check-label">${label}</label>
            </div>`;
    }

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

    // ── Collect filter parameters ─────────────────────────────────────────────
    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
    };

    // ── 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;
    }

    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 => {

                    const itemJson = JSON.stringify(item);

                    // ── ROOT-only extra buttons ───────────────────────────────
                    const btnRootOnly = sess_user_profile === 'ROOT'
                        ? `<button type="button" class="dropdown-item light-warning-on-hover"
                                   onclick='jsEditData(${itemJson})'>
                               <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                           </button>
                           <button type="button" class="dropdown-item danger-on-hover text-danger"
                                   onclick='jsResetTaxReceipt(${itemJson})'>
                               <i class="ph-warning me-1"></i> ${translate.reset}
                           </button>`
                        : '';

                    // ── Action dropdown (shared core + conditional ROOT items) ─
                    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='jsNewTaxReceiptRequest(${itemJson})'>
                                <i class="ph-plus me-1"></i> ${translate.add}
                            </button>
                            <button type="button" class="dropdown-item light-warning-on-hover"
                                    onclick='jsViewTaxReceiptHistory(${itemJson})'>
                                <i class="ph-newspaper me-1"></i> ${translate.history}
                            </button>
                            ${btnRootOnly}
                        </div>`;

                    return [
                        item.fis_rec_id,
                        item.fis_rec_type,
                        item.fis_rec_description,
                        item.fiscal_stock_actual,
                        item.fiscal_stock_used,
                        buildToggle(
                            item.fis_rec_status !== 'Disabled',
                            'jsSwitchStatus',
                            item.fis_rec_id,
                            'Disabled',
                            'Enabled'
                        ),
                        btnOptions,
                    ];
                });

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

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

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

            tbTaxReceiptList.clear().draw();

        } else {

            tbTaxReceiptList.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) {
        tbTaxReceiptList.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();
    }
}

// Enable or disable status
async function jsSwitchStatus(fis_rec_id, status, thisSwitcher, switcher) {

    let props = {
        fis_rec_id: fis_rec_id,
        status: status,
        csrf_token: csrf_token
    }

    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(async function (result) {
        if (result.value) {

            try {

                const response = await $.ajax({
                    type: "POST",
                    url: "ajax/tax-receipt.ajax.php?op=ajaxSwitchStatus",
                    data: props,
                });

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}

$(document).on("change", "#fiscal_entry_from", function () {
    if ($(this).val() <= 0) $(this).val(0);
    jsCalculateAprovedTax();
});

$(document).on("change", "#fiscal_entry_to", function () {
    if ($(this).val() <= 0) $(this).val(0);
    jsCalculateAprovedTax();
});

$(document).on("change", "#fiscal_entry_approved", function () {
    jsCalculateAprovedTax();
});

function jsCalculateAprovedTax() {
    let from = $("#fiscal_entry_from").val();
    let to = $("#fiscal_entry_to").val();
    let total = Number(to) - Number(from);
    $("#fiscal_entry_approved").val(total);
}

// Edit enterprise function
function jsNewTaxReceiptRequest(data) {


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

    if (data.fis_rec_status == 'Disabled') {
        fnSweetToast(translate.this_tax_receipt_is_disabled, "warning", 3500);
        return false;
    }

    document.getElementById("frmNewTaxReceiptRequest").reset();

    $("#fis_rec_description_stock").text(`${data.fis_rec_type} - ${data.fis_rec_description}`);
    $("#fiscal_entry_fis_rec_id").val(data.fis_rec_id);
    $("#fiscal_entry_ent_id").val(data.fis_rec_ent_id);
    $("#fiscal_entry_type").val(data.fis_rec_type);
    $("#fiscal_entry_description").val(data.fis_rec_description);
    jsCalculateAprovedTax();

    $('#myModalNewTaxReceiptRequest').modal("show");
}

// Edit enterprise function
function jsEditData(data) {

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

    $(".btnSave").hide();
    $(".btnEdit").show();

    document.getElementById("frmAddTaxReceipt").reset();

    $("#fis_rec_id").val(data.fis_rec_id);
    $("#fis_rec_ent_id").val(data.fis_rec_ent_id);
    $("#fis_rec_type").val(data.fis_rec_type);
    $("#fis_rec_description").val(data.fis_rec_description);


    $("#myModalAddTaxReceipt").modal("show");
}


$(document).on("change", "#sale_type_add_tax", function () {
    if ($(this).val() < 0) $(this).val(0);
});

// Validation input form
function validateInputFormData(type) {

    var fis_rec_ent_id = $("#fis_rec_ent_id").val();
    var fis_rec_type = $("#fis_rec_type").val();
    var fis_rec_description = $("#fis_rec_description").val();

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

    if ($.trim(fis_rec_type) == "") {
        $("#fis_rec_type").css("border", "1px solid red ");
        fnSweetToast(translate.this_field_can_not_be_empty, "warning");
        return false;
    } else {
        $("#fis_rec_type").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($.trim(fis_rec_description) == "") {
        $("#fis_rec_description").css("border", "1px solid red ");
        fnSweetToast(translate.this_field_can_not_be_empty, "warning");
        return false;
    } else {
        $("#fis_rec_description").css("border", `1px solid ${borderColorValidated}`);
    }
}


// Save enterprise function
$(document).on("click", ".btnSave", function () {
    if (validateInputFormData("save") == false) {
        return false;
    } else {
        checkIfNotExist();
    }
});

// Save enterprise function
$(document).on("click", ".btnEdit", function () {
    if (validateInputFormData("edit") == false) {
        return false;
    } else {
        checkIfNotExist();
    }
});


async function checkIfNotExist() {

    var ent_id = $("#ent_id_value").val();
    var fis_rec_id = $("#fis_rec_id").val();
    var fis_rec_type = $("#fis_rec_type").val();

    try {

        const url = `ajax/tax-receipt.ajax.php?op=ajaxCheckIfNotExist&ent_id=${ent_id}&fis_rec_id=${fis_rec_id}&fis_rec_type=${fis_rec_type}`;
        const response = await fetch(url);

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

        const res = await response.json();

        if (res.status == "success" && res.data.fis_rec_type_quantity >= 1) {
            fnSweetToast(translate.this_type_of_tax_receipt_already_exists_please_try_with_another, 'error', 4000)
            $("#fis_rec_type").css("border", "1px solid red ");
            return false;
        } else {
            $("#fis_rec_type").css("border", `1px solid ${borderColorValidated}`);
            fnSaveUpdate();
        }

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

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

// Save and Edit enterprise function
async function fnSaveUpdate() {

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmAddTaxReceipt")[0]);
    const apiUrl = 'ajax/tax-receipt.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 data = await response.json();
        // console.log(data);

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

            setButtonStatus('ready');
            document.getElementById("frmAddTaxReceipt").reset();
            fnSweetAlert(data.message, "", data.status, 1500);
            $("#myModalAddTaxReceipt").modal("hide");
            listDataToDatatable();

        } else {
            console.log(data);
            swalInit.fire(translate.data_could_not_be_saved, "", data.status).then(function (result) {
                setButtonStatus('ready');
            });
        }

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

// Validation input form
function validateInputFormDataNewRequest(type) {

    var fiscal_entry_ent_id = $("#fiscal_entry_ent_id").val();
    var fiscal_entry_from = $("#fiscal_entry_from").val();
    var fiscal_entry_to = $("#fiscal_entry_to").val();
    var fiscal_entry_approved = $("#fiscal_entry_approved").val();
    var fiscal_entry_expire_date = $("#fiscal_entry_expire_date").val();

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

    if ($.trim(fiscal_entry_from) == "" && Number(fiscal_entry_from <= 0)) {
        $("#fiscal_entry_from").css("border", "1px solid red ");
        fnSweetToast(translate.this_field_can_not_be_empty, "warning");
        return false;
    } else {
        $("#fiscal_entry_from").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($.trim(fiscal_entry_to) == "" && Number(fiscal_entry_to <= 0)) {
        $("#fiscal_entry_to").css("border", "1px solid red ");
        fnSweetToast(translate.this_field_can_not_be_empty, "warning");
        return false;
    } else {
        $("#fiscal_entry_to").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($.trim(fiscal_entry_approved) == "" && Number(fiscal_entry_approved <= 0)) {
        $("#fiscal_entry_approved").css("border", "1px solid red ");
        fnSweetToast(translate.this_field_can_not_be_empty, "warning");
        return false;
    } else {
        $("#fiscal_entry_approved").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($.trim(fiscal_entry_expire_date) == "") {
        $("#fiscal_entry_expire_date").css("border", "1px solid red ");
        fnSweetToast(translate.this_field_can_not_be_empty, "warning");
        return false;
    } else {
        $("#fiscal_entry_expire_date").css("border", `1px solid ${borderColorValidated}`);
    }
}


// Save enterprise function
$(document).on("click", ".btnSaveNewTaxReceiptRequest", function () {
    if (validateInputFormDataNewRequest("save") == false) {
        return false;
    } else {
        fnSaveNewRequest();
    }
});

// Save and Edit enterprise function
async function fnSaveNewRequest() {

    $(".btnSaveNewTaxReceiptRequest").prop("disabled", true);
    $('.btnSaveNewTaxReceiptRequest').css('cursor', 'not-allowed');
    $(".btnSaveNewTaxReceiptRequest").html(`${translate.loading_icon_text}`);

    const formPostData = new FormData($("#frmNewTaxReceiptRequest")[0]);
    const apiUrl = 'ajax/tax-receipt.ajax.php?op=ajaxSaveNewRequest';

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

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

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

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

            $(".btnSaveNewTaxReceiptRequest").prop("disabled", false);
            $('.btnSaveNewTaxReceiptRequest').css('cursor', 'pointer');
            $(".btnSaveNewTaxReceiptRequest").html(`<i class="ph-floppy-disk-back me-1"></i> ${translate.save}`);

            document.getElementById("frmNewTaxReceiptRequest").reset();
            fnSweetAlert(data.message, "", data.status, 1500);
            $("#myModalNewTaxReceiptRequest").modal("hide");
            listDataToDatatable();

        } else {
            console.log(data);
            swalInit.fire(translate.data_could_not_be_saved, "", data.status).then(function (result) {
                $(".btnSaveNewTaxReceiptRequest").prop("disabled", false);
                $('.btnSaveNewTaxReceiptRequest').css('cursor', 'pointer');
                $(".btnSaveNewTaxReceiptRequest").html(`<i class="ph-floppy-disk-back me-1"></i> ${translate.save}`);

            });
        }

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

            $(".btnSaveNewTaxReceiptRequest").prop("disabled", false);
            $('.btnSaveNewTaxReceiptRequest').css('cursor', 'pointer');
            $(".btnSaveNewTaxReceiptRequest").html(`<i class="ph-floppy-disk-back me-1"></i> ${translate.save}`);

        });
    }
}

async function jsViewTaxReceiptHistory(data) {

    const { fis_rec_id, fis_rec_ent_id } = data;

    try {
        const url = `ajax/tax-receipt.ajax.php?op=ajaxTaxReceiptRequestHistory`
            + `&fis_rec_id=${encodeURIComponent(fis_rec_id)}`
            + `&fis_rec_ent_id=${encodeURIComponent(fis_rec_ent_id)}`;

        const response = await fetch(url);

        if (!response.ok) {
            throw new Error(`HTTP error — status: ${response.status}`);
        }

        const res = await response.json();

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

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => [
                    item.fiscal_entry_id,
                    item.fiscal_entry_type,
                    item.fiscal_entry_from,
                    item.fiscal_entry_to,
                    item.fiscal_entry_approved,
                    item.fiscal_entry_expire_date,
                ]);

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

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

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

            tbTaxReceiptRequestHistory.clear().draw();

        } else {

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

        // Always open the modal after data is resolved — success, warning, or empty
        $('#taxReceiptRequestHistoryModal').modal('show');

    } catch (error) {
        console.error('jsViewTaxReceiptHistory error:', error);
        await swalInit.fire(
            translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
            '',
            'error'
        );
    }
}


async function jsResetTaxReceipt(data) {

    let props = {
        fis_rec_id: data.fis_rec_id,
        fis_rec_ent_id: data.fis_rec_ent_id,
        csrf_token: csrf_token
    }

    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(async function (result) {
        if (result.value) {

            try {

                const response = await $.ajax({
                    type: "POST",
                    url: "ajax/tax-receipt.ajax.php?op=ajaxResetTaxReceipt",
                    data: props,
                });

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

            } catch (error) {
                console.error('Error:', error);
            }
        }
    });
}