const token = document.cookie.split("=")[1];
function createNews() {
  const form = document.getElementById("createNewsForm");

  const newsNameInput = form.querySelector("#newsName");
  const pictureInput = form.querySelector("#picture");
  const languageInput = form.querySelector("#language");
  const editorHtml = document.getElementById("editor");

  const innerDiv = editorHtml.querySelector(".ql-editor");

  const innerDivContent = innerDiv.innerHTML;

  innerDiv.contentEditable = "false";

  const newsValue = newsNameInput.value;
  const languageValue = languageInput.value;
  const token = document.cookie.split("=")[1];
  const formData = new FormData();
  if (pictureInput.files.length > 0) {
    formData.append("file", pictureInput.files[0]);
  }
  axios
    .post("https://api.sanabel-altatweer.com/upload", formData)
    .then(function (response) {
      const imageUrl = response.data.url;
      axios
        .post(
          "https://api.sanabel-altatweer.com/news",
          {
            title: newsValue,
            image: imageUrl,
            lang: languageValue,
            description: {
              article: `${innerDivContent}`,
            },
          },
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        )
        .then(function (response) {
          window.location.href = "/html/news.html";
        })
        .catch(function (error) {
          console.log(error);
          Swal.fire({
            icon: "error",
            title: "حدث خطأ",
            text: "حدث خطأ ما, من فضلك حاول مرة اخرى",
            confirmButtonColor: "#db792e",
          });
        });
    })
    .catch(function (error) {
      console.log(error);
      Swal.fire({
        icon: "error",
        title: "حدث خطأ",
        text: "حدث خطأ ما, من فضلك حاول مرة اخرى",
        confirmButtonColor: "#db792e",
      });
    });
}
function getAllNews() {
  axios
    .get("https://api.sanabel-altatweer.com/news")
    .then(function (response) {
      const newsContainer = document.getElementById("NewsContainer");
      response.data.map((news) => {
        const newsRow = document.createElement("div");
        newsRow.className = "news-row d-flex align-center";

        // Create the img element
        const img = document.createElement("img");
        img.setAttribute("decoding", "async");
        img.src = `${news.image.replace("http:", "http://")}`;
        img.alt = "";
        img.className = "img-fluid";

        // Create the info div
        const infoDiv = document.createElement("div");
        infoDiv.className = "info";
        const h3 = document.createElement("h3");
        h3.textContent = news.title;
        const p = document.createElement("p");
        p.className = "m-0 fs-14 c-grey";
        const p2 = document.createElement("p");
        p2.className = "m-0 fs-14 c-grey";
        p2.innerHTML = `اللغة: ${news.lang}`;
        const date = new Date(news.created_at);
        const formattedDate = date.toLocaleString("en-US", {
          day: "2-digit",
          month: "long",
          year: "numeric",
          hour: "2-digit",
          minute: "2-digit",
          hour12: false, // Use 24-hour format,
        });

        p.textContent = `${formattedDate}`;
        infoDiv.appendChild(h3);
        infoDiv.appendChild(p);
        infoDiv.appendChild(p2);

        // Create the buttons-group div
        const buttonsGroup = document.createElement("div");
        buttonsGroup.className = "buttons-group";
        const editButton = document.createElement("button");
        editButton.type = "button";
        editButton.className = "btn btn-secondary";
        editButton.textContent = "الذهاب للخبر";
        const deleteButton = document.createElement("button");
        deleteButton.type = "button";
        deleteButton.className = "btn btn-danger";
        deleteButton.textContent = "حذف";
        deleteButton.onclick = function () {
          deleteNews(news.id);
        };
        editButton.onclick = function () {
          if (news.lang === "AR") {
            const newsString = JSON.stringify(news);
            goToNews(newsString);
          }
          if (news.lang === "ENG") {
            const newsString = JSON.stringify(news);
            goToNewsEng(newsString);
          }
        };
        buttonsGroup.appendChild(editButton);
        buttonsGroup.appendChild(deleteButton);

        // Append elements to newsRow
        newsRow.appendChild(img);
        newsRow.appendChild(infoDiv);
        newsRow.appendChild(buttonsGroup);

        newsContainer.appendChild(newsRow);
      });
    })
    .catch(function (error) {
      console.log(error);
      Swal.fire({
        icon: "error",
        title: "حدث خطأ",
        text: "حدث خطأ ما, من فضلك حاول مرة اخرى",
        confirmButtonColor: "#db792e",
      });
    });
}
function deleteNews(id) {
  axios
    .delete(`https://api.sanabel-altatweer.com/news/${id}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    .then(function (response) {
      Swal.fire({
        icon: "success",
        title: response.data.message,
        confirmButtonColor: "#db792e",
      }).then((result) => {
        if (result.isConfirmed) {
          location.reload();
        }
      });
    })
    .catch(function (error) {
      console.log(error);
      Swal.fire({
        icon: "error",
        title: "حدث خطأ",
        text: "حدث خطأ ما, من فضلك حاول مرة اخرى",
        confirmButtonColor: "#db792e",
      });
    });
}
function goToNews(news) {
  localStorage.setItem("news", news);
  window.location.href = "/html/mainArticleAr.html";
}
function goToNewsEng(news) {
  localStorage.setItem("news", news);
  window.location.href = "/html/mainArticleEn.html";
}
function getNewsById() {
  // document.getElementById("articleInner").innerHTML = `${news.description.article}`;
}
