$(document).ready(function () {
    jalaliDatepicker.startWatch({
        minDate: "attr",
        maxDate: "attr",
        minTime: "attr",
        maxTime: "attr",
        time: true,
        date: true,
        hasSecond: true,
        hideAfterChange: false,
        autoHide: true,
        showTodayBtn: true,
        showEmptyBtn: true,
        topSpace: 10,
        bottomSpace: 30,
        overflowSpace: -10,
        dayRendering(opt, input) {
            return {
                isHollyDay: opt.day == 1,
            };
        },
    });
});

document.addEventListener("DOMContentLoaded", function () {
    const tableBody = document.getElementById("FormBodyTable");
    let rowCounter = document.querySelectorAll("#FormBodyTable tr").length;

    initializeWeightSum();

    let chiefPriceInputs = document.querySelectorAll(
        'input[name="chiefprice1[]"]'
    );

    let workerPriceInputs = document.querySelectorAll(
        'input[name="workerprice1[]"]'
    );

    initializeSelect2();

tableBody.addEventListener("click", function (e) {
    if (e.target.classList.contains("addrow")) {
        const currentRow = e.target.closest("tr");
        
        // ابتدا select2 ردیف جاری رو destroy کنید
        const currentSelect = currentRow.querySelector('select[name="chiefWorker[]"]');
        if (currentSelect && $(currentSelect).hasClass("select2-hidden-accessible")) {
            $(currentSelect).select2("destroy");
        }

        const newRow = currentRow.cloneNode(true);

        // حذف select2 از ردیف جدید
        newRow
            .querySelectorAll(".select2-container")
            .forEach((container) => {
                container.remove();
            });

        newRow
            .querySelectorAll('select[name="chiefWorker[]"]')
            .forEach((select) => {
                select.classList.remove("select2-hidden-accessible");
                select.removeAttribute("data-select2-id");
                select.removeAttribute("tabindex");
                select.removeAttribute("aria-hidden");
                select.removeAttribute("id");
            });

        rowCounter++;

        // آپدیت آیکون
        const addIcon = newRow.querySelector(".fa-circle-plus");
        if (addIcon) {
            addIcon.classList.remove("fa-circle-plus", "addrow");
            addIcon.classList.add("fa-circle-minus", "remove-row");
            addIcon.style.color = "#dc3545";
        }

        // ایجاد ID جدید برای select
        const selectElement = newRow.querySelector(
            'select[name="chiefWorker[]"]'
        );
        if (selectElement) {
            const newId = "chiefWorker_" + rowCounter + "_" + Date.now();
            selectElement.id = newId;
        }

        // ریست کردن مقادیر
        newRow.querySelectorAll("input").forEach((input) => {
            input.value = "";
            if (input.hasAttribute("data-jdp") && input._jdp) {
                input._jdp.destroy();
            }
        });

        newRow.querySelectorAll('input[name="chiefprice1[]"]').forEach((input) => {
            input.value = addPriceSeparator(chiefWorkerPrice);
        });

        newRow.querySelectorAll('input[name="chiefprice[]"]').forEach((input) => {
            input.value = chiefWorkerPrice;
        });

        newRow.querySelectorAll('input[name="workerprice1[]"]').forEach((input) => {
            input.value = addPriceSeparator(workerPrice);
        });

        newRow.querySelectorAll('input[name="workerprice[]"]').forEach((input) => {
            input.value = workerPrice;
        });

        newRow.querySelectorAll("select").forEach((select) => {
            select.selectedIndex = 0;
        });

        currentRow.after(newRow);

        // initialize مجدد select2 برای ردیف اصلی و جدید
        initializeSelect2ForRow(currentRow);
        initializeSelect2ForRow(newRow);
        initializeWeightSum();

        // سایر initializerها
        if (typeof jDatepicker !== "undefined") {
            const dateInput = newRow.querySelector("input[data-jdp]");
            if (dateInput) {
                jDatepicker(dateInput);
            }
        }

        chiefPriceInputs = document.querySelectorAll(
            'input[name="chiefprice1[]"]'
        );

        workerPriceInputs = document.querySelectorAll(
            'input[name="workerprice1[]"]'
        );

        workerPriceInputs.forEach((input) => {
            input.addEventListener("input", function () {
                updateChiefPriceWorker(this);
            });
        });

        chiefPriceInputs.forEach((input) => {
            input.addEventListener("input", function () {
                updateChiefPrice(this);
            });
        });
    }

    if (e.target.classList.contains("remove-row")) {
        if (tableBody.querySelectorAll("tr").length <= 1) {
            alert("حداقل باید یک ردیف وجود داشته باشد!");
            return;
        }

        const row = e.target.closest("tr");
        const selectElement = row.querySelector(
            'select[name="chiefWorker[]"]'
        );
        if (
            selectElement &&
            $(selectElement).hasClass("select2-hidden-accessible")
        ) {
            $(selectElement).select2("destroy");
        }

        row.remove();
    }
});

function initializeSelect2() {
    $('select[name="chiefWorker[]"]').each(function () {
        if (!$(this).hasClass("select2-hidden-accessible")) {
            if (!this.id) {
                this.id =
                    "chiefWorker_" +
                    Date.now() +
                    "_" +
                    Math.random().toString(36).substr(2, 9);
            }

            $(this).select2({
                theme: "bootstrap-5",
                placeholder: "انتخاب سرتیم",
                allowClear: false,
                language: "fa",
                width: "100%",
            });
        }
    });
}

// تابع برای initialize فقط یک ردیف خاص
function initializeSelect2ForRow(row) {
    const selectElement = row.querySelector('select[name="chiefWorker[]"]');
    if (selectElement && !$(selectElement).hasClass("select2-hidden-accessible")) {
        if (!selectElement.id) {
            selectElement.id = "chiefWorker_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
        }

        $(selectElement).select2({
            theme: "bootstrap-5",
            placeholder: "انتخاب سرتیم",
            allowClear: false,
            language: "fa",
            width: "100%",
        });
    }
}

    function initializeWeightSum()
    {
        let AllWeight = document.querySelectorAll('input[name="weight[]"]');
        AllWeight.forEach((input) => {
            input.addEventListener('input', function(){
                let sumWeight = 0;
                AllWeight.forEach((input1) => {
                    let newnum = input1.value;
                    if(newnum == '' || newnum == null)
                    {
                        newnum = 0;
                    }
                    sumWeight = sumWeight + parseFloat(newnum);
                });
                document.getElementById('sumWeight').textContent = sumWeight;
            });
        });
    }
    const submitBtn = document.getElementById("SubmitFormBtn");
    submitBtn.addEventListener("click", function (e) {
        e.preventDefault();
        const editForm = document.getElementById("EditForm");
        const oldWeight = Number(document.getElementById("oldweight").value);
        let newWeight = 0;
        document.querySelectorAll('input[name="weight[]"]').forEach((input) => {
            if (input.value != null && input.value != "") {
                newWeight = newWeight + Number(input.value);
            }
        });

        if (oldWeight > newWeight) {
            Swal.fire({
                title: "اخطار زربرج",
                text: "همه وزن ها توزیع نشده است.",
                icon: "error",
                confirmButtonText: "متوجه شدم",
            });
        } else if (oldWeight < newWeight) {
            Swal.fire({
                title: "اخطار زربرج",
                text: "وزن توزیع شده بیشتر از وزن اعلامی می باشد.",
                icon: "error",
                confirmButtonText: "متوجه شدم",
            });
        } else if (oldWeight == newWeight) {
            editForm.submit();
        }
    });

    chiefPriceInputs.forEach((input) => {
        input.addEventListener("input", function () {
            updateChiefPrice(this);
        });
    });

    function updateChiefPrice(inputElement) {
        const inputs = document.querySelectorAll('input[name="chiefprice1[]"]');
        const index = Array.from(inputs).indexOf(inputElement);

        const hiddenInputs = document.querySelectorAll(
            'input[name="chiefprice[]"]'
        );

        if (hiddenInputs[index]) {
            hiddenInputs[index].value = removePriceSeparator(
                inputElement.value
            );
            inputElement.value = addPriceSeparator(inputElement.value);
        }
    }

    workerPriceInputs.forEach((input) => {
        input.addEventListener("input", function () {
            updateChiefPriceWorker(this);
        });
    });

    function updateChiefPriceWorker(inputElement) {
        const inputs = document.querySelectorAll(
            'input[name="workerprice1[]"]'
        );
        const index = Array.from(inputs).indexOf(inputElement);

        const hiddenInputs = document.querySelectorAll(
            'input[name="workerprice[]"]'
        );

        if (hiddenInputs[index]) {
            hiddenInputs[index].value = removePriceSeparator(
                inputElement.value
            );
            inputElement.value = addPriceSeparator(inputElement.value);
        }
    }

    function addPriceSeparator(number) {
        number = removePriceSeparator(number);

        if (parseInt(number) >= 0) {
            return parseInt(number).toLocaleString();
        }
        return 0;
    }

    function removePriceSeparator(formattedNumber) {
        return formattedNumber.toString().replace(/,/g, "");
    }
});
