'use strict';
$(document).ready(function() {
	$("#loaderImageIcon").hide();
    // Handle delete button click
    $('#nestable').on('click', '.delete-button', function() {
      var item = $(this).closest('.dd-item');
      item.remove();
      updateOutput($('#nestable'));
    });

    // Handle edit button click
    $('#nestable').on('click', '.action-btn', function() {
      var item = $(this).closest('.dd-item');
      var itemEditor = item.find('.item-editor');
      itemEditor.toggle();
    });


    // Handle Add to Menu button click
    $('#addToMenuButton').on('click', function() {
      var url = $('#MenuUrl').val();
      var text = $('#MenuText').val();

      if (url && text) {
        var newItem = $('<li class="dd-item dd3-item"></li>')
		.attr('data-id', Math.random().toString(36).substr(2, 9))
		.attr('data-url', url)
		.attr('data-name', text)
		.attr('data-target', '_self')
		.append('<div class="dd-handle dd3-handle"></div> <div class="dd3-content"><span class="menu-name-item">'+ text +'</span><span class="action-btn">Edit</span><div class="item-editor" style="display: none;"><input class="name-input form-control form-control-sm mt-2" type="text" value="'+ text +'" placeholder="Link Name"><input class="link-input form-control form-control-sm mt-1" type="text" value="'+ url +'" placeholder="Link URL"><select class="open-with-select form-control form-control-sm mt-1"><option value="_blank">Open in New Tab</option><option value="_self" selected>Open in Same Tab</option></select><div class="mt-2"><span class="update-menu-item text-success ">Update</span> | <span class="delete-button text-danger">Delete</span></div></div></div>')

        $('#nestable > .dd-list').append(newItem);

        updateOutput($('#nestable'));

        $('#MenuUrl').val('');
        $('#MenuText').val('');
      }
    });

	// Handle Add to from page and category Menu button click
	$('.addValueToMenu').on('click', function() {
		// Get values from data attributes of the clicked button
		var url = $(this).data('url');
		var text = $(this).data('text');

		if (url && text) {
			var newItem = $('<li class="dd-item dd3-item"></li>')
				.attr('data-id', Math.random().toString(36).substr(2, 9))
				.attr('data-url', url)
				.attr('data-name', text)
				.attr('data-target', '_self')
				.append('<div class="dd-handle dd3-handle"></div> <div class="dd3-content"><span class="menu-name-item">'+ text +'</span><span class="action-btn">Edit</span><div class="item-editor" style="display: none;"><input class="name-input form-control form-control-sm mt-2" type="text" value="'+ text +'" placeholder="Link Name"><input class="link-input form-control form-control-sm mt-1" type="text" value="'+ url +'" placeholder="Link URL"><select class="open-with-select form-control form-control-sm mt-1"><option value="_blank">Open in New Tab</option><option value="_self" selected>Open in Same Tab</option></select><div class="mt-2"><span class="update-menu-item text-success ">Update</span> | <span class="delete-button text-danger">Delete</span></div></div></div>');

			$('#nestable > .dd-list').append(newItem);

			updateOutput($('#nestable'));
		}
	});

    // Handle update menu item button click
    $('#nestable').on('click', '.update-menu-item', function() {
      var item = $(this).closest('.dd-item');
      var name = item.find('.name-input').val();
      var url = item.find('.link-input').val();
      var target = item.find('.open-with-select').val();

      item.data('name', name);
      item.data('url', url);
      item.data('target', target);

      // Update the text of dd-handle with the entered name
      item.find('.menu-name-item').text(name);

      updateOutput($('#nestable'));
      // Add AJAX request here to save the data in the database
    });

    // FOr Output Update
    var updateOutput = function(e) {
        var list = e.length ? e : $(e.target),
            output = list.data('output');
        if (window.JSON) {
              output.val(window.JSON.stringify(list.nestable('serialize')));
              var nestedList = list.nestable('serialize');
              saveToDatabase(JSON.stringify(nestedList));
        } else {
            output.val('JSON browser support required for this features.');
        }
    };

    // AJAX function to save the data to the database
     var saveToDatabase = function(data) {

        var menuname = $("#nestable-output").data('menuname');

       $("#loaderImageIcon").show();
       $.ajax({
         url: 'inc/update-menu.php',
         method: 'POST',
         data: {
           option_value: data,
           menu_name:menuname,
         },
         success: function(response) {
           console.log(response);
		   $("#loaderImageIcon").hide();
           // Handle success response if needed
         },
         error: function(xhr, status, error) {
           console.log(xhr.responseText);
           // Handle error if needed
         }
       });
     };

    $('#nestable').nestable({
        group: 1
    }).on('change', updateOutput);

    updateOutput($('#nestable').data('output', $('#nestable-output')));

});
