$('#save-submit').on('click', function(event) {
  event.preventDefault();
  const formData = new FormData();
  let broadcastTitleInputMedia = document.querySelector(".broadcastTitleInputMedia");
  console.log(broadcastTitleInputMedia)
  if(broadcastTitleInputMedia.type == 'text'){
    let text_content = broadcastTitleInputMedia?.value;
    if(text_content){
      formData.append('text_content',text_content);
    }
  }else{
    const file = broadcastTitleInputMedia?.files[0];
    // Step 1: Append image file (if selected)
    if (file) {
      formData.append('image', file);
    }
  }
  let broadcastTitleInput = document.querySelector(".broadcastTitleInput")?.value;
  formData.append('broadcastTitleInput', broadcastTitleInput);

  // Step 2: Collect other form values
  let templateName = document.getElementById("template-name")?.value || "";
  let category = document.getElementById("category")?.value || "";
  let language = document.getElementById("language")?.value || "";

  let standard = document.querySelector(".option-button.selected");
  let templateStandard = standard
    ? standard.getAttribute("data-marketing-template")
    : "";

  const broadcastTitleRadioInput = document.querySelector(
    "input[name='broadcastTitleRadio']:checked"
  );
  const broadcastTitleRadio = broadcastTitleRadioInput?.value || "";

  const previewMessageFooterInput =
    document.getElementById("previewMessageFooterInput")?.value || "";

  let richTextValue = quill?.root?.innerHTML || "";

  // Collect structured buttons
  let structuredButtons = [];
  let copyButtonItems = [];
  // code for copy buttons 
  document.querySelectorAll(".copy-button-container-item").forEach(item => {
    const offerTextInput = item.querySelector(".copyButtonTextInput");
    const couponCodeInput = item.querySelector("input[placeholder='Enter coupon code to copy']");
  
    const offerText = offerTextInput?.value || "";
    const couponCode = couponCodeInput?.value || "";
  
    if (offerText || couponCode) {
      copyButtonItems.push({
        offerText,
        couponCode
      });
    }
  });



  const addButtonChildren = document.querySelectorAll("#add-button-container > div");

  addButtonChildren.forEach((btnEl) => {
    const typeSelect = btnEl.querySelector(".buttons-select-options");
    const buttonTextInput = btnEl.querySelector(".addWebsiteButtonTextInput");

    if (typeSelect.value == 'phone') {
      const isPhone = btnEl.querySelector(".addWebsiteButtonPhoneInput");
      structuredButtons.push({
        "field-type": "call-phone",
        "text": buttonTextInput?.value || "",
        "number": isPhone?.value || ""
      });
    } else {
      const isUrl = btnEl.querySelector(".addWebsiteButtonURLInput");
      const linkTypeSelect = btnEl.querySelectorAll(".buttons-select-options")[1];
      const linkType = linkTypeSelect?.value;
      structuredButtons.push({
        "field-type": "visit-website",
        "link-type": linkType,
        "link": isUrl?.value || "",
        "text": buttonTextInput?.value || ""
      });
    }
  });

  const quickReplyValues = Array.from(
    document.querySelectorAll('.quick-reply-button-container-item input[type="text"]')
).map(input => input.value);

const commaSeparated = quickReplyValues.join(','); // or ', ' for spacing

  // Step 3: Append all values to FormData
  formData.append("templateName", templateName);
  formData.append("templateCategory", category);
  formData.append("templateLanguage", language);
  formData.append("templateType", templateStandard);
  formData.append("templateMediatype", broadcastTitleRadio);
  // formData.append("broadcastTitleInput", broadcastTitleInput);
  formData.append("templateBody", richTextValue);
  formData.append("previewMessageFooterInput", previewMessageFooterInput);
  formData.append("structuredButtons", JSON.stringify(structuredButtons)); // convert array to JSON string
  formData.append("copyButtonItems", JSON.stringify(copyButtonItems));
  formData.append("commaSeperatedvalue", commaSeparated); 
  for (let pair of formData.entries()) {
    console.log(`${pair[0]}:`, pair[1]);
  }
  
  $.ajax({
    url: 'https://app.watify.io/server/insert_template', // 🔁 Replace with your real endpoint
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
      alert(response['message']);
    },
    error: function(xhr, status, error) {
      console.error("❌", error);
    }
  });
});
