var nodeURL
var bmsURL = "https://rsplapi.rsgr.in/public/api/apps/ta/v3/";
var userPhoneNumber = null
var userID
var grade
var BookId;
var lessonId;
var courseName;
var semester;
var subjectName = null
var themeName = null
var lessonName = null
var getSubjectId
var lessonUid
var getuserInfo;
var getuserInfoaFirstName;
var getuserInfoaLastName;
var getuserInfoCity
var getuserInfoCountry;
var getuserInfoDob;
var getuserInfoAddress;
var getuserInfoState;
var getuserInfoGender;
var getuserMcmCode;
var getUrl;
var bmsuserid;
var course_sectionId;
var financial_year;
var schoolcode;
var courseid;
var cid;
var getclass;
var section;
var academicYear;
var selectedLanguage = 'en';

console.log(courseName);
window.onload = function () {
    let loader = document.getElementById("loader");
    loader.style.display = "block";
    init();
}
function showErrorPopup(message) {
    document.getElementById("errorMessage").innerText = message;
    document.getElementById("errorPopup").style.display = "block";
    let loader = document.getElementById("loader");
    loader.style.display = "none";
}

function closeErrorPopup() {
    document.getElementById("errorPopup").style.display = "none";

}

async function init() {
    try {
        console.log("---------", window.location.href);
        const urlParams = window.top.location.search.substring(1);
        const getValues = new URLSearchParams(urlParams);

        getUrl = getValues.get("url");
        nodeUrl = getUrl;
        userID = getValues.get("userid");
        course_sectionId = getValues.get("course_sectionid")
        financial_year = getValues.get("financial_year")
        schoolcode = getValues.get("schoolcode")
        courseid = getValues.get("courseid")
        cid = getValues.get("cid")
        grade = getValues.get("stdclass")?.toLowerCase();
        courseName = getValues.get("coursename")?.toLowerCase();
        semester = getValues.get("semester")?.toLowerCase();
        subjectName = getValues.get("subject")?.toLowerCase();
        console.log(subjectName)
         if(subjectName ==="reading eggs"){
            subjectName='Reams (Reading Eggs)'
        }
        if(subjectName ==="mathseeds"){
            subjectName='Reams (Mathseeds)'
        }
         if(subjectName ==="reading eggspress"){
            subjectName='Reams (Reading Eggspress)'
        }
        console.log(subjectName)
        themeName = getValues.get("theme")?.toLowerCase();
        console.log(themeName)
        lessonName = getValues.get("lesson")?.toLowerCase();
        getclass=getValues.get("stdclass")
        section = getValues.get("section");

        getUserDetails(userID, grade, courseName, getUrl);
    } catch (error) {
        consol.log("Failed to initialize. ")
        // showErrorPopup("Failed to initialize. " + error.message);
    }
}

async function getUserDetails(userID, grade, courseName, getUrl) {
    const userDetailsUrl = getUrl + `/getUserProfile?userid=${userID}`
    const userInfoResponse = await axios.get(userDetailsUrl);
    getuserInfo = userInfoResponse.data?.info[0]
    console.log(getuserInfo);
    getuserInfoaFirstName = getuserInfo.firstname
    getuserInfoaLastName = getuserInfo.lastname
    getuserInfoAddress = getuserInfo.address
    getuserInfoCity = getuserInfo.city
    getuserInfoCountry = getuserInfo.country
    getuserInfoDob = getuserInfo.dob
    getuserInfoGender = getuserInfo.gender
    getuserInfoState = getuserInfo.state
    getuserMcmCode = getuserInfo.mcm_code
    const url = bmsURL + 'getAcademicSession';
    let res = await axios.post(url, {
        app_type: 'TDA',
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    console.log(res.data);
    academicYear = res.data.astype1
    imageBaseUrl = res.data.image_base_url;
    console.log(academicYear)
    userPhoneNumber = userInfoResponse.data.info[0].email
    // userPhoneNumber=''
    console.log(userPhoneNumber);
    // userPhoneNumber = ""

if (userPhoneNumber && userPhoneNumber.length) {

    const token = 'd90b3ac333de82aab2846bf0f9cb5bc31bdb2309';
    const loginUrl = bmsURL + 'loginByEmailId';

    try {
        const loginRes = await axios.post(loginUrl, {
            app_type: 'TDA',
            email: userPhoneNumber
        }, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        const userData = loginRes.data.data;
        console.log(loginRes.data.error, "login response");

        if (loginRes.data.error) {
            // User not found, register them
            const registerUrl = bmsURL + 'lmsUserRegister';
            const payload = [{
                username: userPhoneNumber,
                email: userPhoneNumber,
                name: getuserInfoaFirstName,
                mcm_code: getuserMcmCode,
                is_principal: 0,
                teacher_info: [
                    {
                        class: grade,
                        section: section,
                        subject: subjectName
                    }
                ]
            }];

            try {
                const res = await axios.post(registerUrl, payload, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                console.log(res.data.data)
                console.log(JSON.stringify(res.data))

                const responseData = res.data.data[0];
                console.log(responseData)
                if (res.data && res.data.status === true) {
                    console.log("Registration successful", res.data);
                    bmsuserid = res.data.data[0].uid;
                    lessonUid = res.data.data[0].uid;
                    getGradeLists(grade, courseName, res.data.data[0].email);
                } else {
                    console.error("Registration API Error:", res.data);
                    alert("Registration failed. Please try again.");
                }

                
                
                

            } catch (error) {
                console.error("Network/API Error:", error);
                alert("Something went wrong. Please check your network and try again.");
            }

        } else {
            // User exists, continue
            const mobileNumber = userData[0].email;
            bmsuserid = userData[0].uid;
            lessonUid = userData[0].uid;

            const optForm = document.querySelector('.login-form');
            if (optForm) optForm.style.display = "none";

            getGradeLists(grade, courseName, mobileNumber);
        }

    } catch (error) {
        console.error("Login API Error:", error);
        alert("Unable to log in. Please try again later.");
    }

}


}



async function getGradeLists(grade, courseName, phoneNumber) {
    try {
        const url = bmsURL + "getSeriesListByGrade";
        let res = await axios.post(url, {
            app_type: "TDA",
            mobile: phoneNumber,
            grade: grade,
            is_live: 1,
            user_id: bmsuserid
        }, {
            headers: { "Authorization": `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309` }
        });

        if (!res.data.data) throw new Error("No series found for this grade.");
        BookId = res.data.data.find(book => book.series_name.toLowerCase() === courseName)?.id;
        if (!BookId) throw new Error("Course not found.");
        getSemseter(BookId);
    } catch (error) {
        // showErrorPopup(error.message);
    }
}
async function getSemseter(BookId,) {
    const url = bmsURL + 'getTermSemester';
    let res = await axios.post(url, {
        app_type: 'TDA',
        mobile: userPhoneNumber,
        series_id: BookId,
        user_id: bmsuserid
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    allSemesterDetails = res.data.data
    console.log(allSemesterDetails);
    const getSemseterid = res.data.data.map(sem => {
        if (sem.term_sem.toLowerCase() === semester) {
            return sem.id
        }
        return null;
    }).filter(id => id !== null)
    console.log(getSemseterid[0]);
    getSubject(getSemseterid[0])
}
async function getSubject(SemId) {
    const url = bmsURL + 'getSubjects';
    let res = await axios.post(url, {
        app_type: 'TDA',
        mobile: userPhoneNumber,
        sem_term_id: SemId,
        user_id: bmsuserid
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    const getAllSubject = res.data.data
    console.log(getAllSubject);

    if (subjectName.includes("environmental")) {
        subjectName = "evs";
    }
 
   
    getSubjectId = getAllSubject.map(subject => {
        console.log(subject.subject_name.length, "subjectName", subjectName.length);
        if (subject.subject_name.toLowerCase() === subjectName) {
            return subject.subject_id
        }
        return null
    }).filter(id => id !== null)
    console.log(getSubjectId[0]);
    getThemeList(getSubjectId[0])
}
async function getThemeList(SubId) {
    const url = bmsURL + 'getSubjectThemeList';
    let res = await axios.post(url, {
        app_type: 'TDA',
        mobile: userPhoneNumber,
        subject_id: SubId,
        is_live: 1,
        user_id: bmsuserid
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    const themeList = res.data.data
    console.log(themeList, "themeList");
    // const getUrlThemeName = themeName.split(": ")
    const getUrlThemeName = themeName.match(/:\s?(.*)/);
    console.log(getUrlThemeName)
    // const theme_nameVal = getUrlThemeName[1]
    const getUrlLessonName = lessonName.match(/.\s?(.*)/)[0]
    console.log(getUrlLessonName)
    var  theme_nameVal = getUrlThemeName
   
  console.log(theme_nameVal)
    if   (theme_nameVal === null && (subjectName.includes("Reams (Reading Eggs)") || subjectName.includes("Reams (Reading Eggspress)") || subjectName.includes("Reams (Mathseeds)")))
{
        console.log("done")
       theme_nameVal=themeName
    }
    else if
        (theme_nameVal===null){
       theme_nameVal=getUrlLessonName
    }
    
     else {
      theme_nameVal=getUrlThemeName[1]
    }
    console.log(theme_nameVal,"theme_nameVal")
    console.log(themeList,theme_nameVal, "themeList");
themeId = themeList.map(theme => {
    console.log(theme.theme_title.toLowerCase(), theme_nameVal, theme.theme_title.length, theme_nameVal.length, "vvv");
    const titleTrimmed = theme.theme_title.toLowerCase().trim();
    const nameValTrimmed = theme_nameVal.toLowerCase().trim();
    
    console.log(titleTrimmed === nameValTrimmed, titleTrimmed == nameValTrimmed, titleTrimmed, nameValTrimmed , "compare");

    if (titleTrimmed === nameValTrimmed) {
        console.log("test");
        return theme.theme_id;
    }
    return null;
}).filter(id => id !== null);

    console.log(themeId, "themecheck");
    getLesson(themeId[0])
   
}
async function getLesson(themeId) {
    try {
        const url = bmsURL + 'getThemeLessonList';
        let res = await axios.post(url, {
            app_type: 'TDA',
            mobile: userPhoneNumber,
            theme_id: themeId,
            is_live: 1,
            user_id: bmsuserid,
            series_id: BookId,
            academic_session: academicYear,
            section: section?.toUpperCase(),
        }, {
            headers: {
                'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
            }
        });
        
//  const lesson_Details = res.data.data;
//  const activityList = document.getElementById("activity-list");
// activityList.innerHTML = ""; // Clear any previous content

// lesson_Details.forEach(lesson => {
//     const lessonDiv = document.createElement("div");
//     lessonDiv.className = "mb-2 fw-bold fs-5"; // Bootstrap styling (optional)
//     lessonDiv.textContent = lesson.lesson_name;
//     activityList.appendChild(lessonDiv);
// });

        console.log(res.data.data, section, "section")
        console.log(res.data.data[0].total_activity.must_do)
        console.log(res.data.data[0].completed_activity.must_do)
        var Total_Activity = res.data.data[0].total_activity.must_do
        var Completed_Activity = res.data.data[0].completed_activity.must_do
        console.log(Total_Activity, Completed_Activity, "check")
        // if (Total_Activity.must_do === Completed_Activity.must_do)
        if (Total_Activity > 0 && Completed_Activity > 0 && Total_Activity === Completed_Activity) {
            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("11111", res.data.message);
        if (!res.data.data || res.data.data.length === 0) {
            throw new Error("No lessons found for the selected theme.");
        }

        const getUrlLessonName = lessonName.match(/.\s?(.*)/);

        console.log("AAAAA000", res.data.data, lessonName);
        const lessonDetails = res.data.data;
         loader.style.display = "none";

var _main = document.querySelector(".main");
_main.style.display = "block";

let linkButton = document.createElement('div');
linkButton.classList.add("container");
linkButton.classList.add("hideonclick");

let linkRow = document.createElement('div');
linkRow.classList.add("row");
linkRow.classList.add("lrow");

linkButton.appendChild(linkRow);

// Loop through lessons
lessonDetails.forEach((lesson) => {
  let linkCol = document.createElement('div');
  linkCol.classList.add("col-lg-6");
  linkCol.classList.add("lcol");
lessonId=lesson.lesson_id
  // Add the lesson name button
//   linkCol.innerHTML = `
//     <button 
//       class="waves-effect waves-light my-5 px-5 py-2 btn btn-primary linkbtn"
//       onclick="getPeriodDetails(${lesson.lesson_id})">
//       ${lesson.lesson_name}
//     </button>
//   `;
console.log(lessonName,lesson.lesson_name,"lesson")
//   linkRow.appendChild(linkCol);
if (lessonName.toLowerCase().trim() === lesson.lesson_chapter_name.toLowerCase().trim()) {

if(lesson.lesson_name){
     linkCol.innerHTML = `
    <button 
      class="waves-effect waves-light my-5 px-5 py-2 btn btn-primary linkbtn"
      onclick="getPeriodDetails(${lesson.lesson_id})">
      ${lesson.lesson_name}
    </button>
  `;

  linkRow.appendChild(linkCol);

} else {

  linkCol.innerHTML = `
    <p class="text-muted my-4">
      The lesson plan for this course is being created. Please check back after it’s updated.
    </p>
  `;

  linkRow.appendChild(linkCol);
}
}
 

});

_main.appendChild(linkButton);


//         console.log("Lessons: ", lessonDetails[0].lesson_chapter_name.toLowerCase(), lessonDetails[0].lesson_chapter_name.length, lessonName, lessonName.toLowerCase());
//         console.log("MEssage")

//         lessonId = lessonDetails
//             .map(lesson => lesson.lesson_chapter_name.toLowerCase().trim() === lessonName.trim() ? lesson.lesson_id : null)
//             .filter(id => id !== null);

//         if (!lessonId[0]) {
//             throw new Error("Lesson not found. Please check the lesson name.");
//         }
// console.log("Lesson:", lessonDetails.map(lesson =>
//   lesson.lesson_chapter_name.toLowerCase().trim() === lessonName.trim().toLowerCase()
//     ? lesson.lesson_id
//     : null
// ));

//         console.log("111100", lessonId[0]);
//         getPeriodDetails(lessonId[0]);
    } catch (error) {
        // getPeriodDetails(themeId)
        console.log(error);
        showErrorPopup("An error occurred while fetching lessons.");
    }
}

async function getPeriodDetails(lessonId) {
    const url = bmsURL + 'getlessonperioddetails';


    let res = await axios.post(url, {
        app_type: 'TDA',
        mobile: userPhoneNumber,
        lesson_id: lessonId,
        is_live: 1,
        user_id: bmsuserid,

    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
document.querySelector(".hideonclick").style.display = "none";
    loader.style.display = "none";
    var _main = document.querySelector(".main");
    _main.style.display = "block";
    const periodNames = res.data.data.period_list.map(period => period.period_name);
    console.log(periodNames);
    let addHTMLCode = ""
    let linkButton = document.createElement('div');
    linkButton.classList.add("container");

    let linkRow = document.createElement('div');
    linkRow.classList.add("row");
    linkRow.classList.add("lrow");

    linkButton.appendChild(linkRow)

    for (name in periodNames) {



        let linkCol = document.createElement('div');
        linkCol.classList.add("col-lg-6");
        linkCol.classList.add("lcol");
        linkRow.appendChild(linkCol)

        linkCol.innerHTML = `<button class="waves-effect waves-light my-5 px-5 py-2 btn btn-primary linkbtn" onclick="getactivitylist(${name},${lessonId},${BookId})">${periodNames[name]}</button>`


    }

    _main.appendChild(linkButton);

}

// function showMobilePopUp() {
//     let popup = document.getElementById("login-form");
//     // popup.style.display = "block";
//     EnterMobNumber()
// }

