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 tbPurchasesList = $('.purchases-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"]],
});

// Column selectors
const tbProductPurchaseList = $('.tbProductPurchaseList').DataTable({
    buttons: {
        buttons: [""]
    },
    order: false,
});

// Column selectors
const tbViewPurchaseDetails = $('.tbViewPurchaseDetails').DataTable({
    buttons: {
        buttons: [""]
    },
    paging: false,
    searching: false,
    info: false,
    order: false,
});

// Column selectors
const tbAddEditPurchaseDetails = $('.tbAddEditPurchaseDetails').DataTable({
    buttons: {
        buttons: [""]
    },
    paging: false,
    searching: false,
    info: false,
    order: false,
});

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

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

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

    document.getElementById("frmAddEditPurchaseData").reset();
    $(".tbAddEditPurchaseDetails tbody tr").html("");

    $("#pur_id").val("");
    $("#pur_ent_id").val($("#ent_id_value").val());
    $("#pur_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());

    $("#pur_total").val(0);
    $("#span_pur_total").text('0.00');
    $("#spanTotalPurchase").text('0.00');
    $("#spanTotalSale").text('0.00');
    $("#spanTotalProfit").text('0.00');
    $("#pur_shipping").val(0);

    // showAmount();
    fnSelectProvidersList($("#ent_id_value").val(), "");

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


/*================================================
FUNCTION TO SHOW ALL CLIENTS LIST
=================================================*/
async function fnSelectProvidersList(ent_id = "", prov_id = "") {
    try {

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

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

        const res = await response.json();

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

        if (prov_id == "") {
            $("#pur_provider_id").append(`<option value="">-- ${translate.select} --</option>`);
        }

        if (res.status == "success") {
            res.data.forEach(item => {
                $("#pur_provider_id").append(`<option value='${item.prov_id}'>${item.prov_name}</option>`);
            });

            // if (prov_id > 0) {
            $("#pur_provider_id").trigger("change");
            // }
        }

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

// 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/purchases.ajax.php?op=ajaxPurchasesList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&fromDate=${props.fromDate}&toDate=${props.toDate}&status=${props.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 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(),
        status: ($(".searchStatus").val() || '').trim(),
        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 finalCost = 0;
    let finalSale = 0;
    let finalBenefit = 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 => {

                    const isCancelled = item.pur_status === 'Disabled';

                    // ── Running totals ────────────────────────────────────────
                    finalCost += Number(item.pur_cost);
                    finalSale += Number(item.total_precio_venta);
                    finalBenefit += Number(item.total_ganancia);

                    // ── Computed display values ───────────────────────────────
                    const totalCost = Number(item.pur_cost) + Number(item.pur_shipping);
                    const totalBenefit = Number(item.total_ganancia) - Number(item.pur_shipping);

                    // ── Status badge ──────────────────────────────────────────
                    const purchaseStatus = isCancelled
                        ? `<span class="badge bg-danger  fw-medium text-white fs-md">${translate.canceled_f}</span>`
                        : `<span class="badge bg-success fw-medium text-white fs-md">${translate.active_f}</span>`;

                    // ── Action buttons hidden when cancelled ──────────────────
                    const transactionInfo = { transaction_id: item.pur_id, section: 'purchases' };
                    const transactionInfoJson = JSON.stringify(transactionInfo);
                    const itemJson = JSON.stringify(item);

                    const btnEdit = !isCancelled
                        ? `<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>`
                        : '';

                    const btnCancel = !isCancelled
                        ? `<div class="dropdown-divider"></div>
                           <button type="button" class="dropdown-item text-danger danger-on-hover"
                                   onclick='jsCancelTransaction(${transactionInfoJson})'>
                               <i class="ph-trash me-1"></i> ${translate.cancel}
                           </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='jsViewData(${itemJson})'>
                                <i class="ph-eye me-1"></i> ${translate.view}
                            </button>
                            ${btnEdit}
                            <button type="button" class="dropdown-item light-warning-on-hover"
                                    onclick='jsPrintData(${item.pur_id})'>
                                <i class="ph-printer me-1"></i> ${translate.print}
                            </button>
                            ${btnCancel}
                        </div>`;

                    return [
                        item.pur_id,
                        item.pos_name,
                        item.pur_date_formated,
                        item.provider_name ? formatName(item.provider_name) : '--',
                        item.createdBy ? formatName(item.createdBy) : '--',
                        fmt(totalCost),
                        fmt(item.total_precio_venta),
                        fmt(totalBenefit),
                        purchaseStatus,
                        btnOptions,
                    ];
                });

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

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

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

            tbPurchasesList.clear().draw();

        } else {

            tbPurchasesList.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) {
        tbPurchasesList.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();
        $('#finalCost').text(fmt(finalCost));
        $('#finalSale').text(fmt(finalSale));
        $('#finalBenefit').text(fmt(finalBenefit));
    }
}

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

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

    // Modal form
    let pur_span_transport = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, data.pur_shipping);
    let pur_span_total = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, data.pur_cost);
    let pur_span_sale_estimate = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, data.total_precio_venta);

    let total_benefits = Number(data.total_ganancia) - Number(data.pur_shipping);
    let pur_span_profit_estimate = showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, total_benefits);

    $("#pur_print_id").val(data.pur_id);
    $(".pos_description").text(data.pos_name);
    $(".pur_span_date").text(data.pur_date);
    $(".pur_span_provider").text(data.provider_name);
    $("#pur_span_transport").text(pur_span_transport);
    $("#pur_span_total").text(pur_span_total);
    $("#pur_span_sale_estimate").text(pur_span_sale_estimate);
    $("#pur_span_profit_estimate").text(pur_span_profit_estimate);

    $("#viewPurchaseModal").modal("show");

    fnViewPurchaseDetails(data, pos_info);
}

/*=============================================
SHOW PURCHASE DETAILS
=============================================*/
async function fnViewPurchaseDetails(data, pos_info) {
    try {

        const url = `ajax/purchases.ajax.php?op=ajaxShowPurchaseDetails&pur_id=${data.pur_id}`;
        const response = await fetch(url);

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

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

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

            if (res.data.length > 0) {
                const formattedData = res.data.map(item => {
                    return [
                        item.pro_description,
                        item.pur_det_pro_qty,
                        showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.pur_det_total),
                        showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.pur_det_pro_cost),
                        showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, item.pur_det_pro_price),
                    ];
                });
                tbViewPurchaseDetails.clear().rows.add(formattedData).draw();
            } else {
                tbViewPurchaseDetails.clear().draw();
            }
        }

        // Show total amount
        showAmount();

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

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

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

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

    document.getElementById("frmAddEditPurchaseData").reset();
    // Modal form
    $(".pos_description").text(data.pos_name);
    $("#pur_id").val(data.pur_id);
    $("#pur_ent_id").val(data.pur_ent_id);
    $("#pur_pos_id").val(data.pur_pos_id);
    $("#pur_cost").val(data.pur_cost);
    $("#pur_date").val(data.pur_date);
    $("#pur_provider_id").val(data.pur_provider_id);
    $("#pur_shipping").val(data.pur_shipping);
    fnSelectProvidersList(data.pur_ent_id, data.pur_provider_id)

    $("#addEditPurchaseModal").modal("show");

    fnShowPurchaseDetails(data.pur_id);
}

// List All Enterprises on click btnRefresh
$(document).on("click", ".btnPrintPurchase", function () {
    let pur_id = $("#pur_print_id").val();
    jsPrintData(pur_id)
});

/*=============================================
PRINT PURCHASE
=============================================*/
function jsPrintData(pur_id) {
    var url = `reports/purchase/index.php?pur_id=${pur_id}`;
    window.open(url);
}

/*=============================================
SHOW PURCHASE DETAILS
=============================================*/
async function fnShowPurchaseDetails(pur_id) {

    try {

        const url = `ajax/purchases.ajax.php?op=ajaxShowPurchaseDetails&pur_id=${pur_id}`;
        const response = await fetch(url);

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

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

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

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {
                    return [
                        `<button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removePurchaseRowSaved"><i class="mi-close"></i></button>
                        <input type="hidden" name="pur_det_pro_id[]" value="${item.pur_det_pro_id}"><input type="hidden" name="pur_det_cat_id[]" value="${item.pur_det_cat_id}"><input type="hidden" name="pur_det_pro_code[]" value="${item.pur_det_pro_code}">`,

                        `<input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" readonly value="${item.pro_description}">`,

                        `<input type="number" min="0" class="form-control form-control-lg purProQty" autocomplete="off" required name="pur_det_pro_qty[]" step="0.01" value="${item.pur_det_pro_qty}">`,

                        `<input type="number" min="0" class="form-control form-control-lg purTotalCost" autocomplete="off" required name="pur_det_total[]" value="${item.pur_det_total}" placeholder="0.00">`,

                        `<input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" required readonly name="pur_det_pro_cost[]" value="${item.pur_det_pro_cost}" placeholder="0.00">`,

                        `<input type="number" min="0" class="form-control form-control-lg purProPrice" autocomplete="off" required name="pur_det_pro_price[]" step="0.01" value="${item.pur_det_pro_price}" placeholder="0.00">`,
                    ];
                });

                tbAddEditPurchaseDetails.clear().rows.add(formattedData).draw();
            } else {
                tbAddEditPurchaseDetails.clear().draw();
            }
        }

        showAmount();

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

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

    if (Number($(this).val()) <= 0) {
        $(this).val(1);
        swalInit.fire(translate.the_quantity_cannot_be_less_than_one, translate.please_add_a_correct_quantity, "warning");
    }
    showAmount();
});

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

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

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

    if (Number($(this).val()) < 0 || Number($(this).val()) == -0) {
        $(this).val(1);
        swalInit.fire(translate.the_sale_price_cannot_be_empty_or_less_than_zero, translate.please_add_a_correct_amount, "warning");
    }
    showAmount();
});

// 
$(document).on("change", "#pur_shipping", function () {
    showAmount();
});


async function fnProductListPurchase() {

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

    let props = {
        ent_id: ent_id,
        pos_id: pos_id,
        pro_status: "Enabled",
        pro_type: "Product",
    }

    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 res = await response.json();
        // console.log(res)

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

            if (res.data.length > 0) {

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

                    let proStock = `<span class="badge bg-danger fw-medium text-white">${item.stock_actual}</span>`;
                    if (item.stock_actual > 10) proStock = `<span class="badge bg-warning fw-medium text-white">${item.stock_actual}</span>`;
                    if (item.stock_actual > 20) proStock = `<span class="badge bg-success fw-medium text-white">${item.stock_actual}</span>`;

                    return [
                        `<button type="button" class="btn btn-sm btn-icon rounded-pill btn-warning" onclick='jsAddNewPurchaseRow(${JSON.stringify(item)})'><i class="ph-plus"></i></button>`,
                        item.pro_description,
                        proStock,
                    ];
                });

                tbProductPurchaseList.clear().rows.add(formattedData).draw();
            } else {
                tbProductPurchaseList.clear().draw();
            }
        }

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

/*=============================================
FUNCTION TO ADD NEW PURCHASE ROW
=============================================*/
$(document).on("click", ".btnAddNewPurchase", function () {
    fnProductListPurchase();
    $("#listProductModal").modal("show");
});



/*====================================================
VALIDATE TO CHECK IF PRODUCT ALREADY EXIST IN ROW
======================================================*/
function checkIfProIdExist(param_pro_id = "") {

    var purchaseTableSize = $('.tbAddEditPurchaseDetails tbody tr').length;
    if (purchaseTableSize <= 0) return false;

    var purProId = document.getElementsByName("pur_det_pro_id[]");
    var purProQty = document.getElementsByName("pur_det_pro_qty[]");

    for (var i = 0; i < purProId.length; i++) {

        var purProIdVal = purProId[i];
        var purProQtyVal = purProQty[i];

        var newQty = Number(purProQtyVal.value) + 1;

        if (purProIdVal.value == param_pro_id) {
            fnSweetToast(translate.this_product_already_exists_its_quantity_will_be_increased, "warning", 3500);
            purProQtyVal.value = newQty;
            showAmount();
            return true;
        }
    }

}

/*=============================================
ADD NEW PURCHASE ROW 
=============================================*/
function jsAddNewPurchaseRow(data) {

    if (checkIfProIdExist(data.pro_id) == true) return false;

    $(".tbAddEditPurchaseDetails tbody").append(`<tr>
            <td><button type="button" class="btn btn-sm btn-icon rounded-pill btn-danger removePurchaseRow"><i class="mi-close"></i></button>
            <input type="hidden" name="pur_det_pro_id[]" value="${data.pro_id}"><input type="hidden" name="pur_det_cat_id[]" value="${data.pro_cat_id}"><input type="hidden" name="pur_det_pro_code[]" value="${data.pro_code}"></td>

            <td><input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" readonly value="${data.pro_description}"></td>

            <td><input type="number" min="0" class="form-control form-control-lg purProQty" autocomplete="off" required name="pur_det_pro_qty[]" step="0.01" value="1"></td>

            <td><input type="number" min="0" class="form-control form-control-lg purTotalCost" autocomplete="off" required name="pur_det_total[]" value="0" placeholder="0.00"></td>

            <td><input type="text" class="form-control form-control-lg input-group-text notAllowed" autocomplete="off" required readonly name="pur_det_pro_cost[]" value="0" placeholder="0.00"></td>

            <td><input type="number" min="0" class="form-control form-control-lg purProPrice" autocomplete="off" required name="pur_det_pro_price[]" step="0.01" value="${data.pro_price}" placeholder="0.00"></td>
            
        </tr>`);

    fnSweetToast(translate.product_added, "success", 2500);

    showAmount();
}


/*=============================================
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 ==========*/

    let pur_det_pro_qty = document.getElementsByName("pur_det_pro_qty[]");
    let pur_det_total = document.getElementsByName("pur_det_total[]");
    let pur_det_pro_cost = document.getElementsByName("pur_det_pro_cost[]");
    let pur_det_pro_price = document.getElementsByName("pur_det_pro_price[]");
    let pur_shipping = $('#pur_shipping').val();

    let total_cost_purchase = 0;
    let totalCostGeneral = 0;
    let total_price_sale = 0;
    let total_benefits = 0;

    let arrPurchaseCost = [];
    let arrSaleEstimate = [];
    let arrBenefitEstimate = [];

    for (var i = 0; i < pur_det_pro_qty.length; i++) {

        let pro_quantity = pur_det_pro_qty[i];
        let purchase_total = pur_det_total[i];
        let pro_cost = pur_det_pro_cost[i];
        let pro_price = pur_det_pro_price[i];

        let currentProCost = Number(purchase_total.value) / Number(pro_quantity.value);
        pro_cost.value = currentProCost.toFixed(2);

        arrPurchaseCost.push(Number(purchase_total.value));
        arrSaleEstimate.push(Number(pro_quantity.value) * Number(pro_price.value));
        arrBenefitEstimate.push(Number(pro_quantity.value * pro_price.value) - Number(purchase_total.value));
    }

    total_cost_purchase = arrPurchaseCost.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    totalCostGeneral = Number(total_cost_purchase) + Number(pur_shipping);
    total_price_sale = arrSaleEstimate.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    total_benefits = arrBenefitEstimate.reduce((previousValue, currentValue) => previousValue + currentValue, 0);
    total_benefits = Number(total_benefits) - Number(pur_shipping);

    $('#pur_cost').val(Number(total_cost_purchase).toFixed(2));
    $('#spanTotalPurchase').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, totalCostGeneral));
    $('#spanTotalSale').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, total_price_sale));
    $('#spanTotalProfit').text(showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, total_benefits));

}


/*=============================================
FUNCTION TO REMOVE ROW
=============================================*/
$(document).on("click", ".removePurchaseRow", function () {
    $(this).parent().parent().remove();
    fnSweetToast(translate.row_removed, "success", 2000);
    showAmount();
});


/*=============================================
FUNCTION TO REMOVE ROW
=============================================*/
$(document).on("click", ".removePurchaseRowSaved", 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();

        $("#addEditPurchaseModal").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
                $("#addEditPurchaseModal").modal("show");
                setTimeout(() => {
                    thisButton.parent().parent().remove();
                    fnSweetToast(translate.row_removed, "success", 2000);
                    showAmount();
                }, 500);
            } else if (result.dismiss === swalInit.DismissReason.cancel) {
                $("#addEditPurchaseModal").modal("show");
            }
        });

    }

});

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

    if (type === "edit") {

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

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

    var purchaseTableSize = $('.tbAddEditPurchaseDetails tbody tr').length;

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

    let pur_det_pro_id = document.getElementsByName("pur_det_pro_id[]");
    let pur_det_pro_qty = document.getElementsByName("pur_det_pro_qty[]");
    let pur_det_pro_price = document.getElementsByName("pur_det_pro_price[]");

    for (var i = 0; i < pur_det_pro_id.length; i++) {
        let purProQtyVal = pur_det_pro_qty[i];
        let purProPriceVal = pur_det_pro_price[i];

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

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

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


$(".btnEdit").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') {
        $('.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}`);
    }
}

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

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmAddEditPurchaseData")[0]);
    const apiUrl = 'ajax/purchases.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("frmAddEditPurchaseData").reset();
            fnSweetAlert(res.message, "", res.status, 1500);
            $("#addEditPurchaseModal").modal("hide");
            listDataToDatatable();

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

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