<script src="/js/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="/js/validator-methods.js"></script>
<script src="/js/plugins/chosen/chosen.jquery.js"></script>
<script src="/js/plugins/chosen/chosen.ajaxaddition.jquery.js"></script>
<script src="/js/plugins/jquery-validation/additional-methods.min.js"></script>

<script>
	
	$(".select2").select2();

	$('.chosen-select').chosen({ width: "100%" }).change(function () {
		// $(this).closest('.form-group').next().find('input').focus();
	});

    $('#data_1 .input-group.date').datepicker({

        todayBtn: "linked",

        clearBtn: true,

        keyboardNavigation: false,

        forceParse: false,

        calendarWeeks: false,

        autoclose: true

    });

    var currentDate = new Date();
	$('.previous_date_picker .input-group.date').datepicker({

		todayBtn: "linked",

		clearBtn: true,

		keyboardNavigation: false,

		forceParse: false,

		calendarWeeks: false,

		autoclose: true,

		endDate: "currentDate",

        maxDate: currentDate

	});

    // show modals
    $(".selectbox").change(function () {

        if ($(this).attr('data-parent')) {
            $('#update-error-child').modal('show');
            return false;
        }

        var selectedText = $(this).find("option:selected").text().toLowerCase().replace(/ /g, '-').replace(/\//g, '-');
        selectedText = selectedText.replace('---', '-');
        var assetId = $(this).attr("data-id");
        var statusId = $(this).val();
        var currentAssetStatus = $(this).attr("data-status");

        // Show "retain-hold-extra" modal if current status is "retain_hold"
		if (currentAssetStatus === 'retain_hold') {
			var $modal = $("#retain-hold-extra");
			$modal.data('selectedText', selectedText);
			$modal.find('#asset_id').val(assetId);
			$modal.find('#status_id').val(statusId);
			$modal.modal('show');
		} else {
            // otherwise, show selected asset status modal
            var availableModals = getAvailableModals();

            if ($.inArray(selectedText, availableModals) >= 0) {
                showModal(selectedText, assetId, statusId);
            }
        }

    });

    // retain-hold-extra data
	$("#search-asset-retain-hold-extra-form").submit(function (e) {
		e.preventDefault();
		var form = $("#search-asset-retain-hold-extra-form");
		// Validate the form before submission
		if (form.valid()) {
			var modal = $("#retain-hold-extra");
			var selectedText = modal.data('selectedText');
			var assetId = modal.find("#asset_id").val();
			var statusId = modal.find("#status_id").val();
			modal.modal('hide');

            var secondModal = $('#' + selectedText);
            var availableModals = getAvailableModals();

            if ($.inArray(selectedText, availableModals) >= 0) {
                showModal(selectedText, assetId, statusId);
            }

            // Store retain-hold-extra form data
            var retainHoldData = {
                wipe_confirmation: modal.find('input[name="wipe_confirmation"]').val(),
                retain_hold_wipe_confirmed_date: modal.find('input[name="retain_hold_wipe_confirmed_date"]').val(),
                retain_hold_note: modal.find('textarea[name="retain_hold_note"]').val()
            };

            // Append the retain-hold-extra data to the second modal as hidden inputs
            appendExtraDataToModal(retainHoldData, secondModal);
		}
	});

    /**
    * Get the current user
    * @param mixed assetId
    * 
    * @return [type]
    */
    function getAssetCurrentUser(assetId) {
        if(!assetId){
            return;
        }

        $.ajax({
            type: "POST",
            url: '{{route('search-assets.get-user')}}',
            data: { id: assetId },
            success: function (data) {
                return data;
            },
            error: function (data) {
                return false;
            },
        });
    }

    /**
    * Get the list of available modal identifiers.
    */
    function getAvailableModals() {
        return [
            'assigned',
            'brand-new',
            'damaged',
            'end-of-life',
            'end-of-life-data-wiped',
            'installed',
            'in-repair',
            'legal-hold',
            'loaner',
            'loaned',
            'pending-return',
            'rma-returned',
            'retain-hold',
            'stolen-lost',
            'used'
        ];
    }

    /**
    * Show the modal
    * @param mixed modal
    * @param mixed assetId
    * @param mixed statusId
    * 
    * @return [type]
    */
    function showModal(modal, assetId, statusId) {
        $('#' + modal).modal('show');
        // $('#' + modal).find('select').next().addClass('chosen-with-drop').find('input').focus();
        $('#' + modal).find('#asset_id').val(assetId);
        $('#' + modal).find('#status_id').val(statusId);
    }


    // General handler for form submission
    $(document).on('click', '.status-form-submit-btn', function () {
        var formSelector = $(this).data('form'); // Get the form selector from the button's data attribute
        let $form = $(this).closest('.modal').find('form');
        let mdmCreateForm = $form.find("input[name='mdm_create_asset']").val();

        // MDM create asset form handling
        if (mdmCreateForm) {
            $(formSelector).attr('action', $(mdmCreateForm).attr('action'));
        }

        if (formSelector) {
            $(formSelector).submit();
        }
    });

    // Generalized form validation setup
    function setupValidation(formSelectors) {
        $.validator.setDefaults({
            ignore: ":hidden:not(select)",
            errorPlacement: function (error, element) {
                // Custom error placement
                if ($.inArray(element.attr("name"), ["loaner_return_date","lost_date","loaner_retention_date","retain_hold_wipe_confirmed_date"]) >= 0) {
				    error.insertAfter(element.closest('.input-group').next('.errorText'));
                }
                else if (element.attr("type") == "file") {
                    error.insertAfter(element.closest('.input-group').next('.errorTextFile')); // Use element's context
                } 
                else{
                    error.insertAfter($(element).next($('.errorText')));
                }
            }
        });

        formSelectors.forEach(selector => {
            const validationConfig = {
                onkeyup: false,
                excluded: ':disabled',
            };

            // Apply specific rules/messages based on the form selector
            if ($.inArray(selector, ["#search-asset-end-of-life-ewaste-form","#search-asset-end-of-life-data-wiped-form"]) >=0) {
                validationConfig.rules = {
                    ewaste_certificate: {
                        required: true,
                        extension: "pdf"
                    }
                };
                validationConfig.messages = {
                    ewaste_certificate: {
                        required: "File is required",
                        extension: "Invalid format. Upload PDF file"
                    }
                };
            }

            $(selector).validate(validationConfig);
        });
    }
    

    // Initialize validation for forms
    const formsToValidate = [
        "#search-asset-assigned-form",
        "#search-asset-damaged-form",
        "#search-asset-brand-new-form",
        "#search-asset-end-of-life-form",
        "#search-asset-installed-form",
        "#search-asset-legal-hold-form",
        "#search-asset-in-repair-form",
        "#search-asset-pending-return-form",
        "#search-asset-rma-returned-form",
        "#search-asset-used-form",
        "#search-asset-stolen-lost-form",
        "#search-asset-loaner-form",
        "#search-asset-loaned-form",
        "#search-asset-retain-hold-form",
        "#search-asset-retain-hold-extra-form",
        "#search-asset-end-of-life-data-wiped-form"

    ];

    setupValidation(formsToValidate);

    // Append input data to the new modal.
    function appendExtraDataToModal(extraData, newModal) {
        $.each(extraData, function (name, value) {
            if (value) {
                var existingInput = newModal.find('input[name="' + name + '"], textarea[name="' + name + '"]');
                if (existingInput.length) {
                    existingInput.val(value);
                } else {
                    $('<input>').attr({
                        type: 'hidden',
                        name: name,
                        value: value
                    }).appendTo(newModal.find('form'));
                }
            }
        });
    }

</script>