'use strict';
flatpickr("#send_datetime", {
    enableTime: true,
    time_24hr: false, // Use 12-hour format with AM/PM
    minDate: "today",
    dateFormat: "Y-m-d h:i K", // User-friendly format
    defaultDate: document.querySelector("#send_datetime").value, // Pre-filled value from server
    disableMobile: true,
    onReady: function (selectedDates, dateStr, instance) {
        // Trigger the same behavior as onChange for the default value
        handleDateChange(instance.selectedDates[0], dateStr);
    },
    onChange: function (selectedDates, dateStr, instance) {
        if (selectedDates.length > 0) {
            handleDateChange(selectedDates[0], dateStr);
        }
    },
});

$('#copy-as-text').click(function() {
      var content_html = CKEDITOR.instances['content_html'].getSnapshot();
      var content = content_html.replace(/<br\s*\/?>|<\/p>|<\/div>|<\/li>/gi, "\n");
      content = content.replace(/&nbsp;/g, ' ');
      // remove html tags
      var regex = /(<([^>]+)>)/ig
      var content = $.trim(content.replace(regex, ""));
      $('#content_text').val(content);
  });

$("#send-option").change(function() {
  $("#send-datetime").slideToggle('slow');
});

$('.repeater-attachments').repeater({
  show: function () {
    $(this).slideDown();
  },
  hide: function (deleteElement) {
    swal({
    title: "",
    text: $('#attachment_delete_msg').data('value'),
    type: "warning",
    showCancelButton: true,
    cancelButtonClass: "btn-primary",
    confirmButtonClass: "btn-danger",
    confirmButtonText: "Yes",
    closeOnConfirm: false
  }, function (isConfirm) {
    if(isConfirm) {
      $(this).slideUp(deleteElement);
      swal.close(); // **Manually close the alert**
    }
  });

  },
  isFirstItemUndeletable: true
});

function aiAnalysisCampaign() {
    $(this).find("i").addClass("spinner-border spinner-border-sm align-middle");
    var email_subject = $('#email_subject').val();
    var email_content = $('#sending_content').val();
    var data = `Could you please imporve the email subjet and the content for the campaign?\n
      Email Subject: ${email_subject}\n
      Email Content: ${email_content}`;
    
    chatGPT('modal', '/chatGPT', data);
    setTimeout(function () {
        $(".btn-loading").find("i").removeClass("spinner-border spinner-border-sm align-middle");
    }, 5000);
  }


$(".delete-file").click(function () {
    var fileName = $(this).data("file"); // Get file name
    var scheduleId = $('#schedule_id').data('value'); // Get schedule ID
    var fileItem = $(this).closest(".file-item"); // Store reference to delete on success

    swal({
    title: "",
    text: $('#attachment_delete_msg').data('value'),
    type: "warning",
    showCancelButton: true,
    cancelButtonClass: "btn-primary",
    confirmButtonClass: "btn-danger",
    confirmButtonText: "Yes",
    closeOnConfirm: false
  }, function (isConfirm) {
    if(isConfirm) {
      $.ajax({
            url: "/delete-attachment/" + scheduleId, 
            type: "DELETE",
            data: {
                file: fileName,
                user_id: $('#user_id').data('value')
            },
            success: function (response) {
                if (response.success) {
                    toastr.success(response.message);
                    fileItem.remove(); // Remove file item from DOM
                    swal.close(); // **Manually close the alert**
                } else {
                    toastr.error(response.message);
                }
            },
            error: function () {
                toastr.error("Failed to delete file.");
            }
        });
    }
  });
});

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);
}

  // Helper function to get selected labels
function getSelectedLabels(choicesInstance) {
  if (!choicesInstance) return [];
  const selectedValues = choicesInstance.getValue(true); // ["8", "15", "17"]
  const allOptions = choicesInstance.passedElement.element.options;
  return selectedValues.map(value => {
    const option = Array.from(allOptions).find(option => option.value === value);
    return option ? option.text : ''; // Return the text if found, otherwise empty string
  });
}


$(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);
  }

  // On the final step, capture input values and display them in the review section
  if (stepIndex === 3) {
    const dataFromDetail = {
      sending_server: `As defined for sending server`,
      list: `As defined for list`,
      custom: `Custom`,
    };
    const name = $("#name").val();
    const selectedRadioValue = $("input[name='from_detail']:checked").val();
    const open_tracking = $('#open_tracking').is(':checked') ? 'Yes' : 'No';;
    const click_tracking = $('#click_tracking').is(':checked') ? 'Yes' : 'No';;
    const email_subject = $("#email_subject").val();
    const sending_content = $("#sending_content").val();
    const send = $("#send").val();
    const send_datetime = $("#send_datetime").val();
    const speed = $("#speed").val();
    const duration = $("#duration").val();
    const limit = $("#limit").val();
    const from_name = $("#from_name").val();
    const from_email = $("#from_email_part1").val()+'@'+$("#from_email_part2").val();
    const reply_email = $("#reply_email").val();


    const review_name = $('#review_name').data('value');
    const review_from_detail = $('#review_from_detail').data('value');
    const review_from_name = $('#review_from_name').data('value');
    const review_from_email = $('#review_from_email').data('value');
    const review_reply_email = $('#review_reply_email').data('value');
    const review_subject = $('#review_subject').data('value');
    const review_sending_content = $('#review_sending_content').data('value');
    const review_open_tracking = $('#review_open_tracking').data('value');
    const review_click_tracking = $('#review_click_tracking').data('value');
    const review_send = $('#review_send').data('value');
    const review_send_at = $('#review_send_at').data('value');
    const review_sending_speed = $('#review_sending_speed').data('value');
    const review_limit = $('#review_limit').data('value');
    const review_maximum = $('#review_maximum').data('value');


    let custom_data;
    
    let reviewHtml = `
      <p><strong>${review_name}:</strong> ${name || "---"}</p>
      <p><strong>${review_from_detail}:</strong> ${dataFromDetail[selectedRadioValue] || "---"}</p>`; // Initial definition

      if($("input[name='from_detail']:checked").val() == 'custom') {
       reviewHtml += `
            <p><strong>${review_from_name}:</strong> ${from_name || "---"}</p>
            <p><strong>${review_from_email}:</strong> ${from_email|| "---"}</p>
            <p><strong>${review_reply_email}:</strong> ${reply_email || "---"}</p>
          `;
      }

      reviewHtml += `
      <p><strong>${review_subject}:</strong> ${email_subject || "---"}</p>
      <p><strong>${review_sending_content}:</strong> ${ucfirst(sending_content)  || "---"}</p>
      <p><strong>${review_open_tracking}:</strong> ${ucfirst(open_tracking) || "---"}</p>
      <p><strong>${review_click_tracking}:</strong> ${ucfirst(click_tracking) || "---"}</p>
      <p><strong>${review_send}:</strong> ${ucfirst(send) || "---"}</p>
      <p><strong>${review_send_at}:</strong> ${send_datetime || "---"}</p>
      <p><strong>${review_sending_speed}:</strong> ${speed == "unlimited" ? ucfirst(review_maximum) : ucfirst(speed)}</p>
      <p><strong>${review_limit}:</strong> ${speed == "unlimited" ? "---" : (limit+"/"+ucfirst(duration))}</p>
    `;
    $("#review-section").html(reviewHtml);

    // Display sending server choices
    if (multipleSendingServers) {
      const selectedLabels = getSelectedLabels(multipleSendingServers);
      $("#review-sending-servers").text(selectedLabels.join(", "));
    }

    // Display list choices
    if (multipleLists) {
      const selectedLabels = getSelectedLabels(multipleLists);
      $("#review-lists").text(selectedLabels.join(", "));
    }
  }

  // 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: `<span class="ps-1"></span>
                    <button type="button" name="scheduled" class="btn btn-success btn-submit d-none" onclick="submitFrom('scheduled', 'Are you sure to schedule?')">Schedule</button>
                    <span class="ps-1"></span>
                    <button type="button" name="save" class="btn btn-secondary btn-submit d-none" onclick="submitFrom('save', 'Are you sure to save as draft?')">Save</button>`
    },
    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) {
// Display submit button on the final step
  if (nextStepIndex === 3) {
    $(".btn-submit").removeClass('d-none');
  } else {
    $(".btn-submit").addClass('d-none');
  }

    if (currentStepIndex === 0) { // Validate only on Step 0
        let form = document.getElementById("frm-schedule");

        const listDropdown = document.getElementById("list_ids");
        const choicesContainerList = listDropdown.closest('.choices'); // Get Choices.js container
        const sendingServerDropdown = document.getElementById("sending_server_ids");
        const choicesContainerSendingServer = sendingServerDropdown.closest('.choices'); // Get Choices.js container

        // Force form validation
        if (form.checkValidity() === false) {
            e.preventDefault(); // Prevent SmartWizard navigation
            form.classList.add("was-validated"); // Add Bootstrap validation styles

            if (!listDropdown.checkValidity()) {
                choicesContainerList.classList.add("is-invalid"); // Add red border
            } else {
                choicesContainerList.classList.remove("is-invalid"); // Remove red border
                choicesContainerList.classList.add("is-valid"); // Optionally add green border
            }

          
            if (!sendingServerDropdown.checkValidity()) {
                choicesContainerSendingServer.classList.add("is-invalid"); // Add red border
            } else {
                choicesContainerSendingServer.classList.remove("is-invalid"); // Remove red border
                choicesContainerSendingServer.classList.add("is-valid"); // Optionally add green border
            }

            return false; // Stop navigation
        } else {
          choicesContainerList.classList.remove("is-invalid"); // Remove red border
          choicesContainerSendingServer.classList.remove("is-invalid"); // Remove red border
        }
    }
    return true; // Allow navigation if valid
});


let multipleDays;
    (function () {
      "use strict";
      multipleDays = new Choices(document.getElementById('days'), {
        searchEnabled: true,
        removeItemButton: true,
        placeholder: true, // Optional: Show placeholder text
        shouldSort: false, // Prevents automatic sorting
      });
    })();

    function updateEndTime() {
        const startTime = parseInt(document.getElementById('startTime').value);
        const endTimeSelect = document.getElementById('endTime');

        // Clear existing options
        for (let i = endTimeSelect.options.length - 1; i >= 0; i--) {
            endTimeSelect.remove(i);
        }

        // Add new options that are greater than the selected start time
        for (let i = startTime + 1; i <= 24; i++) {
            const option = document.createElement("option");
            option.value = i;
            option.text = `${i <= 12 ? i : i - 12} ${i < 12 || i == 24 ? 'AM' : 'PM'}`;
            endTimeSelect.add(option);
        }
    }

    $("#delivery_timing").change(function() {
      $("#delivery_timing_options").slideToggle('slow');
    });