var periodNumber;


function getactivitylist(name, lessonId, BookId) {
  let loader = document.getElementById("loader");
  loader.style.display = "block";
  console.log(name, lessonId, BookId, "fffffffffffff") //this console is not coming

  periodNumber = name;
  document.querySelector(".main").style.display = "none";
  //   document.querySelector(".ActivityMain").style.display = "block";

  const url = bmsURL + "getPeriodActivityDetails";
  const payload = {
    app_type: "TDA",
    mobile: userPhoneNumber || phoneNumber,
    period_id: name + 1,
    lesson_id: lessonId,
    series_id: BookId,
    is_live: 1,
    user_id: bmsuserid,
    academic_session: academicYear,
    class:getclass,
    section: section?.toUpperCase(),
  };

  async function getActivitylist() {
    const resp = await getActivityData();
    console.log("2222222", resp.data.data);
    AllperiodData = resp.data.data;
    console.log(AllperiodData, "rajji");
    const mustDoActivities = AllperiodData.filter(activity =>
      activity.activity_status_list.some(status => status.status_name === "MUST DO")
    );

    const completedMustDoActivities = mustDoActivities.filter(activity => activity.is_completed === 1);
    console.log(mustDoActivities.length, completedMustDoActivities.length, "answer")
    if (mustDoActivities.length === completedMustDoActivities.length) {
      const url = getUrl + `/addCourseSectionCompletion`;
      let res = await axios.post(url,
        {
          courseid: courseid,
          classid: cid,
          course_sectionid: course_sectionId,
          userid: userID,
          status: 1,
          financial_year: financial_year,
          schoolcode: schoolcode,
        },

      )
      console.log(res, "check");
    }

    // console.log(res);
    afterData();
  }

  function getActivityData() {
    let res = axios.post(url, payload, {
      headers: {
        Authorization: `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`,
      },
    });

    return res;
  }
  getActivitylist();
  function afterData() {
    loader.style.display = "none";
    document.querySelector(".ActivityMain").style.display = "block";
    const ActivityTitle = AllperiodData.map(
      (Activity) => Activity.activity_title
    );
    console.log(ActivityTitle);

    const activityListElement = document.getElementById("activity-list");

    AllperiodData.forEach((activity) => {
      const card = document.createElement("div");
      card.className = "card";
      card.classList.add("act-list");
      const cardContent = document.createElement("div");
      cardContent.className = "card-body";
      const titleRow = document.createElement("div");
      titleRow.className = "activity-title";
      // Add Activity Title
      if (activity.activity_title || activity.activity_title === null) {
        const activityTitle = document.createElement("span");
        activityTitle.className = "card-title";
        activityTitle.innerHTML = activity.activity_title;
        titleRow.appendChild(activityTitle);
        const checkboxLabel = document.createElement("label");
        const checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.className = "filled-in";
        checkbox.classList.add("form-check-input");
        checkbox.classList.add("f-chk");
        // checkbox.checked = activity.is_completed ? true : false; // Reflect if activity is completed
        // const span = document.createElement('span');
        // span.className = 'checkbox-right'; // For alignment
        checkbox.dataset.id = activity.activity_id; // Assigning a unique ID for each checkbox
        checkbox.checked = activity.is_completed ? true : false; // Reflect if activity is completed
        checkbox.disabled = activity.is_completed ? true : false; // Disable if completed

        const span = document.createElement("span");
        span.className = "checkbox-right"; // For alignment

        // Add event listener to disable checkbox after checking
        checkbox.addEventListener("change", function () {
          if (this.checked) {
            // this.disabled = true;
            // Enable submit button if any checkbox is checked
            document.getElementById("submit-btn").disabled = false;
          }
        });
        checkboxLabel.appendChild(checkbox);
        checkboxLabel.appendChild(span);
        titleRow.appendChild(checkboxLabel);

        // Append title row to card content
        cardContent.appendChild(titleRow);
      }

      // Add Activity Subtitle
      if (activity.activity_subtitle) {
        const activitySubtitle = document.createElement("h5");
        activitySubtitle.className = "card-title";
        activitySubtitle.innerHTML = activity.activity_subtitle;
        cardContent.appendChild(activitySubtitle);
      }

      // Add Activity Description
    //   if (activity.activity_description) {
    //     const activityDescription = document.createElement("div");
    //     activityDescription.className = "card-text";
    //     activityDescription.innerHTML = activity.activity_description;
    //     console.log(activity.activity_description, "************************");
    //     cardContent.appendChild(activityDescription);
    //   }
     if (activity.activity_description) {
const updatedDescription = activity.activity_description.replace(
    /<img\s+[^>]*src="([^"]+)"[^>]*>/gi,
    (match, src) => {
      const isAbsolute = src.startsWith("http://") || src.startsWith("https://");
      const fullSrc = isAbsolute ? src : `${imageBaseUrl}${src}`;
      return match.replace(src, fullSrc); // Replace only the src part, keeping rest of tag intact
    }
  );
         const activityDescription = document.createElement("div");
        activityDescription.className = "card-text";
        if(updatedDescription.includes("https")){
          activityDescription.innerHTML = updatedDescription;
        }
        else{
          activityDescription.innerHTML = activity.activity_description;
        }
       
     
        console.log(updatedDescription, "************************");
        cardContent.appendChild(activityDescription);
      }
      if (
        activity.activity_status_list &&
        activity.activity_status_list.length > 0
      ) {
        const statusContainer = document.createElement("div");
        statusContainer.className = "activity-status";

        activity.activity_status_list.forEach((status) => {
          const statusSpan = document.createElement("span");
          statusSpan.style.backgroundColor = status.status_color;
          statusSpan.textContent = status.status_name;
          statusContainer.appendChild(statusSpan);
        });

        cardContent.appendChild(statusContainer);
      }
      if (activity.activity_time) {
        const actime = document.createElement("div");
        cardContent.appendChild(actime);
        actime.className = "act-time";
        const activityTime = document.createElement("span");
        activityTime.className = "activity-time";
        actime.appendChild(activityTime);
        const imageTimeIcon = document.createElement("img");
        imageTimeIcon.className = "TimeIconImg";
        imageTimeIcon.src = "images/clock.png";
        actime.appendChild(imageTimeIcon);
        activityTime.textContent = activity.activity_time;
        actime.appendChild(activityTime);
      }
      // Append card content to card
      card.appendChild(cardContent);

      // Append card to activity list
      activityListElement.appendChild(card);
    });
    const SubmitBtn = document.getElementById("submit-btn");
  }
}
async function submitActivities() {
  const completedActivities = [];
  console.log(AllperiodData);
  AllperiodData.forEach((activity) => {
    const checkbox = document.querySelector(
      `input[type="checkbox"][data-id="${activity.activity_id}"]`
    );
    if (checkbox && checkbox.checked) {
      completedActivities.push({
        activity_id: activity.activity_id,
        is_completed: "1",
      });
    }
  });
  const url = bmsURL + "postActivityCompletion";

  console.log(getSubjectId[0]);
  console.log(grade);
  console.log(periodNumber + 1);
  console.log(lessonId);
  console.log(BookId);
  console.log(lessonUid);
  console.log(bmsuserid);
  console.log(section, "sections");

  let res = await axios.post(
    url,
    {
      user_id: bmsuserid,
      subject_id: getSubjectId[0],
      grade: grade,
      period_id: periodNumber + 1,
      activity_data: JSON.stringify(completedActivities),
      lesson_id: lessonId,
      series_id: BookId,
      academic_session: academicYear,
      class:getclass,
      section: section?.toUpperCase()
    },
    {
      headers: {
        Authorization: `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`,
      },
    }
  );
  console.log(res);
  if (res.data.error === false) {
    alert("success")
  }

}
