$(document).ready(function () {
    var currentUrl = new URLSearchParams(window.location.search);
    var quoteId = currentUrl.get('quote_id') ?? 0;

    sDateTime('#details_date');

    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: '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() {
        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>`;

        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");

        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();
                        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>
                        `);

                        if (quoteOthers) {
                            $('#others_edit_photo').val(quoteOthers.edited_photo);
                            $('#others_print_photo').val(quoteOthers.printed_photo);
                            $('#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_drone').val(quoteOthers.drone);
                            $('#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_date").val("");
        $("#details_location").val("-");
        $("#details_package").val("1");
        $("#details_add_ons").val("0");
        $("#details_event_time").val("-");
        $("#details_report_time").val("-");
        $("#details_photog").val("1");
        $("#details_cinemetog").val("1");
    }

    CleanDetails();

    $(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;

        details_fields.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 detailsDate = ($("#details_date").val() || '').trim();
        var detailsLocation = ($("#details_location").val() || '').trim() || '-';
        var detailsPackage = ($("#details_package").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();

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'addQuoteDetails',
                quotationId: quotationId,
                detailsDate: detailsDate,
                detailsLocation: detailsLocation,
                detailsPackage: detailsPackage,
                detailsAddOns: detailsAddOns,
                detailsEventTime: detailsEventTime,
                detailsReportTime: detailsReportTime,
                detailsPhotog: detailsPhotog,
                detailsCinemetog: detailsCinemetog
            },
            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");
                }
            }
        });
    });

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

        var firstInvalid = null;

        details_fields.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 detailsDate = ($("#details_date").val() || '').trim();
        var detailsLocation = ($("#details_location").val() || '').trim() || '-';
        var detailsPackage = ($("#details_package").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();

        $.ajax({
            type: "post",
            url: "cust_quotation.php",
            data: {
                type: 'UpdateQuoteDetails',
                id: id,
                quotationId: quotationId,
                detailsDate: detailsDate,
                detailsLocation: detailsLocation,
                detailsPackage: detailsPackage,
                detailsAddOns: detailsAddOns,
                detailsEventTime: detailsEventTime,
                detailsReportTime: detailsReportTime,
                detailsPhotog: detailsPhotog,
                detailsCinemetog: detailsCinemetog
            },
            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");
                    $("#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>
                        `);
                }
            }
        });
    });

    $(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");
                }
            }
        });
    });

    var details_fields = document.querySelectorAll(".section-details input, .section-details select");
    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('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) {
                console.log(response);
                if (response) {
                    $("#details_date").val(sDate(response.event_date));
                    $("#details_location").val(response.location);
                    $("#details_package").val(response.package_id);
                    $("#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_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) {
                    quoteId = quotationId;
                    detailsTable.ajax.reload();
                    sAlert("Successfully delete Quotation details");
                    $("#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>
                        `);
                }
            });
        });
    });

    $(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 othersDrone = $("#others_drone").val().trim() || '-';

        $.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,
                othersDrone: othersDrone
            },
            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");
                }
            }
        });
    });
});