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

function fnListAllSales() {
    listPendingSaleToTable();
    listCompletedSaleToTable();
    listCancelledSaleToTable();
};

// Column selectors
const tbPendingSalesList = $('.pending-sales-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 tbCompletedSalesList = $('.completed-sales-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 tbCanceledSalesList = $('.canceled-sales-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", ".btnAddSale", function () {
    window.location = "sell";
});

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

async function jsCashierList() {

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

    let props = {
        ent_id: ent_id,
        profile: "!Waiter",
    }

    try {

        const url = `ajax/users.ajax.php?op=ajaxGetUsersList&ent_id=${props.ent_id}&profile=${props.profile}`;
        const response = await fetch(url);

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

        const res = await response.json();

        $("#emp_id_value").html("");
        $("#emp_id_value").append(`<option value="">-- ${translate.all_m} --</option>`);

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

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

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

        const url = `ajax/sales.ajax.php?op=ajaxSalesList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&fromDate=${props.fromDate}&toDate=${props.toDate}&status=${props.status}&empId=${props.empId}`;
        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 listPendingSaleToTable(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(),
        empId: ($("#emp_id_value").val() || '').trim(),
        status: 'Pending',
        fromDate,
        toDate,
    };

    // ── Validate all required props ───────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([key, value]) => key !== 'empId' && (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 finalTotal = 0;
    let finalDebt = 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 ticketInfo = {
                        transaction_id: item.sale_id,
                        sale_id: item.sale_id,
                        sale_cus_id: item.sale_cus_id,
                        sale_ent_id: item.sale_ent_id,
                        sale_pos_id: item.sale_pos_id,
                        section: 'sales',
                    };

                    const ticketJson = JSON.stringify(ticketInfo);
                    const saleDebt = item.sale_debts < 0 ? 0 : Number(item.sale_debts);

                    finalTotal += Number(item.final_total);
                    finalDebt += saleDebt;

                    // ── Sale status badge ─────────────────────────────────────
                    let saleStatus = `<span class="badge bg-warning fw-medium text-white">${translate.pending}</span>`;
                    if (item.sale_status === 'Enabled' && item.sale_debts <= 0) {
                        saleStatus = `<span class="badge bg-success fw-medium text-white">${translate.completed_f}</span>`;
                    }
                    if (item.sale_status === 'Disabled') {
                        saleStatus = `<span class="badge bg-danger fw-medium text-white">${translate.canceled_f}</span>`;
                    }

                    // ── Cancel button (hidden for Waiters and cancelled sales) ─
                    const canCancel = sess_user_profile !== 'Waiter' && item.sale_status !== 'Disabled';
                    const btnCancel = canCancel
                        ? `<div class="dropdown-divider"></div>
                           <button type="button" class="dropdown-item text-danger danger-on-hover"
                                   onclick='jsCancelTransaction(${ticketJson})'>
                               <i class="ph-trash me-1"></i> ${translate.cancel}
                           </button>`
                        : '';

                    // ── Action dropdown ───────────────────────────────────────
                    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='jsShowTicket(${ticketJson})'>
                                <i class="ph-eye me-1"></i> Ticket
                            </button>
                            <a href="sell-det-${item.sale_id}" role="button"
                               class="dropdown-item light-warning-on-hover">
                                <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                            </a>
                            ${btnCancel}
                        </div>`;

                    const waiterName = item.waiter_full_name ? formatName(item.waiter_full_name) : '--';
                    const cashierName = item.cashier_full_name ? formatName(item.cashier_full_name) : '--';

                    return [
                        item.sale_id,
                        item.pos_name,
                        item.sale_date,
                        `<div class="row"><span>${waiterName}</span><span>${cashierName}</span></div>`,
                        item.client_full_name,
                        item.sale_type,
                        fmt(item.final_total),
                        fmt(saleDebt),
                        saleStatus,
                        btnOptions,
                    ];
                });

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

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

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

            tbPendingSalesList.clear().draw();

        } else {

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

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

    } finally {
        // Always restore button and update footer totals
        resetSearchButton();
        $('#finalPendingTotal').text(fmt(finalTotal));
        $('#finalPendingDebt').text(fmt(finalDebt));
    }
}

// List All data function
async function listCompletedSaleToTable(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(),
        empId: ($("#emp_id_value").val() || '').trim(),
        status: 'Completed',
        fromDate,
        toDate,
    };

    // ── Validate required props (empId is optional) ───────────────────────────
    const missingProps = Object.entries(props)
        .filter(([key, value]) => key !== 'empId' && (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 finalTotal = 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 => {

                    // Single info object used by both jsShowTicket and jsCancelTransaction
                    const saleInfo = {
                        transaction_id: item.sale_id,
                        sale_id: item.sale_id,
                        sale_cus_id: item.sale_cus_id,
                        sale_ent_id: item.sale_ent_id,
                        sale_pos_id: item.sale_pos_id,
                        section: 'sales',
                    };
                    const saleInfoJson = JSON.stringify(saleInfo);

                    finalTotal += Number(item.final_total);

                    // ── Sale status badge ─────────────────────────────────────
                    let saleStatus = `<span class="badge bg-warning fw-medium text-white">${translate.pending}</span>`;
                    if (item.sale_status === 'Enabled' && item.sale_debts <= 0) {
                        saleStatus = `<span class="badge bg-success fw-medium text-white">${translate.completed_f}</span>`;
                    }
                    if (item.sale_status === 'Disabled') {
                        saleStatus = `<span class="badge bg-danger fw-medium text-white">${translate.canceled_f}</span>`;
                    }

                    // ── Cancel button (hidden for Waiters and cancelled sales) ─
                    const canCancel = sess_user_profile !== 'Waiter' && item.sale_status !== 'Disabled';
                    const btnCancel = canCancel
                        ? `<div class="dropdown-divider"></div>
                           <button type="button" class="dropdown-item text-danger danger-on-hover"
                                   onclick='jsCancelTransaction(${saleInfoJson})'>
                               <i class="ph-trash me-1"></i> ${translate.cancel}
                           </button>`
                        : '';

                    // ── Action dropdown ───────────────────────────────────────
                    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='jsShowTicket(${saleInfoJson})'>
                                <i class="ph-eye me-1"></i> Ticket
                            </button>
                            <a href="sell-det-${item.sale_id}" role="button"
                               class="dropdown-item light-warning-on-hover">
                                <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                            </a>
                            ${btnCancel}
                        </div>`;

                    const waiterName = item.waiter_full_name ? formatName(item.waiter_full_name) : '--';
                    const cashierName = item.cashier_full_name ? formatName(item.cashier_full_name) : '--';

                    return [
                        item.sale_id,
                        item.pos_name,
                        item.sale_date,
                        `<div class="row"><span>${waiterName}</span><span>${cashierName}</span></div>`,
                        item.client_full_name,
                        item.sale_type,
                        fmt(item.final_total),
                        saleStatus,
                        btnOptions,
                    ];
                });

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

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

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

            tbCompletedSalesList.clear().draw();

        } else {

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

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

    } finally {
        resetSearchButton();
        $('#finalCompletedTotal').text(fmt(finalTotal));
    }
}

// List All data function
async function listCancelledSaleToTable(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(),
        empId: ($("#emp_id_value").val() || '').trim(),
        status: 'Disabled',
        fromDate,
        toDate,
    };

    // ── Validate required props (empId is optional) ───────────────────────────
    const missingProps = Object.entries(props)
        .filter(([key, value]) => key !== 'empId' && (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 finalTotal = 0;
    let finalDebt = 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 => {

                    // All rows in this table are cancelled — single info object
                    // used by jsShowTicket (no cancel button needed)
                    const saleInfo = {
                        sale_id: item.sale_id,
                        sale_cus_id: item.sale_cus_id,
                        sale_ent_id: item.sale_ent_id,
                        sale_pos_id: item.sale_pos_id,
                    };
                    const saleInfoJson = JSON.stringify(saleInfo);

                    const saleDebt = item.sale_debts < 0 ? 0 : Number(item.sale_debts);

                    finalTotal += Number(item.final_total);
                    finalDebt += saleDebt;

                    // All rows are cancelled — badge is always "cancelled"
                    const saleStatus = `<span class="badge bg-danger fw-medium text-white">${translate.canceled_f}</span>`;

                    const waiterName = item.waiter_full_name ? formatName(item.waiter_full_name) : '--';
                    const cashierName = item.cashier_full_name ? formatName(item.cashier_full_name) : '--';

                    return [
                        item.sale_id,
                        item.pos_name,
                        item.sale_date,
                        `<div class="row"><span>${waiterName}</span><span>${cashierName}</span></div>`,
                        item.client_full_name,
                        item.sale_type,
                        fmt(item.final_total),
                        fmt(saleDebt),
                        saleStatus,
                        `<button type="button" class="btn btn-sm btn-indigo"
                                 onclick='jsShowTicket(${saleInfoJson})'>
                             <i class="ph-eye me-1"></i> Ticket
                         </button>`,
                    ];
                });

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

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

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

            tbCanceledSalesList.clear().draw();

        } else {

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

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

    } finally {
        resetSearchButton();
        $('#finalCanceledTotal').text(fmt(finalTotal));
        $('#finalCanceledDebt').text(fmt(finalDebt));
    }
}


$(document).on("click", ".btnCashBox", async function () {

    let emp_id = $.trim($("#emp_id_value").val());

    showSalesReportByEmployee();

    if (sess_user_profile == 'ROOT' || sess_user_profile == 'Owner' || sess_user_profile == 'Manager') {
        showSalesReportByEmployee();
    } else {

        if (emp_id === "") {
            swalInit.fire(translate.select_an_employee, "", "warning");
            return false;
        }

        // SHOW REPORT BY EMPLOYEE
        showSalesReportByEmployee();

        // let entInfo = await jsGetEnterpriseData();
        // console.log(entInfo);

        // swalInit.fire({
        //     title: translate.statistics_code,
        //     input: 'password',
        //     showCancelButton: true,
        //     inputPlaceholder: "**********",
        //     inputAttributes: {
        //         'autocapitalize': 'off',
        //         'autocorrect': 'off'
        //     },
        //     preConfirm: (value) => {
        //         if (!value) {
        //             swalInit.showValidationMessage(translate.you_must_enter_the_password);
        //             return false;
        //         } else if (value !== entInfo.ent_statistic_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

        //         // GENERATE A NEW DISCOUNT PASSWORD
        //         $.post("ajax/enterprises.ajax.php?op=ajaxGenerateNewDiscountPassword", { entId: entInfo.ent_id, csrf_token: csrf_token }, function (response) { });

        //         // SHOW REPORT BY EMPLOYEE
        //         showSalesReportByEmployee();

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


function showSalesReportByEmployee() {

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

    let daterange = $.trim($(".dateSelected").val()).split(" / ");
    let fromDate = daterange[0];
    let toDate = daterange[1];

    let props = {
        ent_id: ent_id,
        pos_id: pos_id,
        emp_id: emp_id,
        from_date: fromDate,
        to_date: toDate,
        csrf_token: csrf_token
    }

    $.ajax({
        data: props,
        url: 'reports/cash-box-report.php',
        type: 'post',
        success: function (datos) {
            // $(".loader").hide();
            $("#printDivCashSummaryHidden").html("");
            $("#printDivCashSummaryHidden").html(datos);
            $("#printDivCashSummary").html("");
            $("#printDivCashSummary").html(datos);
            $("#showCashSummaryModal").modal("show");
        }
    });
}

function printTicketCashSummary() {
    var myPrintContent = document.getElementById('printDivCashSummaryHidden');
    var myPrintWindow = window.open("about:blank", 'Sale Report', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=600,left = 390,top = 50');
    myPrintWindow.document.write(myPrintContent.innerHTML);
    myPrintWindow.document.close();
    myPrintWindow.focus();
    myPrintWindow.print();
    myPrintWindow.close();
    return false;
}