'use strict';

$(function() {
  $('#validate').click(function() {
    $.ajax({
      url: '/pmta_steps/0',
      method: 'POST',
      data: {ip:$('#server-ip').val(), port: $('#server-port').val(), username: $('#server-username').val(), password: $('#server-password').val()},
      beforeSend: function() {
        $(".btn-loading").find("i").addClass("spinner-border spinner-border-sm align-middle");
        $('#server-msg').empty();
      },
      success: function(data) {
        $('#server-msg').html(data);
        $(".btn-loading").find("i").removeClass("spinner-border spinner-border-sm align-middle");
      }
    });
  });

   $(".server-operation").click(function (e) {
   $.ajax({
      url: '/server/'+$(this).data('value')+'/'+$(this).data('id'),
      method: 'GET',
      beforeSend: function() {
       $('#action').html('<i class="spinner-border spinner-border-sm align-middle"></i>');
      },
      success: function(data) {
       $('#action').html(data);
      }
    });
  });

});

function validateBounce(div) {
  var inputs = $('input[name="'+div+'[]"]')
  .map(function(){return $(this).val();}).get();
  var selects = $('select[name="'+div+'[]"]')
  .map(function(){return $(this).val();}).get();
  $.ajax({
    url: '/pmta_steps/10',
    method: 'POST',
    data: {inputs:inputs, selects:selects},
    beforeSend: function() {
      $('#msg-'+div).html('<i class=\"spinner-border spinner-border-sm align-middle\"></i>');
    },
    success: function(data) {
      $('#msg-'+div).html(data);
    }
  });
}

function downloadPmtaSettings(pmta_id) 
{
  $.ajax({
      url: '/pmta_steps/16/'+pmta_id,
      method: 'POST',
      beforeSend: function() {
        $('#action').html('<i class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></i>');
      },
      success: function(data) {
        console.log(data.msg);
        if(data.msg == 'success') {
          $('#action').html('<a href="'+data.file+'"><button type="button" class="btn btn-success">Download</button></a>');
        }
      }
    });
}

function pmtaSteps(step, div_id)
{
  $.ajax({
    url: '/pmta_steps/'+step,
    method: 'POST',
    data: $('#frm-pmta').serialize(),
    beforeSend: function() {
      if(step != 6) {
        $('#'+div_id).html('<i class=\"spinner-border spinner-border-lg align-middle\"></i>');
      }
    },
    success: function(data) {
      if(step == 7) {
        if(data == 'success') {
          document.location.href = '/pmta';
        } else {
          $('#finish-data').html(data);
        }
      } else {
        $('#'+div_id).html(data);
      }
    }
  });
}

function onCancel(){ $('#smartwizard').smartWizard("reset"); }

function submitFrom(operation, msg){ 
  swal({
    title: '',
    text: msg,
    type: "warning",
    showCancelButton: true,
    cancelButtonClass: "btn-danger",
    confirmButtonClass: "btn-success",
    confirmButtonText: "Yes",
    closeOnConfirm: true
  }, function(){
    $("#operation").val(operation);
    $('#frm-schedule').submit(); 
  });
}


function provideContent(idx, stepDirection, stepPosition, selStep, callback) {
  callback();
}


function ucfirst(str) {
  if (!str) return ''; // Handle empty strings
  return str.charAt(0).toUpperCase() + str.slice(1);
}


$(function() {

// Initialize Choices.js for #sending_server_ids and #list_ids only when the step is shown
$("#smartwizard").on("showStep", function(e, anchorObject, stepIndex, stepDirection, stepPosition) {

  $('#smartwizard .nav-link').addClass('text-primary');
  $('#smartwizard .sw-toolbar-elm .btn').addClass('btn-primary');

  // Enable/disable navigation buttons based on step position
  $("#prev-btn").removeClass('disabled').prop('disabled', false);
  $("#next-btn").removeClass('disabled').prop('disabled', false);
  if (stepPosition === 'first') {
    $("#prev-btn").addClass('disabled').prop('disabled', true);
  } else if (stepPosition === 'last') {
    $("#next-btn").addClass('disabled').prop('disabled', true);
  }


  // Update the current step info in the UI
  let stepInfo = $('#smartwizard').smartWizard("getStepInfo");
  $("#sw-current-step").text(stepInfo.currentStep + 1);
  $("#sw-total-step").text(stepInfo.totalSteps);
});

// Smart Wizard
$('#smartwizard').smartWizard({
    selected: 0,
    theme: 'square',
    transition: {
        animation: 'fade'
    },
    toolbar: {
        showNextButton: true,
        showPreviousButton: true,
        position: 'top',
        extraHtml: ``
    },
    keyboardSettings: {
        keyNavigation: false,
    },
    anchor: {
        enableNavigation: true,
        enableNavigationAlways: false,
        enableDoneState: true,
        markPreviousStepsAsDone: true,
        unDoneOnBackNavigation: false,
        enableDoneStateNavigation: true
    },
    disabledSteps: [],
    errorSteps: [],
    hiddenSteps: [],
    getContent: provideContent
});


    $("#state_selector").on("change", function() {
      $('#smartwizard').smartWizard("setState", [$('#step_to_style').val()], $(this).val(), !$('#is_reset').prop("checked"));
      return true;
    });

    $("#style_selector").on("change", function() {
      $('#smartwizard').smartWizard("setStyle", [$('#step_to_style').val()], $(this).val(), !$('#is_reset').prop("checked"));
      return true;
    });

  });

$("#smartwizard").on("leaveStep", function (e, anchorObject, currentStepIndex, nextStepIndex) {
    $('.sw-btn-next').text('Next');

    // Step-specific logic
    $('.sw-btn-next').show();
    if (nextStepIndex === 3) {
        pmtaSteps(3, 'mapping-ips-domains');
    } else if (nextStepIndex === 4) {
        pmtaSteps(4, 'bounces-data');
    } else if (nextStepIndex === 5) {
        pmtaSteps(5, 'authentication-data');
    } else if (nextStepIndex === 6) {
        $('.sw-btn-next').text('Finish');
        $('.sw-btn-next').addClass('btn-success');
        pmtaSteps(6, 'review-data');
    } else if (nextStepIndex === 7) {
        $('.sw-btn-next').hide();
        pmtaSteps(7, 'finish-data');
    }

    // Validate only when going forward
    if (nextStepIndex > currentStepIndex) {
        const currentStep = $('#step-' + (currentStepIndex + 1)); // OFFSET HERE 🔥
        let isValid = true;

        currentStep.find("input, select, textarea").each(function () {
            if (!this.checkValidity()) {
                $(this).addClass("is-invalid");
                this.reportValidity();
                isValid = false;
                return false; // exit loop
            } else {
                $(this).removeClass("is-invalid");
            }
        });

        return isValid;
    }

    return true; // allow backward navigation
});
