const token = document.cookie.split("=")[1];
function createOffer() {
  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 pictureValue = pictureInput.value;
  const languageValue = languageInput.value;

  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/offers",
          {
            title: newsValue,
            image: imageUrl,
            lang: languageValue,
            description: {
              article: `${innerDivContent}`,
            },
          },
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        )
        .then(function (response) {
          window.location.href = "/html/offers.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",
      });
    });
  // axios
  //   .post("https://api.sanabel-altatweer.com/offers", {
  //     title: newsValue,
  //     image: "image.png",
  //     lang: languageValue,
  //     description: {
  //       article: `${innerDivContent}`,
  //     },
  //   })
  //   .then(function (response) {
  //     console.log(response);
  //     window.location.href = "http://127.0.0.1:5501/html/offers.html";
  //   })
  //   .catch(function (error) {
  //     console.log(error);
  //     alert("حدث خطأ ما, حاول مرة اخرى");
  //   });
}
W;
function getAllOffers() {
  axios
    .get("https://api.sanabel-altatweer.com/offers")
    .then(function (response) {
      const newsContainer = document.getElementById("NewsContainer");
      response.data.map((offer) => {
        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 = `${offer.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 = offer.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 = `اللغة: ${offer.lang}`;
        const date = new Date(offer.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 () {
          deleteOffer(offer.id);
        };
        editButton.onclick = function () {
          if (offer.lang === "AR") {
            const newsString = JSON.stringify(offer);
            goToOffer(newsString);
          }
          if (offer.lang === "ENG") {
            const newsString = JSON.stringify(offer);
            goToOfferEng(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 deleteOffer(id) {
  axios
    .delete(`https://api.sanabel-altatweer.com/offers/${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 goToOffer(news) {
  localStorage.setItem("news", news);
  window.location.href = "/html/mainArticleAr.html";
}
function goToOfferEng(news) {
  localStorage.setItem("news", news);
  window.location.href = "/html/mainArticleEn.html";
}
