if (currentLocation === 'enterprise') {
    jsShowEnterprise(sess_ent_id);
}

if (currentLocation === 'enterprises') {
    listDataToDatatable();
}

// Column selectors
const tbEnterpriseList = $('.enterprise-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: true,
});

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

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

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

    document.getElementById("frmEnterprise").reset();
    $("#ent_id").val("");
    $("#ent_document").val("EIN").trigger('change');
    $(".picturePreview").attr("src", "assets/images/no-image.png");

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

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

// List All Enterprises on change status
$(document).on("change", ".searchStatus", function () {
    listDataToDatatable();
});


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

        const url = `ajax/enterprises.ajax.php?op=ajaxEnterpriseList&ent_status=${props.ent_status}`;
        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, labelOn = translate.enabled, labelOff = translate.disabled) {
        const [nextVal, state, label] = isOn
            ? [onValue, 'checked', labelOn]
            : [offValue, 'unchecked', labelOff];

        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_status: ($('.searchStatus').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 => [
                    item.ent_id,
                    `<img src="${item.ent_logo || 'assets/images/no-image.png'}"
                          class="w-32px h-32px rounded-pill"
                          onerror="this.onerror=null;this.src='assets/images/no-image.png';">`,
                    item.ent_name,
                    `${item.ent_document}: ${item.ent_document_number}`,
                    item.ent_email || '__',
                    buildToggle(item.ent_show_notification !== 'No', 'jsSwitchNotificationStatus', item.ent_id, 'No', 'Yes', translate.yes, translate.no),
                    buildToggle(item.ent_email_report !== 'Disabled', 'jsSwitchEmailReportStatus', item.ent_id, 'Disabled', 'Enabled'),
                    buildToggle(item.ent_status !== 'Disabled', 'jsSwitchStatus', item.ent_id, 'Disabled', 'Enabled'),
                    buildToggle(item.ent_contract_status !== 'Disabled', 'jsSwitchContractStatus', item.ent_id, 'Disabled', 'Enabled'),
                    `<button type="button" class="btn btn-sm btn-indigo"
                             onclick='jsEditEnterprise(${JSON.stringify(item)})'>
                         <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                     </button>`,
                ]);

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

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

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

            tbEnterpriseList.clear().draw();
            // Warning means no data — do not toast "loaded successfully"

        } else {

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

// Edit enterprise function
function jsEditEnterprise(data) {

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

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

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

    $("#ent_id").val(data.ent_id);
    $("#ent_name").val(data.ent_name);
    $("#ent_document").val(data.ent_document).trigger('change');
    $("#ent_document_number").val(data.ent_document_number);
    $("#ent_email").val(data.ent_email);
    $("#ent_url").val(data.ent_url);
    $("#ent_website_url").val(data.ent_website_url);
    $("#ent_online_billing_status").val(data.ent_online_billing_status).trigger('change');
    $("#ent_plan_id").val(data.ent_plan_id).trigger('change');
    $("#ent_cancel_password").val(data.ent_cancel_password);
    $("#ent_discount_password").val(data.ent_discount_password);
    $("#ent_statistic_password").val(data.ent_statistic_password);
    $("#ent_notification_text").val(data.ent_notification_text);

    let imagePath = data.ent_logo || "assets/images/no-image.png";
    $(".picturePreview").off("error").on("error", function () {
        $(this).off("error").attr("src", "assets/images/no-image.png");
    }).attr("src", imagePath);

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

}

// Edit enterprise function
async function jsShowEnterprise(ent_id) {

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

    try {

        const url = `ajax/enterprises.ajax.php?op=ajaxGetEnterpriseData&ent_id=${ent_id}`;
        const response = await fetch(url);

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

        const data = await response.json();

        // console.log(data);

        $("#ent_id").val(data.ent_id);
        $("#ent_name").val(data.ent_name);
        $("#ent_document").val(data.ent_document).trigger('change');
        $("#ent_document_number").val(data.ent_document_number);
        $("#ent_email").val(data.ent_email);
        $("#ent_url").val(data.ent_url);
        $("#ent_website_url").val(data.ent_website_url);
        $("#ent_cancel_password").val(data.ent_cancel_password);
        $("#ent_discount_password").val(data.ent_discount_password);
        $("#ent_statistic_password").val(data.ent_statistic_password);
        $("#ent_notification_text").val(data.ent_notification_text);

        let imagePath = data.ent_logo || "assets/images/no-image.png";
        $(".picturePreview").off("error").on("error", function () {
            $(this).off("error").attr("src", "assets/images/no-image.png");
        }).attr("src", imagePath);

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



$(document).on("change", ".new_picture", function () {

    var imageUploaded = this.files[0];

    //image validation
    if (imageUploaded["type"] != "image/jpeg" && imageUploaded["type"] != "image/jpg" && imageUploaded["type"] != "image/png") {

        $(".new_picture").val("");

        fnSweetToast(translate.the_image_must_be_in_jpg_jpeg_or_png_forma, "error", 3500);

    } else if (imageUploaded["size"] > 2000000) {

        $(".new_picture").val("");

        fnSweetToast(translate.the_image_must_not_exceed_2m, "error", 3500);

    } else {

        var imageData = new FileReader;
        imageData.readAsDataURL(imageUploaded);

        $(imageData).on("load", function (event) {
            var imagePath = event.target.result;
            $(".picturePreview").attr("src", imagePath);
        })
    }
});


// Validation input form
function validateInputFormData(type) {

    if (type == "edit") {

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

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

    var ent_name = $("#ent_name").val();
    var ent_email = $("#ent_email").val();

    if ($.trim(ent_name) == "") {
        $("#ent_name").css("border", "1px solid red ");
        fnSweetToast(translate.you_must_enter_the_enterprise_name, "error", 3500);
        return false;
    } else {
        $("#ent_name").css("border", `1px solid ${borderColorValidated}`);
    }

    if (ent_email != "") {
        if (validateEmail(ent_email.trim()) == false) {
            $("#ent_email").css("border", "1px solid red ");
            fnSweetToast(translate.invalid_email_address, "error", 3500);
            return false;
        } else {
            $("#ent_email").css("border", `1px solid ${borderColorValidated}`);
        }
    }
}


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

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

// ── 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($("#frmEnterprise")[0]);
    const apiUrl = 'ajax/enterprises.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();

        if (data.status == "success") {
            setButtonStatus('ready');

            await swalInit.fire(data.message, "", data.status).then(function (result) {

                if (currentLocation === 'enterprise') {
                    location.reload();
                } else {
                    document.getElementById("frmEnterprise").reset();
                    $("#enterprise-modal").modal("hide");
                    listDataToDatatable();
                }
            });

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

            // console.error('Save failed:', res);
            setButtonStatus('ready');

            // Show all failures, let user fix and retry
            await swalInit.fire(data.message, "", data.status);

        } else {

            console.log(data);
            setButtonStatus('ready');
            await swalInit.fire(translate.data_could_not_be_saved, "", 'error');
        }

    } catch (error) {
        console.error('Error:', error);
        await swalInit.fire(translate.data_could_not_be_saved, "", "error").then(function (result) {

            if (currentLocation === 'enterprise') {
                location.reload();
            } else {
                setButtonStatus('ready');
                document.getElementById("frmEnterprise").reset();
                $("#enterprise-modal").modal("hide");
                listDataToDatatable();
            }
        });
    }
}

// Enable or disable status
async function jsSwitchEmailReportStatus(ent_id, status, thisSwitcher, switcher) {

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

    let text = translate.confirm_that_you_want_to_disable_this_account;
    if (status == 'Enabled') text = translate.confirm_that_you_want_to_enable_this_account;

    swalInit.fire({
        title: translate.are_you_sure,
        text: text,
        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/enterprises.ajax.php?op=ajaxSwitchEmailReportStatus",
                    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;
            }
        }
    });
}

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

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

    let text = translate.confirm_that_you_want_to_disable_this_account;
    if (status == 'Enabled') text = translate.confirm_that_you_want_to_enable_this_account;

    swalInit.fire({
        title: translate.are_you_sure,
        text: text,
        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/enterprises.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;
            }
        }
    });
}

// Enable or disable enterprise status
async function jsSwitchNotificationStatus(ent_id, status, thisSwitcher, switcher) {

    let props = {
        ent_id: ent_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/enterprises.ajax.php?op=ajax_show_notification_status",
                    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;
            }
        }
    });
}

// Enable or disable enterprise status
async function jsSwitchContractStatus(ent_id, status, thisSwitcher, switcher) {

    let props = {
        ent_id: ent_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/enterprises.ajax.php?op=ajaxEntContractStatus",
                    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;
            }
        }
    });
}