$(document).ready(function () {
    $("body").on("keyup blur", ".qty, .rate, .roe, .carryperc, .dumprate, .othchgs, .unitqty, .unitamt", CalcAmt);
    $("body").on("keyup", ".amount", CalcAmt);

    $("body").on("change", ".mstate", getStateCode);
    $("body").on("change", ".type", typeairsea);

    $("#partyModal").on("shown.bs.modal", function () {
        $("#party_name").focus();
    });

    // Open modal
    $('#createPartyBtn').click(function () {
        $('#party_name').val('');
        $('.mstate').val('').trigger("change");
        $('.mstatecode').val('');
        $('.mmobile').val('');
        $('#partyModal').modal('show');
    });

    // Save party
    $('#saveParty').click(function () {

        var pname = $('#party_name').val().trim();
        var mstate = $('.mstate').val();
        var mstatecode = $('.mstatecode').val();
        var party_gstno = $('.party_gstno').val();
        var mmobile = $('.mmobile').val();

        if (pname === '') {
            alert('Enter party name');
            $("#party_name").focus();

            return;
        }

        $.ajax({
            url: "createparty.php",
            type: "POST",
            dataType: "json",
            data: { name: pname, state: mstate, statecode: mstatecode, mobile: mmobile, gstno: party_gstno },
            success: function (res) {
                // 🔴 Party already exists
                if (res.status === "exists") {
                    alert("Party With Same Name Already Exists! In Customer Or Supplier Master");
                    $("#partyModal").modal("hide");

                    setTimeout(function () {
                        // open select2
                        $(".party").select2("open");

                        // wait till dropdown opens, then fill search
                        setTimeout(function () {
                            var searchInput = document.querySelector(
                                ".select2-container--open .select2-search__field",
                            );

                            if (searchInput) {
                                searchInput.value = res.name;
                                searchInput.dispatchEvent(
                                    new Event("input", { bubbles: true }),
                                );
                                searchInput.dispatchEvent(
                                    new KeyboardEvent("keydown", {
                                        key: "ArrowDown",
                                    }),
                                );

                            }
                        }, 50);
                    }, 300);

                    return;
                }

                // 🟢 New party created
                var option = new Option(res.name, res.accode, true, true);
                $(".party").append(option).val(res.accode).trigger("change");
                $("#partyModal").modal("hide");
            },

        });
    });



    function getStateCode() {
        var state = $(".mstate").val();
        $.get('get_stcode.php', { state: state }, function (data) {
            $(".mstatecode").val(data);
        });
    }

    typeairsea();

    function typeairsea() {
        var type = $(".type").val();

        if (type == "A") {
            $(".showairchgs").show();
            $(".showcarrychgs").hide();
            $(".carryperc").val("0");
            $(".carryamt").val("0");
        } else if (type == "S") {
            $(".showcarrychgs").show();
            $(".showairchgs").hide();
            $(".unitqty").val("0");
            $(".unitamt").val("0");
            $(".unitotal").val("0");
        }

    }


    function CalcAmt(e) {

        var qty = parseFloat($(".qty").val()) || 0;
        var rate = parseFloat($(".rate").val()) || 0;
        var amount = parseFloat($(".amount").val()) || 0;

        // If user changed Qty or Rate, calculate Amount

        if ($(e.target).hasClass("qty") || $(e.target).hasClass("rate")) {
            if (rate > 0) {
                amount = qty * rate;
                $(".amount").val(amount.toFixed(2));
            }
        }

        // If user entered Amount manually, make Rate zero
        if ($(e.target).hasClass("amount")) {
            if (rate > 0) {
                $(".rate").val(0);
                rate = 0;
            }
        }

        var roe = parseFloat($(".roe").val()) || 0;
        var carryperc = parseFloat($(".carryperc").val()) || 0;
        var dumpqty = parseFloat($(".dumpqty").val()) || 0;
        var dumprate = parseFloat($(".dumprate").val()) || 0;
        var othchgs = parseFloat($(".othchgs").val()) || 0;
        var unitqty = parseFloat($(".unitqty").val()) || 0;
        var unitamt = parseFloat($(".unitamt").val()) || 0;

        var roeamt = Math.round(amount * roe);
        var carryamt = Math.round(roeamt * carryperc / 100);
        var dumpamt = Math.round(dumpqty * dumprate);
        var unittotal = Math.round(unitqty * unitamt);

        $(".roeamt").val(roeamt);
        $(".carryamt").val(carryamt);
        $(".dumpamt").val(dumpamt);
        $(".unittotal").val(unittotal);

        var netamt = roeamt + carryamt + dumpamt + othchgs + unittotal;
        $(".netamt").val(Math.round(netamt));
    }

    // $(".image").change(function () {
    //     readURL1(this);
    // });


    // function readURL1(input) {
    //     if (input.files && input.files[0]) {
    //         var reader = new FileReader();

    //         reader.onload = function (e) {
    //             $('.view1').attr('src', e.target.result);
    //         }

    //         reader.readAsDataURL(input.files[0]);
    //     }
    // }

    $("body").on("click", ".skimg", function () {
        var src = $(this).attr("src");
        $("#fullImage").attr("src", src);
        $("#imgModal").modal("show");
    });

    function resetImages() {

        dt.items.clear();

        $("#images").val("");

        $(".imageGallery .newImage").remove();

        updateImageCount();

    }

    const dt = new DataTransfer();

    $("#images").on("change", function () {

        var dbCount = $(".imageGallery .imgCard:not(.newImage)").length;

        $.each(this.files, function (i, file) {

            // 1. Check image size first
            if (file.size > 500000) {

                alert(file.name + " is larger than 500 KB.");

                return true;   // Skip this image completely

            }

            // 2. Count only images actually displayed
            var total = $(".imageGallery .imgCard").length;

            if (total >= 10) {

                alert("Maximum 10 Images Allowed.");

                return false;

            }

            // 3. Add only valid images
            dt.items.add(file);

            var index = dt.items.length - 1;

            var reader = new FileReader();

            reader.onload = function (e) {

                $(".imageGallery").append(

                    '<div class="col-md-6 imgCard newImage" data-index="' + index + '">' +

                    '<img src="' + e.target.result + '" class="skimg">' +

                    '<div class="imgBtns">' +

                    '<button type="button" class="deleteBtn removeImage">Delete</button>' +

                    '</div>' +

                    '</div>'

                );

                updateImageCount();

            };

            reader.readAsDataURL(file);

        });

        $("#images")[0].files = dt.files;

        // Clear selection so selecting the same image again works
        // this.value = "";

    });

    // for newly added image delete

    $("body").on("click", ".removeImage", function () {

        var card = $(this).closest(".imgCard");

        var index = card.data("index");

        dt.items.remove(index);

        $("#images")[0].files = dt.files;

        card.remove();

        // Re-index remaining images
        $(".imageGallery .newImage").each(function (i) {

            $(this).attr("data-index", i);

        });

        updateImageCount();

    });


    function updateImageCount() {

        var total = $(".imageGallery .imgCard").length;

        $(".imageCount").text(total);

        if (total >= 10) {

            $(".skbtn")
                .addClass("form")
                .text("Maximum Images Reached");

        } else {

            $(".skbtn")
                .removeClass("form")
                .text("Choose Images");

        }
    }

    // for uploaded image delete

    $("body").on("click", ".deleteDbImage", function () {

        if (!confirm("Delete this image?")) return;

        var card = $(this).closest(".imgCard");

        var id = $(this).data("id");

        $("<input>")
            .attr({
                type: "hidden",
                name: "deleteImages[]",
                value: id
            })
            .appendTo("form");

        card.remove();

        updateImageCount();

    });




    $("body").on("click", ".replaceBtn", function () {

        $(this).next(".replaceInput").click();

    });

    $("body").on("change", ".replaceInput", function () {

        var file = this.files[0];

        if (!file) return;

        var reader = new FileReader();

        var img = $(this).closest(".imgCard").find("img");

        reader.onload = function (e) {

            img.attr("src", e.target.result);

        };

        reader.readAsDataURL(file);

    });


});