meta description preview

 avatar
user_8649498
plain_text
a year ago
42 kB
3
Indexable
Never
jQuery(document).ready(function () {
  // Access the API key and link in product-description-script.js
  if (typeof my_plugin_api_key !== "undefined") {
    var apiKey = my_plugin_api_key;
  } else {
    console.log("The API key is not defined. Please check the API key in the settings page.");
  }

  if (typeof my_plugin_api_link !== "undefined") {
    var apiLink = my_plugin_api_link;
  } else {
    console.log("The API link is not defined. Please check the API link in the settings page.");
  }

  // Access the selected temperature and model from the settings page
  if (typeof my_plugin_selected_temperature !== "undefined") {
    var temperature = parseFloat(my_plugin_selected_temperature);
    console.log("The selected temperature is: " + temperature);
  } else {
    var temperature = 0.7; // Use the default temperature if not defined
    console.log("The selected temperature is not defined. Using the default value: " + temperature);
  }

  if (typeof my_plugin_selected_model !== "undefined") {
    var model = my_plugin_selected_model;
    console.log("The selected model is: " + model);
  } else {
    var model = "text-davinci-002"; // Use the default model if not defined
    console.log("The selected model is not defined. Using the default value: " + model);
  }

  if (typeof my_plugin_full_description_prompt !== "undefined" && my_plugin_full_description_prompt.trim() !== "") {
    var prompt = my_plugin_full_description_prompt;
    console.log("The selected prompt is: " + prompt);
  } else {
    var prompt = "Generate full meta description for: ";
    console.log("The selected prompt is not defined. Using the default value: " + prompt);
  }
  if (typeof my_plugin_short_description_prompt !== "undefined" && my_plugin_short_description_prompt.trim() !== "") {
    var shortPrompt = my_plugin_short_description_prompt;
    console.log("The selected short prompt is: " + shortPrompt);
  } else {
    var shortPrompt = "Generate short meta description for: ";
    console.log("The selected short prompt is not defined. Using the default value: " + shortPrompt);
  }

  // Add event listener to the "Generate Description" button
  jQuery(document)
    .off("click", "#chatgpt-generate-desc-btn")
    .on("click", "#chatgpt-generate-desc-btn", function (event) {
      if (typeof apiKey === "undefined" || typeof apiLink === "undefined") {
        event.preventDefault();
        alert("The API key or API link is not defined. Please check the settings page.");
        return;
      } else {
        event.preventDefault();
        var productNameElement = jQuery("#title");
        var productName = productNameElement.val();
        if (productName === null || productName.trim() === "") {
          alert("Please enter the product name first.");
          return;
        }

        if (confirm("Are you sure you want to update the product details?")) {
          // Set the cURL headers
          var headers = {
            "Content-Type": "application/json",
            Authorization: "Bearer " + apiKey,
          };
          // Code for handling .btn-size clicks
          jQuery(".btn-size").click(function () {
            var size = jQuery(this).text().trim();
            if (size) {
              jQuery(".btn-size").removeClass("active");
              jQuery(this).addClass("active");
              jQuery("#selected-size").text(size);
            }
          });

          // Retrieve the new input of the full description prompt
          var myPluginFullDescriptionPromptElement = jQuery("#my-plugin-full-description-prompt");
          var myPluginFullDescriptionPrompt = myPluginFullDescriptionPromptElement.val();
          var fullPrompt =
            myPluginFullDescriptionPrompt && myPluginFullDescriptionPrompt.trim() !== "" ? myPluginFullDescriptionPrompt.trim() : "Generate full meta description for: ";

          console.log("This is Full Prompt: " + fullPrompt);
          // Build the cURL request data for full description
          var requestData = {
            model: model,
            prompt: fullPrompt + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          requestData = JSON.stringify(requestData);

          // Send the cURL request for full description
          var fullDescRequest = new XMLHttpRequest();
          fullDescRequest.open("POST", apiLink, true);
          for (var header in headers) {
            fullDescRequest.setRequestHeader(header, headers[header]);
          }
          fullDescRequest.onreadystatechange = function () {
            if (fullDescRequest.readyState === 4 && fullDescRequest.status === 200) {
              var fullDesc = JSON.parse(fullDescRequest.responseText).choices[0].text.trim();
              console.log("This is Full Description: " + fullDesc);
              jQuery("#content").val(fullDesc); // Update the content field with the generated full description
            }
          };
          fullDescRequest.send(requestData);

          // Retrieve the new input of the short description prompt
          var myPluginShortDescriptionPromptElement = jQuery("#my-plugin-short-description-prompt");
          var myPluginShortDescriptionPrompt = myPluginShortDescriptionPromptElement.val();
          var shortPrompt =
            myPluginShortDescriptionPrompt && myPluginShortDescriptionPrompt.trim() !== "" ? myPluginShortDescriptionPrompt.trim() : "Generate short meta description for: ";

          console.log("This is Short Prompt: " + shortPrompt);
          // Build the cURL request data for short description
          var shortDescRequestData = {
            model: model,
            prompt: shortPrompt + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          shortDescRequestData = JSON.stringify(shortDescRequestData);

          // Send the cURL request for short description
          var shortDescRequest = new XMLHttpRequest();
          shortDescRequest.open("POST", apiLink, true);
          for (var header in headers) {
            shortDescRequest.setRequestHeader(header, headers[header]);
          }
          shortDescRequest.onreadystatechange = function () {
            if (shortDescRequest.readyState === 4 && shortDescRequest.status === 200) {
              var shortDesc = JSON.parse(shortDescRequest.responseText).choices[0].text.trim();
              console.log("This is the short Description for the product: " + shortDesc);
              jQuery("#excerpt").val(shortDesc); // Update the excerpt field with the generated short description
            }
          };
          shortDescRequest.send(shortDescRequestData);

          // Build the cURL request data for generating tags
          var tagRequestData = {
            model: model,
            prompt:
              "Can you provide tags for the mentioned product which has a higher focus keyphrase value, also separate each tag with a comma, and don't include '#' in the tags: " +
              productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          tagRequestData = JSON.stringify(tagRequestData);

          // Send the cURL request for generating tags
          var tagRequest = new XMLHttpRequest();
          tagRequest.open("POST", apiLink, true);
          for (var header in headers) {
            tagRequest.setRequestHeader(header, headers[header]);
          }
          tagRequest.onreadystatechange = function () {
            if (tagRequest.readyState === 4 && tagRequest.status === 200) {
              var tags = JSON.parse(tagRequest.responseText).choices[0].text;
              var newTags = tags.split(",").map((tag) => tag.trim());

              // Remove existing tags
              var numExistingTags = jQuery(".tagchecklist .ntdelbutton").length;
              for (var i = 0; i < numExistingTags; i++) {
                jQuery(".tagchecklist .ntdelbutton:first").trigger("click");
              }

              // Add new tags
              setTimeout(function () {
                newTags.forEach(function (tag) {
                  jQuery("#new-tag-product_tag").val(tag);
                  jQuery(".tagadd").trigger("click");
                });
              }, 0);
            }
          };
          tagRequest.send(tagRequestData);

          // Build the cURL request data for generating Meta Description
          var metaDescRequestData = {
            model: model,
            prompt: "Can you write a Meta Description for the product which is SEO friendly: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          metaDescRequestData = JSON.stringify(metaDescRequestData);

          // Send the cURL request for generating Meta Description
          var metaDescRequest = new XMLHttpRequest();
          metaDescRequest.open("POST", apiLink, true);
          for (var header in headers) {
            metaDescRequest.setRequestHeader(header, headers[header]);
          }
          metaDescRequest.onreadystatechange = function () {
            if (metaDescRequest.readyState === 4 && metaDescRequest.status === 200) {
              var metaDesc = JSON.parse(metaDescRequest.responseText).choices[0].text;
              // Remove newline characters, leading/trailing spaces, and unnecessary whitespace
              metaDesc = metaDesc
                .replace(/[\r\n]+/g, " ")
                .trim()
                .replace(/\s+/g, " ");

              // Simulate a click event on the "Insert variable" button
              var insertVariableButton = document.querySelector(".yst-replacevar__button-insert");
              if (insertVariableButton !== null) {
                insertVariableButton.click();
              }

              // Use a delay to ensure the button click is processed
              setTimeout(function () {
                // Update the Meta Description field with the generated description
                var metaDescField = document.querySelector("#yoast-google-preview-description-metabox");

                // Check if the Meta Description field is empty
                if (metaDescField !== null) {
                  if (metaDescField.textContent.trim() !== "") {
                    // Clear the existing Meta Description
                    metaDescField.textContent = "";
                  }

                  metaDescField.textContent = metaDesc;
                }

                // Update the Meta Description preview field
                var metaDescPreviewField = document.querySelector(".sc-jhrdCu.hQecmn");
                if (metaDescPreviewField !== null) {
                  metaDescPreviewField.textContent = metaDesc;
                }

                console.log("This is the Meta Description for SEO Plugin: " + metaDesc); // Log the Meta Description to the console
              }, 500);
            }
          };
          metaDescRequest.send(metaDescRequestData);

          // Build the cURL request data for generating Focus keyphrase
          var focusKeyphraseRequestData = {
            model: model,
            prompt: "Can you suggest a focus keyphrase for the product: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          focusKeyphraseRequestData = JSON.stringify(focusKeyphraseRequestData);

          // Send the cURL request for generating Focus keyphrase
          var focusKeyphraseRequest = new XMLHttpRequest();
          focusKeyphraseRequest.open("POST", apiLink, true);
          for (var header in headers) {
            focusKeyphraseRequest.setRequestHeader(header, headers[header]);
          }
          focusKeyphraseRequest.onreadystatechange = function () {
            if (focusKeyphraseRequest.readyState === 4 && focusKeyphraseRequest.status === 200) {
              var focusKeyphrase = JSON.parse(focusKeyphraseRequest.responseText).choices[0].text;
              jQuery("#focus-keyword-input-metabox").val(focusKeyphrase); // Update the Focus keyphrase field with the generated keyphrase
              console.log("This is Focus KeyPhrase: " + focusKeyphrase);
            }
          };
          focusKeyphraseRequest.send(focusKeyphraseRequestData);

          // Build the cURL request data for generating Slug
          var slugRequestData = {
            model: model,
            prompt: "Can you suggest a Yoast SEO slug for the product: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          slugRequestData = JSON.stringify(slugRequestData);

          // Send the cURL request for generating Slug
          var slugRequest = new XMLHttpRequest();
          slugRequest.open("POST", apiLink, true);
          for (var header in headers) {
            slugRequest.setRequestHeader(header, headers[header]);
          }
          slugRequest.onreadystatechange = function () {
            if (slugRequest.readyState === 4 && slugRequest.status === 200) {
              var slug = JSON.parse(slugRequest.responseText).choices[0].text;
              jQuery("#editable-post-name-full").val(slug); // Update the slug field with the generated slug
              console.log("This is Slug: " + slug);
            }
          };
          slugRequest.send(slugRequestData);
        }
      }
    });

  // Update the product name input field with the name entered in the window buttons
  jQuery(document)
    .off("click", "#chatgpt-enter-details-btn")
    .on("click", "#chatgpt-enter-details-btn", function (event) {
      if (typeof apiKey === "undefined" || typeof apiLink === "undefined") {
        event.preventDefault();
        alert("The API key or API link is not defined. Please check the settings page.");
        function dismissErrorMessage() {
          jQuery(this).parent().remove();
        }
        var errorMessageLink =
          '<div class="notice notice-error"><p>Please set up the API key or the API link in the <a href="admin.php?page=my-plugin-settings">Settings page</a>.</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';

        jQuery("#titlediv").before(errorMessageLink);
        jQuery(".notice-dismiss").on("click", dismissErrorMessage);
        return;
      } else {
        event.preventDefault();
        var productName = prompt("Enter product details for which content needs to be generated:");
        if (productName !== null && productName.trim() !== "") {
          jQuery("#title").val(productName);
          var productNameElement = jQuery("#title");
          if (productName.trim() !== "") {
            jQuery("#title").val(productName);
            jQuery("#title-prompt-text").hide();
          }

          if (productName === null || productName.trim() === "") {
            alert("Please enter the product name first.");
            return;
          }

          if (confirm("Are you sure you want to update the product details?")) {
            // Set the cURL headers
            var headers = {
              "Content-Type": "application/json",
              Authorization: "Bearer " + apiKey,
            };

            // Send the request to OpenAI to generate new title
            var titleRequestData = {
              model: "text-davinci-002",
              prompt: "Can you generate a new title for the given product description: " + productName,
              max_tokens: 100,
              temperature: 0.8,
            };
            titleRequestData = JSON.stringify(titleRequestData);

            // Send the cURL request for generating new title
            var titleRequest = new XMLHttpRequest();
            titleRequest.open("POST", apiLink, true);
            for (var header in headers) {
              titleRequest.setRequestHeader(header, headers[header]);
            }
            titleRequest.onreadystatechange = function () {
              if (titleRequest.readyState === 4 && titleRequest.status === 200) {
                var generatedTitle = JSON.parse(titleRequest.responseText).choices[0].text;
                jQuery("#title").val(generatedTitle); // Update the title field with the generated title
                generateContentForProduct(productName, generatedTitle); // Call the function to generate the remaining content
              }
            };
            titleRequest.send(titleRequestData);
          }
        }
      }
    });

  // Function to generate content based on product details
  function generateContentForProduct(productName) {
    // Set the cURL headers
    var headers = {
      "Content-Type": "application/json",
      Authorization: "Bearer " + apiKey,
    };

    // Retrieve the new input of the full description prompt
    var myPluginFullDescriptionPromptElement = jQuery("#my-plugin-full-description-prompt");
    var myPluginFullDescriptionPrompt = myPluginFullDescriptionPromptElement.val();
    var fullPrompt = myPluginFullDescriptionPrompt && myPluginFullDescriptionPrompt.trim() !== "" ? myPluginFullDescriptionPrompt.trim() : "Generate full meta description for: ";

    // Build the cURL request data for full description
    var requestData = {
      model: model,
      prompt: fullPrompt + productName,
      max_tokens: 1000,
      temperature: temperature,
    };
    requestData = JSON.stringify(requestData);

    // Send the cURL request for full description
    var fullDescRequest = new XMLHttpRequest();
    fullDescRequest.open("POST", apiLink, true);
    for (var header in headers) {
      fullDescRequest.setRequestHeader(header, headers[header]);
    }
    fullDescRequest.onreadystatechange = function () {
      if (fullDescRequest.readyState === 4 && fullDescRequest.status === 200) {
        var fullDesc = JSON.parse(fullDescRequest.responseText).choices[0].text.trim();
        jQuery("#content").val(fullDesc); // Update the content field with the generated full description
      }
    };
    fullDescRequest.send(requestData);

    // Retrieve the new input of the short description prompt
    var myPluginShortDescriptionPromptElement = jQuery("#my-plugin-short-description-prompt");
    var myPluginShortDescriptionPrompt = myPluginShortDescriptionPromptElement.val();
    var shortPrompt =
      myPluginShortDescriptionPrompt && myPluginShortDescriptionPrompt.trim() !== "" ? myPluginShortDescriptionPrompt.trim() : "Generate short meta description for: ";

    // Build the cURL request data for short description
    var shortDescRequestData = {
      model: model,
      prompt: shortPrompt + productName,
      max_tokens: 1000,
      temperature: temperature,
    };
    shortDescRequestData = JSON.stringify(shortDescRequestData);

    // Send the cURL request for short description
    var shortDescRequest = new XMLHttpRequest();
    shortDescRequest.open("POST", apiLink, true);
    for (var header in headers) {
      shortDescRequest.setRequestHeader(header, headers[header]);
    }
    shortDescRequest.onreadystatechange = function () {
      if (shortDescRequest.readyState === 4 && shortDescRequest.status === 200) {
        var shortDesc = JSON.parse(shortDescRequest.responseText).choices[0].text.trim();
        jQuery("#excerpt").val(shortDesc); // Update the excerpt field with the generated short description
      }
    };
    shortDescRequest.send(shortDescRequestData);

    // Build the cURL request data for generating tags
    var tagRequestData = {
      model: model,
      prompt:
        "Can you provide tags for the mentioned product which has a higher focus keyphrase value, also separate each tag with a comma, and don't include '#' in the tags: " +
        productName,
      max_tokens: 1000,
      temperature: temperature,
    };
    tagRequestData = JSON.stringify(tagRequestData);

    // Send the cURL request for generating tags
    var tagRequest = new XMLHttpRequest();
    tagRequest.open("POST", apiLink, true);
    for (var header in headers) {
      tagRequest.setRequestHeader(header, headers[header]);
    }
    tagRequest.onreadystatechange = function () {
      if (tagRequest.readyState === 4 && tagRequest.status === 200) {
        var tags = JSON.parse(tagRequest.responseText).choices[0].text;
        var newTags = tags.split(",").map((tag) => tag.trim());

        // Remove existing tags
        var numExistingTags = jQuery(".tagchecklist .ntdelbutton").length;
        for (var i = 0; i < numExistingTags; i++) {
          jQuery(".tagchecklist .ntdelbutton:first").trigger("click");
        }

        // Add new tags
        setTimeout(function () {
          newTags.forEach(function (tag) {
            jQuery("#new-tag-product_tag").val(tag);
            jQuery(".tagadd").trigger("click");
          });
        }, 0);
      }
    };
    tagRequest.send(tagRequestData);

    // Build the cURL request data for generating Focus keyphrase
    var focusKeyphraseRequestData = {
      model: model,
      prompt: "Can you suggest a focus keyphrase for the product: " + productName,
      max_tokens: 1000,
      temperature: temperature,
    };
    focusKeyphraseRequestData = JSON.stringify(focusKeyphraseRequestData);

    // Send the cURL request for generating Focus keyphrase
    var focusKeyphraseRequest = new XMLHttpRequest();
    focusKeyphraseRequest.open("POST", apiLink, true);
    for (var header in headers) {
      focusKeyphraseRequest.setRequestHeader(header, headers[header]);
    }
    focusKeyphraseRequest.onreadystatechange = function () {
      if (focusKeyphraseRequest.readyState === 4 && focusKeyphraseRequest.status === 200) {
        var focusKeyphrase = JSON.parse(focusKeyphraseRequest.responseText).choices[0].text;
        jQuery("#focus-keyword-input-metabox").val(focusKeyphrase); // Update the Focus keyphrase field with the generated keyphrase
        console.log(focusKeyphrase);
      }
    };
    focusKeyphraseRequest.send(focusKeyphraseRequestData);

    // Build the cURL request data for generating Slug
    var slugRequestData = {
      model: model,
      prompt: "Can you suggest a Yoast SEO slug for the product: " + productName,
      max_tokens: 1000,
      temperature: temperature,
    };
    slugRequestData = JSON.stringify(slugRequestData);

    // Send the cURL request for generating Yoast SEO slug
    var slugRequest = new XMLHttpRequest();
    slugRequest.open("POST", apiLink, true);
    for (var header in headers) {
      slugRequest.setRequestHeader(header, headers[header]);
    }
    slugRequest.onreadystatechange = function () {
      if (slugRequest.readyState === 4) {
        if (slugRequest.status === 200) {
          var response = JSON.parse(slugRequest.responseText);
          var choices = response.choices;
          if (choices.length > 0) {
            var slug = choices[0].text.trim();
            jQuery("#yoast-google-preview-slug-metabox").val(slug); // Update the Yoast SEO slug field with the generated slug
            console.log("This is the Slug for SEO Plugin: " + slug); // Log the slug to the console
          }
        }
      }
    };
    slugRequest.send(slugRequestData);

    // Build the cURL request data for generating Meta Description
    var metaDescRequestData = {
      model: model,
      prompt: "Can you write a Meta Description for the product which is SEO friendly with words between 120 to 150 : " + productName,
      max_tokens: 1000,
      temperature: temperature,
    };
    metaDescRequestData = JSON.stringify(metaDescRequestData);

    // Send the cURL request for generating Meta Description
    var metaDescRequest = new XMLHttpRequest();
    metaDescRequest.open("POST", apiLink, true);
    for (var header in headers) {
      metaDescRequest.setRequestHeader(header, headers[header]);
    }
    metaDescRequest.onreadystatechange = function () {
      if (metaDescRequest.readyState === 4 && metaDescRequest.status === 200) {
        var metaDesc = JSON.parse(metaDescRequest.responseText).choices[0].text;

        // Simulate a click event on the "Insert variable" button
        var insertVariableButton = document.querySelector(".yst-replacevar__button-insert");
        insertVariableButton.click();

        // Use a delay to ensure the button click is processed
        setTimeout(function () {
          // Update the Meta Description field with the generated description
          var metaDescField = document.querySelector("#yoast-google-preview-description-metabox");
          metaDescField.textContent = metaDesc;

          // Update the Meta Description preview field
          var metaDescPreviewField = document.querySelector(".sc-jhrdCu.hQecmn");
          metaDescPreviewField.textContent = metaDesc;

          console.log("This is the Meta Description for SEO Plugin: " + metaDesc); // Log the Meta Description to the console
        }, 500);
      }
    };
    metaDescRequest.send(metaDescRequestData);
  }
  // Add event listener to the "Custom Button 3"
  jQuery(document)
    .off("click", "#custom-button-3")
    .on("click", "#custom-button-3", function (event) {
      if (typeof apiKey === "undefined" || typeof apiLink === "undefined") {
        event.preventDefault();
        alert("The API key or API link is not defined. Please check the settings page.");
        function dismissErrorMessage() {
          jQuery(this).parent().remove();
        }
        var errorMessageLink =
          '<div class="notice notice-error"><p>Please set up the API key or the API link in the plugin settings.</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';
        jQuery("#titlediv").before(errorMessageLink);
        jQuery(".notice-dismiss").on("click", dismissErrorMessage);
        return;
      } else {
        event.preventDefault();
        var productNameElement = jQuery(".editor-post-title__input");
        var productName = productNameElement.text().trim();
        if (productName === "") {
          alert("Please enter the product name first.");
          return;
        }

        if (confirm("Are you sure you want to generate post details?")) {
          // Set the cURL headers
          var headers = {
            "Content-Type": "application/json",
            Authorization: "Bearer " + apiKey,
          };

          // Build the cURL request data for post details generation
          var requestData = {
            model: model,
            prompt: "Can you provide in-depth information for the following title: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          requestData = JSON.stringify(requestData);

          // Send the cURL request for post details generation
          var postDetailsRequest = new XMLHttpRequest();
          postDetailsRequest.open("POST", apiLink, true);
          for (var header in headers) {
            postDetailsRequest.setRequestHeader(header, headers[header]);
          }
          postDetailsRequest.onreadystatechange = function () {
            if (postDetailsRequest.readyState === 4 && postDetailsRequest.status === 200) {
              var postDetails = JSON.parse(postDetailsRequest.responseText).choices[0].text;
              console.log("Generated Post Details: " + postDetails);

              var targetField = jQuery(".is-root-container .block-editor-rich-text__editable.block-editor-block-list__block.wp-block.wp-block-paragraph.rich-text");

              // Set focus on the target field
              targetField.focus();

              // Use a delay to wait for the field to be ready
              setTimeout(function () {
                // Simulate a click event on the target field
                targetField.click();

                // Use another delay to ensure the field is clicked
                setTimeout(function () {
                  // Clear the existing content and update with the new post details
                  targetField.empty().html(postDetails);
                }, 500);
              }, 500);
            }
          };
          postDetailsRequest.send(requestData);

          // Build the cURL request data for generating Focus keyphrase
          var focusKeyphraseRequestData = {
            model: model,
            prompt: "Can you suggest a focus keyphrase for the product: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          focusKeyphraseRequestData = JSON.stringify(focusKeyphraseRequestData);

          // Send the cURL request for generating Focus keyphrase
          var focusKeyphraseRequest = new XMLHttpRequest();
          focusKeyphraseRequest.open("POST", apiLink, true);
          for (var header in headers) {
            focusKeyphraseRequest.setRequestHeader(header, headers[header]);
          }
          focusKeyphraseRequest.onreadystatechange = function () {
            if (focusKeyphraseRequest.readyState === 4 && focusKeyphraseRequest.status === 200) {
              var focusKeyphrase = JSON.parse(focusKeyphraseRequest.responseText).choices[0].text;
              jQuery("#focus-keyword-input-metabox").val(focusKeyphrase); // Update the Focus keyphrase field with the generated keyphrase
              console.log("This is Focus KeyPhrase: " + focusKeyphrase);
            }
          };
          focusKeyphraseRequest.send(focusKeyphraseRequestData);

          // Build the cURL request data for generating Slug
          var slugRequestData = {
            model: model,
            prompt: "Can you suggest a Yoast SEO slug for the product: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          slugRequestData = JSON.stringify(slugRequestData);

          // Send the cURL request for generating Yoast SEO slug
          var slugRequest = new XMLHttpRequest();
          slugRequest.open("POST", apiLink, true);
          for (var header in headers) {
            slugRequest.setRequestHeader(header, headers[header]);
          }
          slugRequest.onreadystatechange = function () {
            if (slugRequest.readyState === 4) {
              if (slugRequest.status === 200) {
                var response = JSON.parse(slugRequest.responseText);
                var choices = response.choices;
                if (choices.length > 0) {
                  var slug = choices[0].text.trim();
                  jQuery("#yoast-google-preview-slug-metabox").val(slug); // Update the Yoast SEO slug field with the generated slug
                  console.log("This is the Slug for SEO Plugin: " + slug); // Log the slug to the console
                }
              }
            }
          };
          slugRequest.send(slugRequestData);
          // Build the cURL request data for generating Meta Description
          var metaDescRequestData = {
            model: model,
            prompt: "Can you write a Meta Description for the product which is SEO friendly: " + productName,
            max_tokens: 1000,
            temperature: temperature,
          };
          metaDescRequestData = JSON.stringify(metaDescRequestData);

          // Send the cURL request for generating Meta Description
          var metaDescRequest = new XMLHttpRequest();
          metaDescRequest.open("POST", apiLink, true);
          for (var header in headers) {
            metaDescRequest.setRequestHeader(header, headers[header]);
          }
          metaDescRequest.onreadystatechange = function () {
            if (metaDescRequest.readyState === 4 && metaDescRequest.status === 200) {
              var metaDesc = JSON.parse(metaDescRequest.responseText).choices[0].text;

              // Simulate a click event on the "Insert variable" button
              var insertVariableButton = document.querySelector(".yst-replacevar__button-insert");
              insertVariableButton.click();

              // Use a delay to ensure the button click is processed
              setTimeout(function () {
                // Update the Meta Description field with the generated description
                var metaDescField = document.querySelector("#yoast-google-preview-description-metabox");

                // Check if the Meta Description field is empty
                if (metaDescField !== null) {
                  if (metaDescField.textContent.trim() !== "") {
                    // Clear the existing Meta Description
                    metaDescField.textContent = "";
                  }

                  metaDescField.textContent = metaDesc;
              }

                // Update the Meta Description preview field
                var metaDescPreviewField = document.querySelector(".sc-jhrdCu.hQecmn");
                if (metaDescPreviewField !== null) {
                  var defaultText = "Default Text"; // Replace with the actual default text
                  if (metaDescPreviewField.textContent.trim() === defaultText) {
                    metaDescPreviewField.textContent = metaDesc;
                  }
                }

                console.log("This is the Meta Description for SEO Plugin: " + metaDesc); // Log the Meta Description to the console
              }, 500);
            }
          };
          metaDescRequest.send(metaDescRequestData);
        }
      }
    });
  // Add event listener to the "Custom Button 4"
  jQuery(document)
    .off("click", "#custom-button-4")
    .on("click", "#custom-button-4", function (event) {
      if (typeof apiKey === "undefined" || typeof apiLink === "undefined") {
        event.preventDefault();
        alert("The API key or API link is not defined. Please check the settings page.");
        function dismissErrorMessage() {
          jQuery(this).parent().remove();
        }
        var errorMessageLink =
          '<div class="notice notice-error"><p>Please set up the API key or the API link in the <a href="admin.php?page=my-plugin-settings">settings</a> page.</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>';

        jQuery("#titlediv").before(errorMessageLink);
        jQuery(".notice-dismiss").on("click", dismissErrorMessage);
        return;
      } else {
        event.preventDefault();
        var productName = prompt("Enter product details for which content needs to be generated:");
        if (productName !== null && productName.trim() !== "") {
          jQuery(".editor-post-title__input").val(productName);

          if (productName === null || productName.trim() === "") {
            alert("Please enter the product name first.");
            return;
          }

          if (confirm("Are you sure you want to update the product details?")) {
            // Set the cURL headers
            var headers = {
              "Content-Type": "application/json",
              Authorization: "Bearer " + apiKey,
            };

            // Send the request to OpenAI to generate a new title
            var titleRequestData = {
              model: model,
              prompt: "Can you generate a new title for the given product description: " + productName,
              max_tokens: 100,
              temperature: temperature,
            };
            titleRequestData = JSON.stringify(titleRequestData);

            // Send the cURL request for generating a new title
            var titleRequest = new XMLHttpRequest();
            titleRequest.open("POST", apiLink, true);
            for (var header in headers) {
              titleRequest.setRequestHeader(header, headers[header]);
            }
            titleRequest.onreadystatechange = function () {
              if (titleRequest.readyState === 4 && titleRequest.status === 200) {
                var generatedTitle = JSON.parse(titleRequest.responseText).choices[0].text;
                console.log("Generated Title: " + generatedTitle); // Log the generated title to the console
                jQuery(".editor-post-title__input").text(generatedTitle); // Update the title field with the generated title
                generatePostDetails(generatedTitle); // Call the function to generate the remaining content
              }
            };
            titleRequest.send(titleRequestData);
          }
        }
      }
    });

  function generatePostDetails(generatedTitle) {
    console.log("Generated Title: " + generatedTitle);

    // Set the cURL headers
    var headers = {
      "Content-Type": "application/json",
      Authorization: "Bearer " + apiKey,
    };

    // Build the cURL request data for post details generation
    var requestData = {
      model: "text-davinci-002",
      prompt: "Can you provide in-depth information for the following title: " + generatedTitle,
      max_tokens: 1000,
      temperature: 0.7,
    };
    requestData = JSON.stringify(requestData);

    // Send the cURL request for post details generation
    var postDetailsRequest = new XMLHttpRequest();
    postDetailsRequest.open("POST", apiLink, true);
    for (var header in headers) {
      postDetailsRequest.setRequestHeader(header, headers[header]);
    }
    postDetailsRequest.onreadystatechange = function () {
      if (postDetailsRequest.readyState === 4 && postDetailsRequest.status === 200) {
        var postDetails = JSON.parse(postDetailsRequest.responseText).choices[0].text;
        console.log("Generated Post Details: " + postDetails);

        var targetField = jQuery(".is-root-container .block-editor-rich-text__editable.block-editor-block-list__block.wp-block.wp-block-paragraph.rich-text");

        // Set focus on the target field
        targetField.focus();

        // Use a delay to wait for the field to be ready
        setTimeout(function () {
          // Simulate a click event on the target field
          targetField.click();

          // Use another delay to ensure the field is clicked
          setTimeout(function () {
            // Clear the existing content and update with the new post details
            targetField.empty().html(postDetails);
          }, 500);
        }, 500);
      }
    };
    postDetailsRequest.send(requestData);

    // Build the cURL request data for generating Focus keyphrase
    var focusKeyphraseRequestData = {
      model: model,
      prompt: "Can you suggest a focus keyphrase for the product: " + generatedTitle,
      max_tokens: 1000,
      temperature: temperature,
    };
    focusKeyphraseRequestData = JSON.stringify(focusKeyphraseRequestData);

    // Send the cURL request for generating Focus keyphrase
    var focusKeyphraseRequest = new XMLHttpRequest();
    focusKeyphraseRequest.open("POST", apiLink, true);
    for (var header in headers) {
      focusKeyphraseRequest.setRequestHeader(header, headers[header]);
    }
    focusKeyphraseRequest.onreadystatechange = function () {
      if (focusKeyphraseRequest.readyState === 4 && focusKeyphraseRequest.status === 200) {
        var focusKeyphrase = JSON.parse(focusKeyphraseRequest.responseText).choices[0].text;
        jQuery("#focus-keyword-input-metabox").val(focusKeyphrase); // Update the Focus keyphrase field with the generated keyphrase
        console.log("This is Focus KeyPhrase: " + focusKeyphrase);
      }
    };
    focusKeyphraseRequest.send(focusKeyphraseRequestData);

    // Build the cURL request data for generating Slug
    var slugRequestData = {
      model: model,
      prompt: "Can you suggest a Yoast SEO slug for the product: " + generatedTitle,
      max_tokens: 1000,
      temperature: temperature,
    };
    slugRequestData = JSON.stringify(slugRequestData);

    // Send the cURL request for generating Yoast SEO slug
    var slugRequest = new XMLHttpRequest();
    slugRequest.open("POST", apiLink, true);
    for (var header in headers) {
      slugRequest.setRequestHeader(header, headers[header]);
    }
    slugRequest.onreadystatechange = function () {
      if (slugRequest.readyState === 4) {
        if (slugRequest.status === 200) {
          var response = JSON.parse(slugRequest.responseText);
          var choices = response.choices;
          if (choices.length > 0) {
            var slug = choices[0].text.trim();
            jQuery("#yoast-google-preview-slug-metabox").val(slug); // Update the Yoast SEO slug field with the generated slug
            console.log("This is the Slug for SEO Plugin: " + slug); // Log the slug to the console
          }
        }
      }
    };
    slugRequest.send(slugRequestData);

    const model = "text-davinci-002";
    // Build the cURL request data for generating Meta Description  // Build the cURL request data for generating Meta Description
    var metaDescRequestData = {
      model: model,
      prompt: "Can you generate a Meta Description for the product which is SEO friendly with words between 120 to 150 : " + generatedTitle,
      max_tokens: 1000,
      temperature: temperature,
    };
    metaDescRequestData = JSON.stringify(metaDescRequestData);

    // Send the cURL request for generating Meta Description
    var metaDescRequest = new XMLHttpRequest();
    metaDescRequest.open("POST", apiLink, true);
    for (var header in headers) {
      metaDescRequest.setRequestHeader(header, headers[header]);
    }
    metaDescRequest.onreadystatechange = function () {
      if (metaDescRequest.readyState === 4 && metaDescRequest.status === 200) {
        var metaDesc = JSON.parse(metaDescRequest.responseText).choices[0].text;

        // Simulate a click event on the "Insert variable" button
        var insertVariableButton = document.querySelector(".yst-replacevar__button-insert");
        insertVariableButton.click();

        // Use a delay to ensure the button click is processed
        setTimeout(function () {
          // Update the Meta Description field with the generated description
          var metaDescField = document.querySelector("#yoast-google-preview-description-metabox");
          metaDescField.textContent = metaDesc;

          // Update the Meta Description preview field
          var metaDescPreviewField = document.querySelector(".sc-jhrdCu.hQecmn");
          metaDescPreviewField.textContent = metaDesc;

          console.log("This is the Meta Description for SEO Plugin: " + metaDesc); // Log the Meta Description to the console
        }, 500);
      }
    };
    metaDescRequest.send(metaDescRequestData);
  }
});