var all_states;
var stateName;
var getStateCode;
var allCity;
var getcityCode
var getCityName;
var getSchoolName;
var getSchoolCode;
var userSection;
var userMobile;
var userEmail;
var userName;
var getGradeName;
var getGradeCode;
console.log(getuserInfoaFirstName);

const updateBodyHeight = () => {
    console.log("body hegith")
    document.body.style.height = "100vh";
}

function showMobilePopUp() {
    document.getElementById('otpForm').addEventListener('submit', function (event) {
        event.preventDefault();
        var phoneNumber = document.getElementById('phoneNumber').value;
        console.log(phoneNumber)
        submit(phoneNumber)
        userUpdateProfile(phoneNumber)
        console.log(getuserInfoaFirstName);
    })

}
var getuserInfoaFirstName;
var getuserInfoaLastName;
var getuserInfoCity
var getuserInfoCountry;
var getuserInfoDob;
var getuserInfoState;


async function userUpdateProfile(phoneNumber) {
    const userUpdateUrl = getUrl  + `/updateUserProfile`
    let res = await axios.post(userUpdateUrl, {
        userid: userID,
        firstname: getuserInfoaFirstName,
        lastname: getuserInfoaLastName,
        phone1: phoneNumber,
        phone2: '',
        address: getuserInfoAddress,
        city: getuserInfoCity,
        country: getuserInfoCountry,
        dob: getuserInfoDob === 'Invalid date' ? "" :  getuserInfoDob,
        gender: "",
        state: ""
    },
    )
    console.log(res);


}
async function submit(phoneNumber) {
    console.log(phoneNumber);
    const url = bmsURL + 'loginByMobileNumber';
    let res = await axios.post(url, {
        app_type: 'TDA',
        mobile: phoneNumber
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    console.log(res.data.error);
    if (res.data.error) {
        // // do registration first
console.log(getuserInfoaFirstName);
        let popupResForm = document.getElementById("modal1");
        popupResForm.style.display = "block";
        // alert('do registration first')
        var optForm = document.querySelector('.login-form')
        optForm.style.display = "none";
 console.log(getuserInfoaFirstName,getuserInfoaLastName)
        // registration_form()

    } else {
        var optForm = document.querySelector('.login-form')
        optForm.style.display = "none";
        let loader = document.getElementById("loader");
        loader.style.display = "block";
        getGradeLists(grade, courseName, phoneNumber);
    }
}

function registration_form() {
     
    getState()
    let popupResForm = document.getElementById("modal1");
    popupResForm.style.display = "none";
    let popup = document.getElementById("Registration_form");
    popup.style.display = "block";


}
async function getState() {
    const url = bmsURL + 'getStates';
    console.log(url);
    let res = await axios.get(url, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    updateBodyHeight();
    all_states = res.data.data
    let stateSelect = document.createElement("select");
    stateSelect.setAttribute("required", "");
    stateSelect.classList.add("form-select");

    let stateSelectContainer = document.getElementById("selectState");
    stateSelectContainer.appendChild(stateSelect);

    stateSelect.addEventListener("change", (event) => {
        console.log(event.target.value);
        getStateCode = event.target.value
        getCity(getStateCode)
    }
    )
    console.log(res.data.data);
    console.log(all_states);
    const stateOption = document.createElement("option")
    stateOption.innerHTML = 'Select State'
    stateOption.value = ''
    stateSelect.appendChild(stateOption)
    for (st = 0; st < all_states.length; st++) {
        let stateOptions = document.createElement("option")
        stateOptions.innerHTML = all_states[st].state_name
        stateOptions.value = all_states[st].state_code
        stateSelect.appendChild(stateOptions)
    }

    /*  let citySelect = document.createElement("select");
     citySelect.setAttribute("required", "");
    
     let citySelectContainer = document.getElementById("selectCity");
     citySelectContainer.innerHTML = ''
     citySelectContainer.appendChild(citySelect); */
}

async function getCity(stateCode) {
    const url = bmsURL + 'getCities';
    console.log(url);
    let res = await axios.post(url, {
        app_type: "TDA",
        state_code: stateCode
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    allCity = res.data.data
    let citySelect = document.createElement("select");
    citySelect.setAttribute("required", "");
    citySelect.classList.add("form-select");
    let citySelectContainer = document.getElementById("selectCity");
    citySelectContainer.innerHTML = ''
    citySelectContainer.appendChild(citySelect);




    citySelect.addEventListener("change", (event) => {
        getCityName = event.target.options[event.target.selectedIndex].text;
        getcityCode = event.target.value
        getSchool(getcityCode, getCityName)
    }
    )
    console.log(res.data.data);
    console.log(allCity);
    const cityOption = document.createElement("option")
    cityOption.innerHTML = 'Select city'
    cityOption.value = ''
    citySelect.appendChild(cityOption)
    for (ct = 0; ct < allCity.length; ct++) {
        let cityOptions = document.createElement("option")
        cityOptions.innerHTML = allCity[ct].city_name
        cityOptions.value = allCity[ct].state_code
        citySelect.appendChild(cityOptions)
    }
    // getSchool()
}
async function getSchool(getcityCode, getCityName) {
    const url = bmsURL + 'mcmList';
    console.log(url);
    let res = await axios.post(url, {
        app_type: "TDA",
        state_code: getcityCode,
        city: getCityName
    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    console.log(res.data.data);
    allSchool = res.data.data
    let schoolSelect = document.createElement("select");
    schoolSelect.setAttribute("required", "");
    schoolSelect.classList.add("form-select");
    let schoolSelectContainer = document.getElementById("selectSchool");
    schoolSelectContainer.innerHTML = ''
    schoolSelectContainer.appendChild(schoolSelect);

    schoolSelect.addEventListener("change", (event) => {
        getSchoolName = event.target.options[event.target.selectedIndex].text;
        getSchoolCode = event.target.value
        console.log(getSchoolCode);
        console.log(getSchoolName);
        getGrade()
    }
    )
    console.log(res.data.data);
    console.log(allSchool);
    const stateOption = document.createElement("option")
    stateOption.innerHTML = 'Select School'
    stateOption.value = ''
    schoolSelect.appendChild(stateOption)
    for (st = 0; st < allSchool.length; st++) {
        let schoolOptions = document.createElement("option")
        schoolOptions.innerHTML = allSchool[st].name
        schoolOptions.value = allSchool[st].mcm_no
        schoolSelect.appendChild(schoolOptions)
    }

}
async function getGrade() {
    const url = bmsURL + 'getGradeList';
    console.log(url);
    let res = await axios.post(url, {
        app_type: "TDA",

    }, {
        headers: {
            'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
        }
    })
    console.log(res.data.data);
    allGrade = res.data.data
    let gradeSelect = document.createElement("select");
    gradeSelect.setAttribute("required", "");
    gradeSelect.classList.add("form-select");
    let gradeSelectContainer = document.getElementById("selectGrade");
    gradeSelectContainer.innerHTML = ''
    gradeSelectContainer.appendChild(gradeSelect);

    gradeSelect.addEventListener("change", (event) => {
        getGradeName = event.target.options[event.target.selectedIndex].text;
        getGradeCode = event.target.value
        console.log(getGradeName);
        console.log(getGradeCode);

    }
    )
    console.log(res.data.data);
    console.log(allSchool);
    const gradeOption = document.createElement("option")
    gradeOption.innerHTML = 'Select Grade'
    gradeOption.value = ''
    gradeSelect.appendChild(gradeOption)
    for (gt = 0; gt < allGrade.length; gt++) {
        let gradeOptions = document.createElement("option")
        gradeOptions.innerHTML = allGrade[gt].grade
        gradeOptions.value = allGrade[gt].id
        gradeSelect.appendChild(gradeOptions)
    }
}
async function submitDetails() {
    console.log(getuserInfoaFirstName,getuserInfoaLastName,grade,section,userPhoneNumber);
    document.getElementById('registration-form').addEventListener('submit', async function (event) {
        // event.preventDefault();

        // let userName = document.getElementById('name').value;
        // let userEmail = document.getElementById('email').value;
        // let userMobile = document.getElementById('mobile').value;
        // let userSection = document.getElementById('section').value;

        const url = bmsURL + 'acUserRegistration';

        try {
            const res = await axios.post(url, {
                 username:userPhoneNumber,
                email:email,
                name:getuserInfoaFirstName ,
                mcm_code:getuserMcmCode,
                is_principal:0,
                class:grade,
                section:section,
                subject:subjectName
                // name: userName,
                // state: getcityCode,
                // city: getCityName,
                // mcm_code: getSchoolCode,
                // school: getSchoolName,
                // section: userSection,
                // grade: getGradeName,
                // mobile: userMobile,
                // email: userEmail,
                // deviceId: "fgh",
                // devicename: "tsts",
                // appid: "172",
                // app_fcm_token: "defd",
                // app_package_name: "com.ratnasagar.apptiveclasses",
                // device_type: "android",
                // app_type: "TDA"
            }, {
                headers: {
                    'Authorization': `Bearer d90b3ac333de82aab2846bf0f9cb5bc31bdb2309`
                }
            });

            // Check if response contains an error
            if (res.data && res.data.error === false) {
                console.log("Registration successful", res.data);

                // Hide registration form
                let popup = document.getElementById("Registration_form");
                popup.style.display = "none";

                // Show login form
                var optForm = document.querySelector('.login-form');
                optForm.style.display = "block";

            } else {
                console.error("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.");
        }
    });
}
