<script>
	$(document).ready(function () {

        $(".phone_number_div").hide();
		$(".no_phone_number_div").show();
		$(".mobilephone").hide();

		$(".upload_phone_number_div").hide();

        // Initialize for both forms
        handleAssetTypeChange(
            "#asset_type_id", 
            ".phone_number_div", 
            ".no_phone_number_div", 
            ".mobilephone", 
            "#make_and_model_id", 
            "#technical_spec_id", 
            "#extra_fields",
            "#carriers"
        );

        handleAssetTypeChange(
            "#upload_asset_type_id", 
            ".upload_phone_number_div", 
            ".no_phone_number_div", 
            ".mobilephone", 
            "#upload_make_and_model_id", 
            "#upload_technical_spec_id", 
            "#extra_fields",
            "#carrier_id"
        );

        function handleAssetTypeChange(
            assetTypeSelector,
            phoneNumberDiv,
            noPhoneNumberDiv,
            mobilePhoneDiv,
            makeAndModelSelector,
            technicalSpecSelector,
            extraFieldsSelector,
            carrierSelector
        ) {
            $(assetTypeSelector).change(function () {
                const selectedValue = $(this).val();
                const selectedText = $.trim($(`${assetTypeSelector} option:selected`).text());

                if (!selectedValue || selectedValue === '--Select--' || selectedValue === '0') {
                    return; // Exit if no valid selection
                }

                try {
                    resetCommonElements(phoneNumberDiv, noPhoneNumberDiv, mobilePhoneDiv);

                    if (selectedText === "Mobile Phone") {
                        handleMobilePhoneSelection(phoneNumberDiv, noPhoneNumberDiv, mobilePhoneDiv, carrierSelector, selectedValue);
                    } else if (selectedText === "Mobile Phone Number") {
                        handleMobilePhoneNumberSelection(phoneNumberDiv, noPhoneNumberDiv,mobilePhoneDiv, carrierSelector, selectedValue);
                    } else if (selectedText === "Printer") {
                        $(".lease-fields").show('slow');
                    }

                    fetchHardwareList(selectedValue, makeAndModelSelector, technicalSpecSelector);
                    fetchExtraFields(selectedValue, extraFieldsSelector);
                } catch (err) {
                    console.error("Error in asset type change logic:", err);
                }
            });
        }

        // Helper function to reset common elements
        function resetCommonElements(phoneNumberDiv, noPhoneNumberDiv, mobilePhoneDiv) {
            $(phoneNumberDiv).hide();
            $(noPhoneNumberDiv).show();
            $(".lblserial_and_phone").html('Serial #<span class="text-danger">*</span>');
            $(mobilePhoneDiv).hide();
            $(".lease-fields").hide();
            $('#serial_no').unmask('(000) 000-0000');
        }

        // Helper function for Mobile Phone selection
        function handleMobilePhoneSelection(phoneNumberDiv, noPhoneNumberDiv, mobilePhoneDiv, carrierSelector, selectedValue) {
            $(phoneNumberDiv).show();
            $(noPhoneNumberDiv).show();
            $(".lblserial_and_phone").html("Serial #<span class='text-danger'>*</span>");
            $(mobilePhoneDiv).show();
            getCarrier(selectedValue, carrierSelector);
            $(".lease-fields").show('slow');
        }

        // Helper function for Mobile Phone Number selection
        function handleMobilePhoneNumberSelection(phoneNumberDiv, noPhoneNumberDiv, mobilePhoneDiv,carrierSelector, selectedValue) {
            $(phoneNumberDiv).show();
            $(noPhoneNumberDiv).hide();
            $(".lblserial_and_phone").html("Mobile Phone Number<span class='text-danger'>*</span>");
            $('#serial_no').mask('(000) 000-0000');
            $(mobilePhoneDiv).hide();
            getCarrier(selectedValue, carrierSelector);
        }

        // Helper function to fetch hardware list
        function fetchHardwareList(selectedValue, makeAndModelSelector, technicalSpecSelector) {
            $.ajax({
                type: "POST",
                data: { id: selectedValue, type: $('#category').val() },
                url: "/assets-create/listHardware",
                success: function (data) {
                    updateDropdown(makeAndModelSelector, data, 'hardware');
                    updateDropdown(technicalSpecSelector, [], '');
                },
                error: function () {
                    console.error("Error fetching hardware list.");
                }
            });
        }

        // Helper function to fetch extra fields
        function fetchExtraFields(selectedValue, extraFieldsSelector) {
            $.ajax({
                type: "POST",
                data: { id: selectedValue },
                url: "{{ route('assets-create.list-additional-attributes') }}",
                success: function (data) {
                    $(extraFieldsSelector).html(data);
                },
                error: function () {
                    console.error("Error fetching extra fields.");
                }
            });
        }

        function handleMakeAndModelChange(makeAndModelSelector, technicalSpecSelector, url = "/assets-create/listtechnics") {
            $(makeAndModelSelector).change(function () {
                const selectedValue = $(this).val();
                if (selectedValue && selectedValue !== '--Select--' && selectedValue !== '0') {
                    try {
                        $.ajax({
                            type: "POST",
                            data: { id: selectedValue },
                            url: url,
                            success: function (data) {
                                updateDropdown(technicalSpecSelector, data, 'details');
                            },
                            error: function (xhr, status, error) {
                            }
                        });
                    } catch (err) {
                        console.error("An error occurred:", err);
                    }
                }
            });
        }

        // Usage
        handleMakeAndModelChange("#make_and_model_id", "#technical_spec_id");
        handleMakeAndModelChange("#upload_make_and_model_id", "#upload_technical_spec_id");

        // Reusable function for updating dropdowns
        function updateDropdown(dropdownId, data, textField) {
            const $dropdown = $(dropdownId);
            $dropdown.empty();
            $dropdown.append($('<option>', {
                value: '',
                text: "--Select--"
            }));
            $dropdown.select2();
            $.each(data, function (key, value) {
                $dropdown.append($('<option>', {
                    value: value.id,
                    text: value[textField]
                }));
            });
        }


        function getCarrier(id, carrierSelector = '#carriers') {
            if (!id) {
                console.warn("Invalid ID provided for fetching carriers.");
                return;
            }

            $.ajax({
                type: "POST",
                data: { id: id },
                url: "{{ route('list-carrier') }}",
                success: function (data) {
                    updateDropdown(carrierSelector, data,'name');
                },
                error: function (xhr, status, error) {
                    console.warn("No carrier data returned.");
                }
            });
        }
    });
</script>