import { CmsItem, ICourse } from "../schema";

export class Api {
  postCall(url: string, data: CmsItem<any, any> | any) {
    return fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("Success:", data);
        return data;
      })
      .catch((error) => {
        console.error("Error:", error);
        return error;
      });
  }

  getItem(id: number, done: (data: CmsItem<any, any>) => void) {
    const base = "https://cms.tybo.co.za/api/cms/get-data-item.php";
    const url = `${base}?id=${id}&includeChildren=true`;

    return fetch(url)
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        done(data);
        return data;
      })
      .catch((error) => {
        console.error("Error fetching class data:", error);
        throw error; // Re-throw the error to be caught by the caller if needed
      });
  }
  deleteItem(id: number) {
    const base = "https://cms.tybo.co.za/api/cms/delete-data-item.php";
    const url = `${base}?id=${id}`;

    return fetch(url)
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => {
        return data;
      })
      .catch((error) => {
        console.error("Error fetching class data:", error);
        throw error; // Re-throw the error to be caught by the caller if needed
      });
  }
  uploadBase64Image(base64Images: string[], done: (data: any) => void) {
    const base = "https://cms.tybo.co.za/api/upload/upload-base-64.php";
    const url = `${base}`;
    const data = {
      images: base64Images.map((base64) => ({ image: base64 })),
    };

    return this.postCall(url, data).then((data) => {
      done(data);
      return data;
    });
  }

  uploadFile(formData: FormData, item: any, key: string) {
    const base = "https://cms.tybo.co.za/api/upload/upload.php";
    const url = `${base}`;
    return fetch(url, {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        item[key] = data;
        alert("File uploaded successfully");
      })
      .catch((error) => {
        console.error("Error:", error);
        return error;
      });
  }
}
