$(document).ready(function () {
    var searchEventTextBox = document.getElementById('searchEventTextBox');
    var payAmount = document.getElementById('payAmount');

    if (searchEventTextBox) {
        searchEventTextBox.focus();
    }

    $(searchEventTextBox).on("click", function (e) {
        searchEventTextBox.select();
    });

    loadSelect2(['#empList']);
    $('.select2-selection__rendered').addClass('fw-bold text-primary');

    $('#dataTableDueList').DataTable({
        columns: [
            { data: 'id' },
            {
                data: null,
                render: function (data, type, row) {
                    return `${row.event_name} (${row.package_name})`;
                }
            },
            { data: 'due_amount' }
        ],
        searching: false,
        lengthChange: false,
        info: false,
        bSort: false,
        paging: false
    });

    $('#dataTablePay').DataTable({
        columns: [
            { data: 'event_id' },
            {
                data: null,
                render: function (data, type, row) {
                    return sDate(row.payment_date);
                }
            },
            { data: 'pay_method' },
            { data: 'comment' },
            { data: 'payment_amt' },
            {
                data: null,
                render: function (data, type, row) {
                    return `
                    <div class="text-center">
                        <div class="btn-group">
                            <button class="btn btn-sm btn-danger" data-id="${row.id}" id="billEventPayDelete">
                                <i class="bi bi-trash-fill"></i>
                            </button>
                        </div>
                    </div>`;
                }
            }
        ],
        searching: false,
        lengthChange: false,
        info: false,
        bSort: false,
        paging: false
    });

    var tablePay = $('#dataTablePay').DataTable();

    setTimeout(function () {
        tablePay.column(5).visible(Permission(2));
        tablePay.columns.adjust().draw(false);
    }, 200);

    $("#searchEventBtn").on("click", function (e) {
        LoadBill();
    });

    $("#searchEventTextBox").on("keydown", function (e) {
        if (e.key === "Enter") {
            LoadBill();
        }
    });

    $("#eventIdSearch, #billNumSearch").on("change change", function (e) {
        if (searchEventTextBox) {
            searchEventTextBox.focus();
            searchEventTextBox.select();
        }
    });

    var paymentRadios = document.querySelectorAll('input[name="payMethod"]');

    paymentRadios.forEach(radio => {
        radio.addEventListener('change', function () {
            payAmount.focus();
            payAmount.select();
        });
    });

    $('#empList').on('change', function () {
        setTimeout(function () {
            $('#payAmount').focus().select();
        }, 10);
    });


    $(payAmount).on("click", function (e) {
        payAmount.select();
    });

    $("#paymentBtn").on("click", function (e) {
        billPayment();
    });

    $(payAmount).on("keydown", function (e) {
        if (e.key === "Enter") {
            billPayment();
        }
    });
});

$(document).on("click", "#billEventPayDelete", function (e) {
    e.preventDefault();
    var id = $(this).data("id");

    sAlertConfirm(() => {
        $.ajax({
            type: "post",
            url: "cust_bill_collection.php",
            data: {
                type: 'cd',
                id: id
            },
            dataType: "json",
            success: function (response) {
                if (response.flag) {
                    LoadBill();
                }
            }
        });
    }, 'delete');
});

function LoadBill() {
    var eventIdSearch = document.getElementById('eventIdSearch');
    var searchValue = sInt($("#searchEventTextBox").val());

    $('#hBillNum').val('');
    $('#hBillPayable').val('');
    $('#billNumber').html(InvoicePrefix.BILL_NUMBER);
    $('#billAmount').html('0');
    $('#billDiscount').html('0');
    $('#billDue').html('0');
    $('#billPayment').html('0');
    $('#billPayable').html('0');
    $('#billerName').val('...');

    if ($.fn.DataTable.isDataTable('#dataTable')) {
        $('#dataTable').DataTable().clear().draw();
    }

    if ($.fn.DataTable.isDataTable('#dataTablePay')) {
        $('#dataTablePay').DataTable().clear().draw();
    }

    var eventId = eventIdSearch.checked ? searchValue : 0;
    var billNum = eventIdSearch.checked ? 0 : searchValue;

    $.ajax({
        type: "post",
        url: "cust_bill_collection.php",
        data: {
            type: "find",
            eventId: eventId,
            billNum: billNum
        },
        dataType: "json",
        success: function (response) {
            if (response.billMst && response.billDtl) {
                var billMst = response.billMst;
                var billDtl = response.billDtl;

                var totalBill = sInt(billMst['ttl_bill_amt']);
                var totalPay = 0;

                $('#hBillNum').val(billMst['bill_num']);
                $('#billNumber').html(InvoicePrefix.BILL_NUMBER + billMst['bill_num']);
                $('#billAmount').html(sTakaFormat(billMst['bill_amt']));
                $('#billDiscount').html(sTakaFormat(billMst['discount']));
                $('#billDue').html(sTakaFormat(billMst['ttl_bill_amt']));
                $('#billerName').val(billMst['name']);

                var table = $('#dataTableDueList').DataTable();
                table.clear().rows.add(billDtl).draw();


                if (response.billPayDtl) {
                    var billPayDtl = response.billPayDtl;
                    var dataTablePay = $('#dataTablePay').DataTable();
                    var invoiceSet = new Set();

                    dataTablePay.clear().rows.add(billPayDtl).draw();
                    response.billPayDtl.forEach(row => {
                        if (sInt(row["invoice"]) > 0) {
                            totalPay += sInt(row["payment_amt"]);
                            invoiceSet.add(row["invoice"]);
                        }
                    });
                }

                var payableAmt = totalBill - totalPay;

                $('#billPayment').html(sTakaFormat(totalPay));
                $('#billPayable').html(sTakaFormat(payableAmt));
                $('#hBillPayable').val(payableAmt);
                $('#payAmount').val(payableAmt);

                var payAmount = document.getElementById("payAmount");
                payAmount.focus();
                payAmount.select();

                var container = document.querySelector(".print-invoice-button");
                container.innerHTML = "";

                var sortedInvoices = Array.from(invoiceSet).sort((a, b) => a - b);

                sortedInvoices.forEach(invoice => {
                    var button = document.createElement("button");
                    button.type = "button";
                    button.className = "btn btn-sm btn-outline-info me-1 my-1";
                    button.setAttribute("data-invoice", invoice);
                    button.innerHTML = `<i class="bi bi-printer-fill"></i> ${InvoicePrefix.EVENT_PAY}${invoice}`;

                    button.addEventListener("click", () => {
                        printInvoice(invoice);
                    });

                    container.appendChild(button);
                });

            } else {
                sAlert("Bill not found!", "", "error");
            }
        }
    });
}

function PaymentMethod() {
    const selected = document.querySelector('input[name="payMethod"]:checked');
    if (selected) {
        const label = document.querySelector(`label[for="${selected.id}"]`);
        return label.textContent;
    }
    return null;
}

function billPayment() {
    var billNum = sInt($("#hBillNum").val()) ?? 0;
    var billerName = $("#billerName").val() ?? "";
    var receivedBy = $('#empList').find(':selected').data('emp-name');
    var paymentAmount = sInt($("#payAmount").val()) ?? 0;

    var paymentMethod = PaymentMethod();

    if (billNum > 0) {
        if (receivedBy) {
            $.ajax({
                type: "post",
                url: "cust_bill_collection.php",
                data: {
                    type: "pay",
                    billNum: billNum,
                    billerName: billerName,
                    paymentAmount: paymentAmount,
                    paymentMethod: paymentMethod,
                    receivedBy: receivedBy
                },
                dataType: "json",
                success: function (response) {
                    if (response.flag > 0) {
                        sAlert("Bill payment successful", "", "success");
                        LoadBill();
                        printInvoice(response.flag);
                    } else if (response.flag == 0) {
                        sAlert("0 payment not possible", "", "info");
                    } else {
                        sAlert("Payment Failed", "", "error");
                    }
                }
            });
        }else{
            sAlert("Received By not found", "Please select Received By and try again", "info");
        }
    } else {
        sAlert("Bill Number not found", "", "error")
    }
}

function printInvoice(invoice) {

    if (!invoice) {
        alert("Bill payment not found.");
        return;
    }

    var url = `../print/cust_bill_money_receipt.php?invoice=${encodeURIComponent(invoice)}`;

    var windowFeatures = "width=900,height=700,top=100,left=200,scrollbars=yes";

    var printWindow = window.open(url, "printWindow", windowFeatures);

    var interval = setInterval(() => {
        if (printWindow.document.readyState === "complete") {
            clearInterval(interval);
            printWindow.focus();
            printWindow.print();

            // Optional: auto-close after print
            //setTimeout(() => printWindow.close(), 1000);
        }
    }, 500);
}
