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

    var eventIdSearch = document.getElementById('eventIdSearch');
    var billNumSearch = document.getElementById('billNumSearch');

    var billDiscount = document.getElementById('billDiscount');
    var billerName = document.getElementById('billerName');

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

    $('#dataTable').DataTable({
        columns: [
            { data: 'event_id' },
            {
                data: null,
                render: function (data, type, row) {
                    return sDate(row.event_date_time);
                }
            },
            {
                data: null,
                render: function (data, type, row) {
                    const addOnsStr = row.addons;
                    if (addOnsStr && addOnsStr.trim() !== "") {
                        const dtl = ParseAddOns(addOnsStr);
                        return dtl.map(item => item.name + " " + item.amount + " tk").join("<br>");
                    }
                    return addOnsStr || '';
                }
            },
            {
                data: null,
                render: function (data, type, row) {
                    var addTime = row.add_time;
                    if (addTime != "" && addTime != null) {
                        var dtl = AdditionalTime(addTime);
                        return dtl.hours + " " + dtl.amount + " tk";
                    }
                    return addTime;
                }
            },
            { data: 'outdoor_amt' },
            { data: 'amount' },
            { data: 'total_amt' },
            {
                data: null,
                render: function (data, type, row) {
                    return `
                    <div class="text-center">
                        <div class="btn-group">
                            <button class="btn btn-sm btn-light" data-id="${row.id}" id="billEventEdit">
                                <i class="bi bi-pencil-square"></i>
                            </button>
                            <span class="delete-btn-placeholder" data-id="${row.id}"></span>
                        </div>
                    </div>`;
                }
            }
        ],
        drawCallback: function (settings) {
            const api = this.api();
            const rowCount = api.rows({ page: 'current' }).count();

            if (rowCount > 1) {
                $('.delete-btn-placeholder').each(function () {
                    const id = $(this).data('id');
                    const deleteBtn = `
                    <button class="btn btn-sm btn-danger" data-id="${id}" id="billEventDelete">
                        <i class="bi bi-trash-fill"></i>
                    </button>`;
                    $(this).replaceWith(deleteBtn);
                });
            } else {
                $('.delete-btn-placeholder').remove();
            }
        },
        searching: false,
        lengthChange: false,
        bSort: false
    });

    $("#searchEventBtn").on("click", function (e) {
        var searchValue = sInt($("#searchEventTextBox").val());
        if (eventIdSearch.checked) {
            searchEvent(false, searchValue, 0);
        } else {
            searchEvent(false, 0, searchValue);
        }
    });

    $("#searchEventTextBox").on("keydown", function (e) {
        if (e.key === "Enter") {
            var searchValue = sInt($("#searchEventTextBox").val());
            if (eventIdSearch.checked) {
                searchEvent(false, searchValue, 0);
            } else {
                searchEvent(false, 0, searchValue);
            }
        }
    });

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

    if (billDiscount) {
        billDiscount.addEventListener("keydown", (e) => {
            if (e.key === "Enter") {
                e.preventDefault();
                if (billerName) {
                    billerName.focus();
                    billerName.select();
                }
            }
        });
    }

    if (billerName) {
        billerName.addEventListener("keydown", (e) => {
            if (e.key === "Enter") {
                e.preventDefault();
                updateBillMst();
            }
        });
    }

    document.addEventListener('keydown', function (e) {
        if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'p') {
            e.preventDefault();
            printBill();
        }
    });


});

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

    $.ajax({
        type: "post",
        url: "modal_cust_bill.php",
        data: {
            type: "edit",
            id: id
        },
        success: function (response) {
            sModalShow(response);
        }
    });
});

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

    sAlertConfirm(() => {
        $.ajax({
            type: "post",
            url: "modal_cust_bill.php",
            data: {
                type: "delete",
                billDtlId: id,
                delete: true
            },
            success: function (response) {
                if (response.flag === "pay") {
                    sAlert("This Bill Has Payment. Cann't Delete!", "", "info");
                } else if (response.flag) {
                    LoadBill(0, response.flag);
                }
            }
        });
    });

});

$(document).on("input", "#billDiscount", function (e) {
    let billAmount = sInt($('#billAmount').text().trim());
    let billDiscount = sInt($('#billDiscount').val().trim());
    let $billPayable = $("#billPayable");

    // Validate that discount is not more than the amount
    if (billDiscount > billAmount) {
        $('#billDiscount').val(0);

        $billPayable.val(billAmount);
        return;
    }

    // Calculate payable
    let payable = billAmount - billDiscount;
    $billPayable.text(payable);

});

function searchEvent(addAnother = false, eventId = 0, billNum = 0) {
    if (!addAnother) {
        LoadBill(0);
    }

    //var eventId = (addAnother) ? eventId : sInt($("#searchEventTextBox").val());

    if (eventId < 0 || billNum < 0) {
        sAlert("Please provide a valid EVENT or BILL NUMBER", "", "error");
    } else {
        $.ajax({
            type: "post",
            url: "cust_bill.php",
            data: {
                type: "find",
                eventId: eventId,
                billNum: billNum,
            },
            success: function (response) {
                if (response.bill === false) {
                    $.ajax({
                        type: "post",
                        url: "modal_cust_bill.php",
                        data: {
                            type: "find",
                            eventId: eventId,
                            addAnother: addAnother,
                            billNum: billNum
                        },
                        success: function (response) {
                            if (response.event === false) {
                                sAlert("Event not found.", "", "error");
                            } else {
                                sModalShow(response);
                            }
                        }
                    });
                } else {
                    if (addAnother) {
                        var billNumFind = response.billMst['bill_num'];
                        var title = `Bill Number = ${InvoicePrefix.BILL_NUMBER + billNumFind}`;
                        var text = 'This event is already added in this bill';
                        sAlert(title, text, "info");

                    } else {
                        LoadBill(eventId, billNum);
                    }
                }
            }
        });

    }
}

function LoadBill(eventId = 0, billNum = 0) {
    $('#hBillNum').val('');
    $('#billNumber').html(InvoicePrefix.BILL_NUMBER);
    $('#billAmount').html('0');
    $('#billDiscount').val('0');
    $('#billPayable').html('0');
    $('#billerName').val('...');
    $('#actionButton').html('');

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

    $.ajax({
        type: "post",
        url: "cust_bill.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;

                $('#hBillNum').val(billMst['bill_num']);
                $('#billNumber').html(InvoicePrefix.BILL_NUMBER + billMst['bill_num']);
                $('#billAmount').html(billMst['bill_amt']);
                $('#billDiscount').val(billMst['discount']);
                $('#billPayable').html(billMst['ttl_bill_amt']);
                $('#billerName').val(billMst['name']);
                $('#actionButton').html(`<td class="text-center" colspan="6">
                                            <button type="button" class="btn btn-sm btn-primary px-3 fw-bold" onclick="updateBillMst()">Update Bill</button>
                                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteBill()"><i class="bi bi-trash-fill"></i></button>
                                            <button type="button" class="btn btn-sm btn-success px-3 fw-bold" onclick="addEvent()"><i class="bi bi-plus-lg me-2"></i>Add Event</button>
                                            <button type="button" class="btn btn-sm btn-info" onclick="sPrint('bill', ${billMst['bill_num']})"><i class="bi bi-printer-fill"></i></button>
                                        </td>`);

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


}

function generateBill(billNumber = 0) {
    var eventId = $("#eventId").val();
    var addHour = $("#addHour").val();
    var addHourAmt = $("#addHourAmt").val();
    var outdoorDtl = $("#outdoorDtl").val();
    var outdoorVenue = $("#outdoorVenue").val();
    var outdoorPhoto = $("#outdoorPhoto").val();
    var outdoorCinemeto = $("#outdoorCinemeto").val();
    var outdoorAmt = $("#outdoorAmt").val();

    if (billNumber == 0 || billNumber == '' || billNumber == null) {
        $.ajax({
            type: "post",
            url: "modal_cust_bill.php",
            data: {
                type: "gbill",
                eventId: eventId,
                addHour: addHour,
                addHourAmt: addHourAmt,
                outdoorDtl: outdoorDtl,
                outdoorVenue: outdoorVenue,
                outdoorPhoto: outdoorPhoto,
                outdoorCinemeto: outdoorCinemeto,
                outdoorAmt: outdoorAmt
            },
            success: function (response) {
                sModalHide();
                LoadBill(eventId);
            }
        });
    } else if (billNumber > 0) {
        $.ajax({
            type: "post",
            url: "modal_cust_bill.php",
            data: {
                type: "aaB",
                billNumber: billNumber,
                eventId: eventId,
                addHour: addHour,
                addHourAmt: addHourAmt,
                outdoorDtl: outdoorDtl,
                outdoorVenue: outdoorVenue,
                outdoorPhoto: outdoorPhoto,
                outdoorCinemeto: outdoorCinemeto,
                outdoorAmt: outdoorAmt
            },
            success: function (response) {
                sModalHide();
                LoadBill(eventId);
            }
        });
    }
}

function updateBillDtl(billDtlId) {
    var eventId = $("#eventId").val();
    var billNumber = $("#hBillNum").val();
    var addHour = $("#addHour").val();
    var addHourAmt = $("#addHourAmt").val();
    var outdoorDtl = $("#outdoorDtl").val();
    var outdoorVenue = $("#outdoorVenue").val();
    var outdoorPhoto = $("#outdoorPhoto").val();
    var outdoorCinemeto = $("#outdoorCinemeto").val();
    var outdoorAmt = $("#outdoorAmt").val();

    $.ajax({
        type: "post",
        url: "modal_cust_bill.php",
        data: {
            type: "billDtlE",
            eventId: eventId,
            billNumber: billNumber,
            billDtlId: billDtlId,
            addHour: addHour,
            addHourAmt: addHourAmt,
            outdoorDtl: outdoorDtl,
            outdoorVenue: outdoorVenue,
            outdoorPhoto: outdoorPhoto,
            outdoorCinemeto: outdoorCinemeto,
            outdoorAmt: outdoorAmt
        },
        success: function (response) {
            if (response.flag) {
                sModalHide();
                LoadBill(eventId);
                sAlert("Successfully Updated Bill");
            }else{
                sAlert("Failed", "", "error");
            }
        }
    });
}

function addEvent() {
    var billNumber = $('#hBillNum').val();

    $.ajax({
        type: "post",
        url: "modal_add_event_bill.php",
        data: {
            billNumber: billNumber,
        },
        success: function (response) {
            sModalShow(response);
        }
    });

}

function addAnotherEvent() {
    var eventId = sInt($("#mSearchEventTextBox").val());
    var billNum = sInt($("#mBillNumber").val());
    sModalHide();
    searchEvent(true, eventId, billNum);
}

function updateBillMst() {
    var billNumber = $('#hBillNum').val();
    var billDiscount = sInt($('#billDiscount').val().trim());
    var billerName = $('#billerName').val().trim();

    if (billDiscount >= 0) {
        $.ajax({
            type: "post",
            url: "cust_bill.php",
            data: {
                type: "mstUp",
                billNumber: billNumber,
                billDiscount: billDiscount,
                billerName: billerName
            },
            dataType: "json",
            success: function (response) {
                if (response.flag) {
                    LoadBill(0, billNumber);
                    sAlert("Successfully Updated Bill");
                } else {
                    sAlert("Please enter valid discount amount.", "", "error");
                }
            }
        });
    } else {
        sAlert("Please enter valid discount amount.", "", "error");
    }
}

function deleteBill() {
    var billNumber = $('#hBillNum').val();

    sAlertConfirm(() => {
        $.ajax({
            type: "post",
            url: "cust_bill.php",
            data: {
                type: 'db',
                billNumber: billNumber,
            },
            dataType: "json",
            success: function (response) {
                if (response.flag == "pay") {
                    sAlert("This Bill Has Payment. Cann't Delete!", "", "info");
                } else if (response.flag) {
                    sAlertDelete(true);
                }
            }
        });
    });


}
