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 tbProductsList = $('.products-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", ".btnAddProduct", async function () {

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

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

    let ent_id = $.trim($("#ent_id_value").val());
    let pos_id = $.trim($("#pos_id_value").val());

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

    fnSelectCategoriesList(ent_id, pos_id);

    $("#pro_id").val("");
    $("#pro_ent_id").val(ent_id);
    $("#pro_pos_id").val(pos_id);
    $("#pro_type").val("Product").trigger('change');
    $(".pos_description").text($("#pos_id_value option:selected").text());

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

    if (pos_info.pos_business_category == "Others") {
        $(".divFestivePrice").hide();
    } else {
        $(".divFestivePrice").show();
    }

    $(".picturePreview").attr("src", "assets/images/no-image.png");

    $('#product-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/products.ajax.php?op=ajaxProductsList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&pro_status=${props.pro_status}&pro_type=${props.pro_type}`;
        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 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}`);
    }

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

    // ── Helper: stock badge — FULL guard must come first ──────────────────────
    function buildStockBadge(stockRaw) {
        if (stockRaw === 'FULL') {
            return `<span class="badge bg-primary fw-medium text-white">FULL</span>`;
        }

        const stock = Number(stockRaw);
        const badgeColour = stock > 20 ? 'bg-success'
            : stock > 10 ? 'bg-warning'
                : 'bg-danger';

        return `<span class="badge ${badgeColour} fw-medium text-white">${stockRaw}</span>`;
    }

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

    // ── Collect filter parameters ─────────────────────────────────────────────
    const pos_info = JSON.parse(localStorage.getItem('pos_info'));
    const fmt = val => showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, val);
    const posCategory = { pos_business_category: pos_info.pos_business_category };

    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
        pos_id: ($("#pos_id_value").val() || '').trim(),
        pro_status: ($(".searchStatus").val() || '').trim(),
        pro_type: ($(".searchType").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') {

            // ── Apply column visibility now that data is confirmed ────────────
            tbProductsList.column(6).visible(pos_info.pos_business_category !== 'Others');

            const isRestrictedProfile = sess_user_profile === 'Waiter' || sess_user_profile === 'Cashier';
            tbProductsList.column(8).visible(!isRestrictedProfile);
            tbProductsList.column(9).visible(!isRestrictedProfile);

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

            if (res.data.length > 0) {

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

                    // Merge pos category into item for edit/adjust handlers
                    const dataDetails = { ...item, ...posCategory };
                    const dataDetailsJson = JSON.stringify(dataDetails);

                    const isService = item.stock_actual === 'FULL';

                    // Service products have no stock to adjust — show edit only
                    const btnOptions = isService
                        ? `<button type="button" class="btn btn-sm btn-indigo"
                                   onclick='jsEditData(${dataDetailsJson})'>
                               <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                           </button>`
                        : `<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(${dataDetailsJson})'>
                                   <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                               </button>
                               <button type="button" class="dropdown-item light-warning-on-hover"
                                       onclick='jsStockAdjustment(${dataDetailsJson})'>
                                   <i class="ph-arrows-down-up me-1"></i> ${translate.stock_adjust}
                               </button>
                           </div>`;

                    return [
                        item.pro_id,
                        item.pro_code,
                        `<img src="${item.pro_image || 'assets/images/no-image.png'}"
                              class="w-32px h-32px rounded-pill"
                              onerror="this.onerror=null;this.src='assets/images/no-image.png';">`,
                        item.cat_name ?? '--',
                        item.pro_description,
                        fmt(item.pro_price),
                        fmt(item.pro_price_party),
                        buildStockBadge(item.stock_actual),
                        buildToggle(
                            item.pro_status !== 'Disabled',
                            'jsSwitchStatus',
                            item.pro_id,
                            'Disabled',
                            'Enabled'
                        ),
                        btnOptions,
                    ];
                });

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

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

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

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

        } else {

            tbProductsList.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) {
        tbProductsList.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(pro_id, status, thisSwitcher, switcher) {

    let props = {
        pro_id: pro_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: 'warning',
        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/products.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;
            }
        }
    });
}


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

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

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

    document.getElementById("frmAddEditProduct").reset();
    // Modal form
    $("#pro_id").val(data.pro_id);
    $("#pro_ent_id").val(data.pro_ent_id);
    $("#pro_pos_id").val(data.pro_pos_id);
    $("#pro_description").val(data.pro_description);
    $("#pro_code").val(data.pro_code);
    $("#pro_cat_id").val(fnSelectCategoriesList(data.pro_ent_id, data.pro_pos_id, data.pro_cat_id));
    $("#pro_type").val(data.pro_type).trigger('change');
    $("#pro_sale_measure").val(data.pro_sale_measure);
    $("#pro_price").val(data.pro_price);
    $("#pro_price_party").val(data.pro_price_party);
    $(".pos_description").text(data.pos_name);

    if (data.pos_business_category == "Others") {
        $(".divFestivePrice").hide();
    } else {
        $(".divFestivePrice").show();
    }

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

    $("#product-modal").modal("show");
}

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

    document.getElementById("frmStockAdjust").reset();
    // Modal form
    $("#adjust_product_id").val(data.pro_id);
    $(".pos_description").text(data.pos_name);
    $("#pro_id").val(data.pro_id);
    $("#adjust_current_stock").val(data.stock_actual);
    $("#span_final_stock").text(data.stock_actual);
    $("#span_pro_description").text(data.pro_description);
    $("#span_current_stock").text(data.stock_actual);
    $("#adjust_ent_id").val($("#ent_id_value").val());
    $("#adjust_pos_id").val($("#pos_id_value").val());

    $("#stock-adjust-modal").modal("show");
}


$(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);
        })
    }
});



/*================================================
FUNCTION TO SHOW ALL CLIENTS LIST
=================================================*/
async function fnSelectCategoriesList(sess_user_id, pos_id, pro_cat_id = "") {
    try {

        const url = `ajax/categories.ajax.php?op=ajaxSelectList&ent_id=${sess_user_id}&pos_id=${pos_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#pro_cat_id").html("");

        if (res.status == "success") {
            res.data.forEach(item => {
                let selected = item.cat_id === pro_cat_id ? "selected" : "";
                $("#pro_cat_id").append(`<option value='${item.cat_id}' ${selected}>${item.cat_name}</option>`);
            });
        }

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


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

    if (type == "edit") {

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

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

    var pro_description = $("#pro_description").val();
    var pro_price = $("#pro_price").val();

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

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

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


$(".btnEdit").click(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, .btnSaveAdjustStock')
            .prop('disabled', true)
            .css('cursor', 'not-allowed')
            .html(translate.loading_icon_text);
        return;
    }
    if (state === 'ready') {
        $('.btnSave, .btnEdit, .btnSaveAdjustStock')
            .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($("#frmAddEditProduct")[0]);
    const apiUrl = 'ajax/products.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("frmAddEditProduct").reset();
            fnSweetAlert(data.message, "", data.status, 1000);
            $("#product-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);
            swalInit.fire(translate.data_could_not_be_saved, "", data.status).then(function (result) {
                $("#product-modal").modal("hide");
                document.getElementById("frmAddEditProduct").reset();
                setButtonStatus('ready');
            });
        }

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

document.getElementById('adjust_quantity').addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
        event.preventDefault(); // Prevent the form from submitting
    }
});

$(document).on("change", "#adjust_type", function () {
    $("#adjust_quantity").trigger("change");
});

$(document).on("change", "#adjust_quantity", function () {

    if (this.value < 0) this.value = 0;

    let adjust_type = $("#adjust_type").val();
    let adjust_quantity = this.value;
    let adjust_current_stock = $("#adjust_current_stock").val();

    let final_stock = Number(adjust_current_stock) + Number(adjust_quantity);

    if (adjust_type == "Decrease") {

        final_stock = Number(adjust_current_stock) - Number(adjust_quantity);

        if (final_stock < 0 || adjust_current_stock == 0) {
            final_stock = 0;
            this.value = adjust_current_stock;
        }
    }

    $("#span_final_stock").text(decimalNumberFormat(final_stock));

});

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

    var adjust_product_id = $("#adjust_product_id").val();
    var adjust_quantity = $("#adjust_quantity").val();
    var adjust_reason = $("#adjust_reason").val();

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

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

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

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


//Función para guardar o editar
$('.btnSaveAdjustStock').click(function () {
    if (stockAdjustementInputValidation() == false) {
        return false;
    } else {
        fnSaveAdjustStock();
    }
});

async function fnSaveAdjustStock() {

    const formPostData = new FormData($("#frmStockAdjust")[0]);
    const apiUrl = 'ajax/stock-adjustment.ajax.php?op=ajaxSaveStockAdjustment';

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

    setButtonStatus('loading');

    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("frmStockAdjust").reset();
            fnSweetAlert(data.message, "", data.status, 1500);
            $("#stock-adjust-modal").modal("hide");
            listDataToDatatable();

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

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