$(document).ready(function () {
    sDateTime('#details_date');

    loadSelect2(['#details_package_dtl'], null, true);

    $('#details_package_dtl').select2({
        templateSelection: function (data) {
            if (!data.id) {
                return data.text;
            }
            var option = $(data.element);
            return option.data('title') || data.text;
        }
    });

    var detailsTable = $('#detailsTable').DataTable({
        ajax: {
            url: 'cust_quotation.php',
            type: 'POST',
            data: function (d) {
                d.type = 'detailsList';
                d.quoteId = quoteId;
            },
            dataSrc: function (json) {
                return json;
            },
        },
        columns: [{
            data: null,
            render: function (data) {
                return sDate(data['event_date']);
            }
        },
        { data: 'location' },
        {
            data: null,
            render: function (data, type, row) {
                return row.package_name + ((row.add_ons_id > 0) ? ' + Add-Ons' : '');
            }
        },
        { data: 'event_time' },
        { 
            data: null,
            render: function (data, type, row) { 
                return (sInt(row.package_amt) + sInt(row.add_ons_amt) + sInt(row.out_amt));
            }
        },
        { data: 'adjust_amt' },
        { data: 'total' },
        {
            data: null,
            render: function (data, type, row) {
                var btn = '<div class="btn-group">';
                btn += '<button type="button" id="detailEdit" class="btn btn-sm action-btn" data-detail-id = "' + row.id + '"><i class="bi bi-pencil-square"></i></button>';
                btn += '<button type="button" id="detailDelete" class="btn btn-sm action-btn" data-detail-id = "' + row.id + '"><i class="bi bi-trash-fill"></i></button>';
                btn += '</div>';
                return btn;
            }
        }
        ],
        ordering: false,
        paging: false,
        info: false,
        searching: false,
        lengthChange: false
    });

    var tableBreakdown = $('#tableBreakdown').DataTable({
        ajax: {
            url: 'cust_quotation.php',
            type: 'POST',
            data: function (d) {
                d.type = 'detailsList';
                d.quoteId = quoteId;
            },
            dataSrc: function (json) {
                return json;
            },
        },
        columns: [{
            data: null,
            render: function (data, type, row) {
                return row.package_name + ((row.add_ons_id > 0) ? ' + Add-Ons' : '');
            }
        },
        { data: 'event_type' },
        { data: 'duration' },
        { data: 'total' },
        {
            data: null,
            render: function (data, type, row) {
                var btn = '<div class="btn-group">';
                btn += '<button type="button" id="breakdownEdit" class="btn btn-sm action-btn" data-detail-id = "' + row.id + '"><i class="bi bi-pencil-square"></i></button>';
                btn += '</div>';
                return btn;
            }
        }
        ],
        ordering: false,
        paging: false,
        info: false,
        searching: false,
        lengthChange: false
    });

    LoadQuotation(quoteId);

    function DisableForm() {
        var quoteMstActionBtn = document.getElementById("quoteMstActionBtn");
        quoteMstActionBtn.innerHTML = `
            <button type="button" id="initial_quote" class="btn btn-sm btn-outline-warning fw-bold">
                Initial Quotation
            </button>`;
        document.querySelectorAll("input, select, button").forEach(function (el) {
            var skipIDs = ["client_name", "purpose", "initial_quote", "update_quote"];
            if (!skipIDs.includes(el.id)) {
                el.setAttribute("disabled", true);
                el.classList.add("cursor-not-allowed");
            }
        });
        $(".section-details, .section-others, .section-breakdown").addClass("opacity-75 cursor-not-allowed");
    }

    function EnableForm(quote_id) {
        var quoteMstActionBtn = document.getElementById("quoteMstActionBtn");
        quoteMstActionBtn.innerHTML = `
            <button type="button" id="update_quote" class="btn btn-sm btn-outline-warning fw-bold">
                Update Quotation
            </button>
            <a href="../print/cust_quotation.php?quote_id=${quote_id}" class="btn btn-sm action-btn" target="_blank"><i class="bi bi-printer-fill"></i></a>`;

        document.querySelectorAll("input, select, button").forEach(function (el) {
            var skipIDs = ["client_name", "purpose", "initial_quote", "update_quote"];
            if (!skipIDs.includes(el.id)) {
                el.removeAttribute("disabled");
                el.classList.remove("cursor-not-allowed");
            }
        });
        $(".section-details, .section-others, .section-breakdown").removeClass("opacity-75 cursor-not-allowed");
    }

    function LoadQuotation(quoteId) {
        var quote_id = sInt(quoteId);
        var hQuoteId = document.getElementById("hQuoteId");
        var client_name = document.getElementById("client_name");
        var purpose = document.getElementById("purpose");
        var discount_total = document.getElementById("discount_total");
        var discount_discount = document.getElementById("discount_discount");
        var discount_after = document.getElementById("discount_after");

        if (quote_id > 0) {
            $.ajax({
                type: "post",
                url: "cust_quotation.php",
                data: {
                    type: 'get',
                    id: quote_id
                },
                dataType: "json",
                success: function (response) {
                    var quoteMst = response.quoteMst;
                    var quoteOthers = response.quoteOthers;

                    if (quoteMst) {
                        EnableForm(quote_id);
                        hQuoteId.value = quoteMst.id;
                        client_name.value = quoteMst.client_name;
                        purpose.value = quoteMst.purpose;
                        $("#details_btn").html(`
                            <button type="button" class="btn btn-sm bg-success border-white text-white px-3" id="details_add">
                                <i class="bi bi-plus-lg me-2"></i>Add Details
                            </button>
                        `);

                        discount_total.value = quoteMst.amount;
                        discount_discount.value = quoteMst.discount;
                        discount_after.value = quoteMst.total_amt;

                        if (quoteOthers) {
                            $('#others_edit_photo').val(quoteOthers.edited_photo);
                            $('#others_reels').val(quoteOthers.reels);
                            $('#others_photo_quality').val(quoteOthers.photo_quality);
                            $('#others_promo').val(quoteOthers.promo);
                            $('#others_video').val(quoteOthers.video);
                            $('#others_album').val(quoteOthers.album);
                            $('#others_photo_frame10l').val(quoteOthers.pf_10l);
                            $('#others_update').removeClass("bg-success").addClass("bg-primary").html("Update Others");
                        }
                    } else {
                        DisableForm();
                        sAlert("Quotation Not Found", "Please initiat quotation first", "info");
                    }
                }
            });
        } else {
            DisableForm();
        }
    }

    function CleanDetails() {
        $("#details_for_outdoor").prop("checked", false);
        $("#details_date").val("");
        $("#details_location").val("-");
        $('#details_package_dtl').val(null).trigger('change');
        $("#details_outdoor_amt").val("");
        $("#details_package").val("0");
        $("#details_additional_amt").val("0");
        $("#details_add_ons").val("0");
        $("#details_event_time").val("-");
        $("#details_report_time").val("-");
        $("#details_photog").val("1");
        $("#details_cinemetog").val("1");
        $("#details_drone").val("1");
        LoadOutdoor();
    }

    function LoadOutdoor(enableCheckBox = false) {
        if (enableCheckBox) {
            $("#details_for_outdoor").prop("checked", true).trigger("change");
            return;
        }
        var outdoorCheckBox = $("#details_for_outdoor").is(':checked');
        var packageList = $("#dp");
        var packageDtl = $("#dpd");
        var packageDtlAmt = $("#dpda");

        if (outdoorCheckBox || enableCheckBox) {
            packageList.addClass("d-none");
            packageDtl.removeClass("d-none");
            packageDtlAmt.removeClass("d-none");
            $("#details_package").val("0");
        } else {
            packageList.removeClass("d-none");
            packageDtl.addClass("d-none");
            packageDtlAmt.addClass("d-none");
            $('#details_package_dtl').val(null).trigger('change');
            $("#details_outdoor_amt").val("0");
        }
    }

    CleanDetails();
    LoadOutdoor();

    var details_fields = Array.from(document.querySelectorAll(".section-details input, .section-details select")).filter(field => field.id != "details_for_outdoor");
    if (details_fields) {
        details_fields.forEach((field, index) => {
            field.addEventListener("keydown", function (e) {
                if (e.key === "Enter") {
                    e.preventDefault();

                    if (index < details_fields.length - 1) {
                        var nextField = details_fields[index + 1];
                        nextField.focus();

                        if (nextField.tagName === "INPUT") {
                            nextField.select();
                        }
                    }
                }
            });
        });
    }

    $(document).on('change', '#details_for_outdoor', function () {
        LoadOutdoor();
    });

    $(document).on('click', '#initial_quote', function () {
        var clientName = $("#client_name").val().trim();
        var purpose = $("#purpose").val().trim();

        if (clientName != "" && purpose != "") {
            $.ajax({
                type: "post",
                url: "cust_quotation.php",
                data: {
                    type: 'add',
                    clientName: clientName,
                    purpose: purpose
                },
                dataType: "json",
                success: function (response) {
                    if (response.flag == false) {

                    } else if (response.flag > 0) {
                        LoadQuotation(response.flag);
                        sAlert("Quotation Successfully Initiated", "Quotation ID: " + response.flag);
                    }
                }
            });
        } else {
            sAlert("", "Client Name and Purpose should not be empty.", "error");
        }
    });

    $(document).on('click', '#update_quote', function () {
        var id = $("#hQuoteId").val().trim();
        var clientName = $("#client_name").val().trim();
        var purpose = $("#purpose").val().trim();

        if (id != "" && clientName != "" && purpose != "") {
            $.ajax({
                type: "post",
                url: "cust_quotation.php",
                data: {
                    type: 'mst_update',
                    id: id,
                    clientName: clientName,
                    purpose: purpose
                },
                dataType: "json",
                success: function (response) {
                    sAlert("Successfully update Initial information");
                    $("#details_btn").html(`
                            <button type="button" class="btn btn-sm bg-success border-white text-white px-3" id="details_add">
                                <i class="bi bi-plus-lg me-2"></i>Add Details
                            </button>
                        `);
                }
            });
        } else {
            sAlert("", "Client Name and Purpose should not be empty.", "error");
            $("#initial_quote").prop("disabled", false).removeClass("cursor-not-allowed");
        }
    });

    $(document).on('click', '#details_add', function () {
        var firstInvalid = null;
        var outdoorCheckBox = $("#details_for_outdoor").is(':checked');
        details_fields.forEach(element => {
            var value = (element.value || '').trim();

            if (outdoorCheckBox) {
                if (element.className == "select2-search__field") {
                    value = $('#details_package_dtl').val();
                }

                if (element.id == "details_package") {
                    value = "-";
                }
            } else if (
                element.className == "form-select select2-hidden-accessible"
                || element.className == "select2-search__field"
            ) {
                value = '-';
            } else {
                if (element.id == "details_outdoor_amt") {
                    value = "-";
                }
            }

            if (element.id == "details_add_ons") {
                value = value == 0 ? '-' : value;
            }

            if (element.id == "details_additional_amt") {
                value = element.valueAsNumber == 0 ? '-' : value;
            }

            element.classList.remove('border-danger');

            if (value == '' || value == 0) {
                element.classList.add('border-danger');
                if (!firstInvalid) {
                    firstInvalid = element;
                }
            }

        });

        if (firstInvalid) {
            firstInvalid.focus();
            return;
        }

        var quotationId = ($("#hQuoteId").val() || '').trim() || 0;
        var detailsDate = ($("#details_date").val() || '').trim();
        var detailsLocation = ($("#details_location").val() || '').trim() || '-';
        var packageDetailsId = $('#details_package_dtl').val().join(',');
        var detailsOutdoorAmt = ($("#details_outdoor_amt").val() || '').trim() || 0;
        var detailsPackage = ($("#details_package").val() || '').trim() || 0;
        var detailsAdditionalAmt = ($("#details_additional_amt").val() || '').trim() || 0;
        var detailsAddOns = $("#details_add_ons").val().trim();
        var detailsEventTime = ($("#details_event_time").val() || '').trim() || '-';
        var detailsReportTime = ($("#details_report_time").val() || '').trim() || '-';
        var detailsPhotog = $("#details_photog").val().trim();
        var detailsCinemetog = $("#details_cinemetog").val().trim();
        var detailsDrone = ($("#details_drone").val() || '').trim() || '-';

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'addQuoteDetails',
                quotationId: quotationId,
                detailsDate: detailsDate,
                detailsLocation: detailsLocation,
                packageDetailsId: packageDetailsId,
                detailsOutdoorAmt: detailsOutdoorAmt,
                detailsPackage: detailsPackage,
                detailsAdditionalAmt: detailsAdditionalAmt,
                detailsAddOns: detailsAddOns,
                detailsEventTime: detailsEventTime,
                detailsReportTime: detailsReportTime,
                detailsPhotog: detailsPhotog,
                detailsCinemetog: detailsCinemetog,
                detailsDrone: detailsDrone
            },
            dataType: "json",
            success: function (response) {
                if (response.flag == false) {
                    sAlert("Failed");
                } else {
                    quoteId = quotationId;
                    detailsTable.ajax.reload();
                    tableBreakdown.ajax.reload();
                    CleanDetails();
                    sAlert("Successfully added details in Quotation");
                    LoadQuotation(quoteId);
                }
            }
        });
    });

    $(document).on('click', '#details_update', function () {
        var id = $(this).data('dtl-id');

        var firstInvalid = null;
        var outdoorCheckBox = $("#details_for_outdoor").is(':checked');
        details_fields.forEach(element => {
            var value = (element.value || '').trim();

            if (outdoorCheckBox) {
                if (element.className == "select2-search__field") {
                    value = $('#details_package_dtl').val();
                }

                if (element.id == "details_package") {
                    value = "-";
                }
            } else if (
                element.className == "form-select select2-hidden-accessible"
                || element.className == "select2-search__field"
            ) {
                value = '-';
            } else {
                if (element.id == "details_outdoor_amt") {
                    value = "-";
                }
            }

            if (element.id == "details_add_ons") {
                value = value == 0 ? '-' : value;
            }

            if (element.id == "details_additional_amt") {
                value = element.valueAsNumber == 0 ? '-' : value;
            }

            element.classList.remove('border-danger');

            if (value == '' || value == 0) {
                element.classList.add('border-danger');
                if (!firstInvalid) {
                    firstInvalid = element;
                }
            }

        });

        if (firstInvalid) {
            firstInvalid.focus();
            return;
        }

        var quotationId = ($("#hQuoteId").val() || '').trim() || 0;
        var detailsDate = ($("#details_date").val() || '').trim();
        var detailsLocation = ($("#details_location").val() || '').trim() || '-';
        var packageDetailsId = $('#details_package_dtl').val().join(',');
        var detailsOutdoorAmt = ($("#details_outdoor_amt").val() || '').trim() || 0;
        var detailsPackage = ($("#details_package").val() || '').trim() || 0;
        var detailsAdditionalAmt = ($("#details_additional_amt").val() || '').trim() || 0;
        var detailsAddOns = $("#details_add_ons").val().trim();
        var detailsEventTime = ($("#details_event_time").val() || '').trim() || '-';
        var detailsReportTime = ($("#details_report_time").val() || '').trim() || '-';
        var detailsPhotog = $("#details_photog").val().trim();
        var detailsCinemetog = $("#details_cinemetog").val().trim();
        var detailsDrone = ($("#details_drone").val() || '').trim() || '-';

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'UpdateQuoteDetails',
                id: id,
                quotationId: quotationId,
                detailsDate: detailsDate,
                detailsLocation: detailsLocation,
                detailsPackage: detailsPackage,
                packageDetailsId: packageDetailsId,
                detailsOutdoorAmt: detailsOutdoorAmt,
                detailsAdditionalAmt: detailsAdditionalAmt,
                detailsAddOns: detailsAddOns,
                detailsEventTime: detailsEventTime,
                detailsReportTime: detailsReportTime,
                detailsPhotog: detailsPhotog,
                detailsCinemetog: detailsCinemetog,
                detailsDrone: detailsDrone
            },
            dataType: "json",
            success: function (response) {
                if (response.flag == false) {
                    sAlert("Failed");
                } else {
                    quoteId = quotationId;
                    detailsTable.ajax.reload();
                    tableBreakdown.ajax.reload();
                    CleanDetails();
                    sAlert("Successfully updated details in Quotation");
                    LoadQuotation(quoteId);
                }
            }
        });
    });

    $(document).on('click', '#breakdown_update', function () {
        var id = $(this).data('detail-id');

        var firstInvalid = null;

        var others_inputs = document.querySelectorAll(".section-breakdown textarea");

        others_inputs.forEach(element => {
            var value = (element.value || '').trim();

            element.classList.remove('border-danger');

            if (value == '') {
                element.classList.add('border-danger');
                if (!firstInvalid) {
                    firstInvalid = element;
                }
            }

        });

        if (firstInvalid) {
            firstInvalid.focus();
            return;
        }

        var breakdownEventType = ($("#breakdown_event_type").val() || '').trim();
        var breakdownDuration = ($("#breakdown_duration").val() || '').trim();

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'updateBreakdown',
                dtlId: id,
                breakdownEventType: breakdownEventType,
                breakdownDuration: breakdownDuration
            },
            dataType: "json",
            success: function (response) {
                if (response == false) {
                    sAlert("Failed", "", "error");
                } else {
                    $('#breakdown_event_type').val('');
                    $('#breakdown_duration').val('');
                    $('#breakdownBtn').html('');
                    tableBreakdown.ajax.reload();
                    sAlert("Successfully updated Cost Breakdown");
                }
            }
        });
    });

    $(document).on('click', '#detailEdit', function () {
        var id = $(this).data('detail-id');
        CleanDetails();
        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'getDtl',
                dtlId: id
            },
            dataType: "json",
            success: function (response) {
                if (response) {
                    var outdoor = response.package_id <= 0;
                    if (outdoor) {
                        LoadOutdoor(true);
                        var ids = response.out_purp_id.split(',');
                        $("#details_outdoor_amt").val(response.out_amt);
                        $("#details_package_dtl").val(ids).trigger('change');
                    }
                    $("#details_date").val(sDate(response.event_date));
                    $("#details_location").val(response.location);
                    $("#details_package").val(response.package_id);
                    $("#details_additional_amt").val(response.adjust_amt);
                    $("#details_add_ons").val(response.add_ons_id);
                    $("#details_event_time").val(response.event_time);
                    $("#details_report_time").val(response.report_time);
                    $("#details_photog").val(response.photog);
                    $("#details_cinemetog").val(response.cinemetog);
                    $("#details_drone").val(response.drone);

                    $("#details_btn").html(`
                            <button type="button" class="btn btn-sm bg-primary border-white text-white px-3" id="details_update" data-dtl-id="${response.id}">
                                Update Details
                            </button>
                        `);
                }
            }
        });
    });

    $(document).on('click', '#detailDelete', function () {
        var id = $(this).data('detail-id');
        var quotationId = ($("#hQuoteId").val() || '').trim() || 0;
        sAlertConfirm(() => {
            $.ajax({
                type: "post",
                url: "cust_quotation.php",
                data: {
                    type: 'detailDelete',
                    id: id,
                    quotationId: quotationId
                },
                dataType: "json",
                success: function (response) {
                    if (response == true) {
                        quoteId = quotationId;
                        detailsTable.ajax.reload();
                        sAlert("Successfully delete Quotation details");
                        LoadQuotation(quoteId);
                    }
                }
            });
        });
    });

    $(document).on('click', '#breakdownEdit', function () {
        var id = $(this).data('detail-id');

        $('#breakdown_event_type').val('');
        $('#breakdown_duration').val('');

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'getDtl',
                dtlId: id
            },
            dataType: "json",
            success: function (response) {
                console.log(response);
                if (response) {
                    $("#breakdown_event_type").val(response.event_type);
                    $("#breakdown_duration").val(response.duration);

                    $("#breakdownBtn").html(`
                            <button type="button" class="btn btn-sm bg-primary border-white text-white px-3" id="breakdown_update" data-detail-id="${response.id}">
                            Update Cost Breakdown</button>
                        `);
                }
            }
        });
    });

    var others_inputs = document.querySelectorAll(".section-others input");
    if (others_inputs) {
        others_inputs.forEach((input, index) => {
            input.addEventListener("keydown", function (e) {
                if (e.key === "Enter") {
                    e.preventDefault();

                    if (index < others_inputs.length - 1) {
                        var nextInput = others_inputs[index + 1];

                        nextInput.focus();
                        nextInput.select();
                    }
                }
            });
        });
    }

    $(document).on('click', '#others_update', function () {
        var firstInvalid = null;

        others_inputs.forEach(element => {
            var value = (element.value || '').trim();

            element.classList.remove('border-danger');

            if (value == '') {
                element.classList.add('border-danger');
                if (!firstInvalid) {
                    firstInvalid = element;
                }
            }

        });

        if (firstInvalid) {
            firstInvalid.focus();
            return;
        }

        var quotationId = ($("#hQuoteId").val() || '').trim() || 0;
        var othersEditPhoto = ($("#others_edit_photo").val() || '').trim() || '-';
        var othersPrintPhoto = ($("#others_print_photo").val() || '').trim() || '-';
        var othersPhotoQuality = ($("#others_photo_quality").val() || '').trim() || '-';
        var othersPromo = $("#others_promo").val().trim() || '-';
        var othersVideo = ($("#others_video").val() || '').trim() || '-';
        var othersAlbum = ($("#others_album").val() || '').trim() || '-';
        var othersPhotoFrame10l = $("#others_photo_frame10l").val().trim() || '-';
        var othersReels = ($("#others_reels").val() || '').trim() || 0;

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'updateOthers',
                quotationId: quotationId,
                othersEditPhoto: othersEditPhoto,
                othersPrintPhoto: othersPrintPhoto,
                othersPhotoQuality: othersPhotoQuality,
                othersPromo: othersPromo,
                othersVideo: othersVideo,
                othersAlbum: othersAlbum,
                othersPhotoFrame10l: othersPhotoFrame10l,
                othersReels: othersReels
            },
            dataType: "json",
            success: function (response) {
                if (response.flag == false) {
                    sAlert("Failed");
                } else {
                    $('#others_update').removeClass("bg-success").addClass("bg-primary").html("Update Others");
                    sAlert("Successfully updated others in Quotation");
                }
            }
        });
    });

    $(document).on('input', '#discount_discount', function () {
        var discount_total = $("#discount_total").val();
        var discount_discount = $("#discount_discount").val();
        var discount_after = document.getElementById("discount_after");
        var afterDiscount = sInt(discount_total) - sInt(discount_discount);

        discount_after.value = afterDiscount;

    });

    $(document).on('keyup', '#discount_discount', function (e) {
        if (e.key === 'Enter') {
            $("#apply_discount_btn").click();
        }
    });

    $(document).on('click', '#apply_discount_btn', function () {
        var id = $("#hQuoteId").val().trim();
        var discount_discount = $("#discount_discount").val();
        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: "discount",
                mstId: id,
                discount: discount_discount,
            },
            dataType: "json",
            success: function (response) {
                if (response.msg) {
                    sAlert(response.msg, "", "info");
                } else if (response == true) {
                    sAlert("Successfully Apply Discount Amount");
                } else {
                    sAlert(response);
                }
            }
        });
    });
});