"use strict";

const User = require('../models/user');
const Document = require('../models/document');
const keys = require('../config/keys');
const nodemailer = require("nodemailer");
const M_session = require("../models/mannual__session");
const fs = require('fs');
const path = require('path');


// const fileSavePath = 'D:/backend_Api/nodeJs_pro/public';
const fileSavePath = path.join(__dirname, 'public');


class userController {
    static async submitForm(req, res) {
        try {
            console.log(`in submitForm... ${JSON.stringify(req.body)}`)
            const { email, apps_data, phone_uid } = req.body;
            let lower_email = email.toLowerCase()
            if (lower_email == '' || phone_uid == '' || lower_email == null || phone_uid == null) {
                res.send({ "message": 'Please enter all fields', 'code': 204 });
            } else {

                let existingUser = await User.findOne({ $and: [{ email: lower_email }, { phone_uid: phone_uid }] });
                let existing_Loginuser = await User.findOne({ $and: [{ email: lower_email }, { phone_uid: phone_uid }, { otp_verify: 'Yes' }] });

                let existUser = await User.find({ email: lower_email }).exec();
                // ----------------------Will be add a new condition if parent or Teacher---------------
                if (existUser.role_id == 6) {
                    res.send({ "message": "Email Already registered as Teacher!!", "data": null, 'code': 204 });
                } else {
                    // ----------------------Will be add a new condition if parent or Teacher---------------
                    let filteredUsers = existUser.filter(user => user.phone_uid === '').sort((a, b) => b.createdAt - a.createdAt);

                    // Assuming you want to collect emails from filtered users into an array
                    let fill_data = filteredUsers.map(user => user.phone_uid);
                    // let fill__id = filteredUsers.map(user => user._id);
                    // Now, 'emails' contains the emails of users with an empty 'phone_uid'

                    console.log(`in line no. 21.... ${fill_data}`)

                    // let countDoc = await User.countDocuments({$and: [{ email: email },{ phone_uid!=''}]}).exec();
                    let countDoc = await User.countDocuments({ $and: [{ email: lower_email }, { phone_uid: { $ne: '' } }, { otp_verify: 'Yes' }] }).exec();
                    // console.log(`in line 28... ${JSON.stringify(countDoc)}`)
                    if (!existUser) {
                        console.log(`in line no. 20 - not existing User`);
                        // ---------------------Mail Function Started------------------------
                        // console.log(`in line 22 |... ${keys.host}`);
                        const transporter = nodemailer.createTransport({
                            host: keys.host,
                            port: keys.port,
                            // ssl: false,
                            ssl: true,
                            // secure:true,
                            auth: {
                                user: keys.user,
                                pass: keys.pass
                            }
                        });

                        // Random Otp Generate Start----------------
                        function between(min, max) {
                            return Math.floor(Math.random() * (max - min + 1) + min);
                        }
                        var otp = between(100000, 999999);
                        if(lower_email === 'test@gmail.com'){
                            console.log(`in testemail fucntion....`)
                            var otp = 111111 
                        }

                        // Random Otp Generate End----------------
                        async function main() {
                            const info = await transporter.sendMail({
                                from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                                to: lower_email,
                                subject: `Your verification code for your ${apps_data}`,
                                text: `${apps_data}`,
                                html: `<!doctype html>
                                <html>
                                    <head>
                                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                        <!-- Add CSS styles for your email -->
                                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                        <style>
                                            body {
                                                font-family: sans-serif;
                                                text-align: center;
                                            }
                                            .main {
                                                display: block;
                                                margin: auto;
                                                max-width: 600px;
                                            }
                                            img {
                                                max-width: 100%;
                                                margin-top:8%;
                                                height:10em;
                                            }
                                            .logo_img {
                                                max-width: 90%;
                                                margin-top:6%;
                                                height:2em;
                                            }
                                            .social-icons img {
                                                max-width: 80%;
                                                height:24px;
                                            }
                                            h3 {
                                                font-size: 18px;
                                                font-weight: bold;
                                                margin-top: 20px;
                                                color: #0563aa;
                                            }
                                            h1 {
                                                color: #0563aa;
                                                letter-spacing: 2px;
                                                font-size:3em;
                                            }
                                            p {
                                                font-size: 12px;
                                                color: #0563aa;
                                            }
                                            a{
                                                color:#0563aa;
                                            }
                                            .social-icons {
                                                color: #F4F6F6;
                                            }
                                            hr{
                                                color:#DDF9F8;
                                            }
                                        </style>
                                    </head>
                                    <body style="text-align:center;">
                                        <div class="main" >
                                            <img src="https://gunjanappstudios.com/public/mail/toddler.png" alt="Logo">
                                            <br>
                                            <h3>Your verification code is:</h3>
                                            <br>
                                            <div style="background:#e3fffd; margin-left: 15%; margin-right: 15%; padding: 1% 0%; border-radius: 20px;">
                                                <h1>${otp}</h1>
                                            </div>
                                        </div>
                                        <br>
                                        <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                        <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>
                                        
                                        <div class="social-icons">
                                            <!-- Add your social icons here using Font Awesome classes -->
                                            <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                            <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                            <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                            <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                        </div>
                                        <hr>
                                        <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                    </body>
                                </html>`,
                            });

                            // console.log("Message sent: %s", info.messageId);
                        }
                        // console.log(`in line 67...`);
                        let newPerson = new User({
                            email: lower_email,
                            phone_uid: phone_uid,
                            otp_no: otp,
                            otp_verify: 'No',
                            login_count: 0,
                            role_id: 8,
                            signin_count: 1,
                            apps_data: apps_data,
                        });

                        await main();
                        await newPerson.save();
                        res.send({ "message": "Otp has been sent successfully!!", "email": lower_email, 'code': 200 });
                        // -----------------------Mail Function End--------------------
                    } else {
                        console.log(`in line no. 77 - existing User`);
                        let login_user = await M_session.find({ user_id: req.session.userId }).exec();

                        if (login_user.length > 0) {
                            // Session already exists for the user
                            res.send({ "message": "Already Logged In!", "data": existing_Loginuser, 'code': 202 });
                        } else {
                            console.log(`in line 93...`)

                            console.log(`in line 96.......${phone_uid}`)
                            // if (existingUser.phone_uid == phone_uid) {
                            if (existingUser) {
                                console.log(`in line 94....`)
                                // ---------------------Mail Function Started------------------------
                                const transporter = nodemailer.createTransport({
                                    host: keys.host,
                                    port: keys.port,
                                    ssl: true,
                                    // ssl: false,
                                    auth: {
                                        user: keys.user,
                                        pass: keys.pass
                                    }
                                });
                                // Random Otp Generate Start----------------
                                function between(min, max) {
                                    return Math.floor(Math.random() * (max - min + 1) + min);
                                }

                                var otp = between(100000, 999999);
                                // Random Otp Generate End----------------
                                if(lower_email === 'test@gmail.com'){
                                    console.log(`in testemail fucntion....`)
                                    var otp = 111111 
                                }

                                async function main() {
                                    const info = await transporter.sendMail({
                                        from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                                        to: lower_email,
                                        subject: `Your verification code for your ${apps_data}`,
                                        text: `${apps_data}`,
                                        html: `<!doctype html>
                                        <html>
                                            <head>
                                                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                                <!-- Add CSS styles for your email -->
                                                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                                <style>
                                                    body {
                                                        font-family: sans-serif;
                                                        text-align: center;
                                                    }
                                                    .main {
                                                        display: block;
                                                        margin: auto;
                                                        max-width: 600px;
                                                    }
                                                    img {
                                                        max-width: 100%;
                                                        margin-top:8%;
                                                        height:10em;
                                                    }
                                                    .logo_img {
                                                        max-width: 90%;
                                                        margin-top:6%;
                                                        height:2em;
                                                    }
                                                    .social-icons img {
                                                        max-width: 80%;
                                                        height:24px;
                                                    }
                                                    h3 {
                                                        font-size: 18px;
                                                        font-weight: bold;
                                                        margin-top: 20px;
                                                        color: #0563aa;
                                                    }
                                                    h1 {
                                                        color: #0563aa;
                                                        letter-spacing: 2px;
                                                        font-size:3em;
                                                    }
                                                    p {
                                                        font-size: 12px;
                                                        color: #0563aa;
                                                    }
                                                    a{
                                                        color:#0563aa;
                                                    }
                                                    .social-icons {
                                                        color: #F4F6F6;
                                                    }
                                                    hr{
                                                        color:#DDF9F8;
                                                    }
                                                </style>
                                            </head>
                                            <body style="text-align:center;">
                                                <div class="main" >
                                                    <img src="https://gunjanappstudios.com/public/mail/toddler.png" alt="Logo">
                                                    <br>
                                                    <h3>Your verification code is:</h3>
                                                    <br>
                                                    <div style="background:#e3fffd; margin-left: 15%; margin-right: 15%; padding: 1% 0%; border-radius: 20px;">
                                                        <h1>${otp}</h1>
                                                    </div>
                                                </div>
                                                <br>
                                                <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                                <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>
                                                
                                                <div class="social-icons">
                                                    <!-- Add your social icons here using Font Awesome classes -->
                                                    <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                                    <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                                    <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                                    <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                                </div>
                                                <hr>
                                                <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                            </body>
                                        </html>`,
                                    });

                                    // console.log("Message sent: %s", info.messageId);
                                }

                                // console.log(`in line 126...`);
                                existingUser.otp_no = otp;
                                existingUser.otp_verify = 'No';
                                // existingUser.phone_uid = phone_uid;
                                existingUser.apps_data = apps_data;
                                existingUser.phone_uid = phone_uid;

                                await main();
                                await existingUser.save();
                                res.send({ "message": "Otp has been sent successfully!!", "email": lower_email, 'code': 200 });
                            } else {
                                // console.log(`in line 155....${JSON.stringify(existUser)}`)
                                const sign_count = existUser.signin_count
                                console.log(`in line 158......${sign_count}`)

                                console.log(`in line 437......`)
                                if (countDoc <= 2) {
                                    console.log(`in line 438....${countDoc}`)
                                    const transporter = nodemailer.createTransport({
                                        host: keys.host,
                                        port: keys.port,
                                        // ssl: false,
                                        ssl: true,
                                        // secure:true,
                                        auth: {
                                            user: keys.user,
                                            pass: keys.pass
                                        }
                                    });

                                    // Random Otp Generate Start----------------
                                    function between(min, max) {
                                        return Math.floor(Math.random() * (max - min + 1) + min);
                                    }
                                    var otp = between(100000, 999999);
                                    // Random Otp Generate End----------------
                                    if(lower_email === 'test@gmail.com'){
                                        console.log(`in testemail fucntion....`)
                                        var otp = 111111 
                                    }
                                    async function main() {
                                        const info = await transporter.sendMail({
                                            from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                                            to: lower_email,
                                            subject: `Your verification code for your ${apps_data}`,
                                            text: `${apps_data}`,
                                            html: `<!doctype html>
                                                <html>
                                                    <head>
                                                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                                        <!-- Add CSS styles for your email -->
                                                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                                        <style>
                                                            body {
                                                                font-family: sans-serif;
                                                                text-align: center;
                                                            }
                                                            .main {
                                                                display: block;
                                                                margin: auto;
                                                                max-width: 600px;
                                                            }
                                                            img {
                                                                max-width: 100%;
                                                                margin-top:8%;
                                                                height:10em;
                                                            }
                                                            .logo_img {
                                                                max-width: 90%;
                                                                margin-top:6%;
                                                                height:2em;
                                                            }
                                                            .social-icons img {
                                                                max-width: 80%;
                                                                height:24px;
                                                            }
                                                            h3 {
                                                                font-size: 18px;
                                                                font-weight: bold;
                                                                margin-top: 20px;
                                                                color: #0563aa;
                                                            }
                                                            h1 {
                                                                color: #0563aa;
                                                                letter-spacing: 2px;
                                                                font-size:3em;
                                                            }
                                                            p {
                                                                font-size: 12px;
                                                                color: #0563aa;
                                                            }
                                                            a{
                                                                color:#0563aa;
                                                            }
                                                            .social-icons {
                                                                color: #F4F6F6;
                                                            }
                                                            hr{
                                                                color:#DDF9F8;
                                                            }
                                                        </style>
                                                    </head>
                                                    <body style="text-align:center;">
                                                        <div class="main" >
                                                            <img src="https://gunjanappstudios.com/public/mail/toddler.png" alt="Logo">
                                                            <br>
                                                            <h3>Your verification code is:</h3>
                                                            <br>
                                                            <div style="background:#e3fffd; margin-left: 15%; margin-right: 15%; padding: 1% 0%; border-radius: 20px;">
                                                                <h1>${otp}</h1>
                                                            </div>
                                                        </div>
                                                        <br>
                                                        <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                                        <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>

                                                        <div class="social-icons">
                                                            <!-- Add your social icons here using Font Awesome classes -->
                                                            <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                                            <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                                            <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                                            <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                                        </div>
                                                        <hr>
                                                        <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                                    </body>
                                                </html>`,
                                        });

                                        // console.log("Message sent: %s", info.messageId);
                                    }

                                    // console.log(`in line 67...`);
                                    let newPerson = new User({
                                        email: lower_email,
                                        // phone_uid: phone_uid,
                                        otp_no: otp,
                                        otp_verify: 'No',
                                        login_count: 0,
                                        role_id: 8,
                                        signin_count: countDoc + 1,
                                        apps_data: apps_data,
                                        phone_uid: phone_uid
                                    });

                                    await main();
                                    await newPerson.save();
                                    res.send({ "message": "Otp has been sent successfully!!", "email": lower_email, 'code': 200 });
                                    // -----------------------Mail Function End--------------------
                                } else {
                                    // console.log(`in line 149...${countDoc}`)
                                    res.send({ "message": `Warning: Maximum Signin limit ${lower_email}'s 3 has been reached!!`, 'code': 429 });
                                }
                            }
                        }
                        // -----------------------Mail Function End--------------------
                    }
                }
            }
        } catch (error) {
            res.send({ "message": "An error occurred while checking the existing user.", "message": error, 'code': 500 });
        }

    }
    // -----------------------Otp Form Function end-----------------------------
    static async otpForm(req, res) {
        try {
            if (req.session.userId) {
                const data = await User.findOne({ _id: req.session.userId }).exec();
                res.send({ "message": "Already Logged In!", "data": data, 'code': 202 });
            } else {
                let { email, otp, phone_uid } = req.body;
                let lower_email = email.toLowerCase()
                const data = await User.findOne({ $and: [{ email: lower_email }, { phone_uid: phone_uid }] }).exec();
                if (data && data.otp_no == otp && data.otp_verify === 'No' && data.phone_uid == phone_uid) {
                    data.otp_verify = 'Yes';
                    data.login_count = (data.login_count || 0) + 1;
                    await data.save();
                    req.session.userId = data._id;
                    // ------------------------------------------------------------------------------------------------
                    const oneDayInMilliseconds = 1000 * 60 * 60 * 24 * 365; // One Year in milliseconds

                    const expirationTime = new Date(Date.now() + oneDayInMilliseconds);

                    const mSession = new M_session({
                        session: req.session.cookie,
                        user_id: req.session.userId,
                        expires: expirationTime.toISOString(),
                        expireAt: expirationTime
                    });

                    await mSession.save();

                    res.send({ "message": "Welcome to Dashboard!", "data": data, "session": req.session, "code": 200 });
                } else {
                    res.send({ "message": "Wrong Otp Or Already Verified!!", 'code': 400 });
                }
            }
        } catch (err) {
            res.send({ "message": "An error occurred while processing the request.", "data": err, "code": 500 });
        }
    }

    // -----------------------Otp Form Function end-----------------------------
    // -----------------------Profile Page access start-----------------------------
    static async profile(req, res) {
        try {
            if (!req.body.session.userId) {
                // User is not logged in, send an error response
                return res.send({ "message": 'You have no access for getting this page. Please login and try!!', "code": 401 });
            }
            const session_data = await M_session.findOne({ user_id: req.body.session.userId }).exec();
            console.log(`in profile function...'s ${JSON.stringify(session_data)}`)
            if (!session_data) {
                // Profile data not found, send an error response
                return res.send({ "message": 'Please Sign in!!', 'data': null, 'code': 204 });
            }
            // User is logged in, fetch profile data
            const data = await User.findOne({ _id: req.body.session.userId }).exec();

            // Send the profile data in the success response
            res.send({ "message": 'Data has been sent successfully!!', 'data': data, 'code': 200 });
        } catch (err) {
            // Handle any errors that occur during the data retrieval process
            res.send({ "message": 'An error occurred while fetching the data.', 'data': err, 'code': 500 });
        }
    }

    // -----------------------Profile Page access end-----------------------------

    // -----------------------Profile Update function start-----------------------------
    static async profileUpdate(req, res) {
        try {
            if (!req.body.session.userId) {
                // User is not logged in, send an error response
                return res.send({ "message": 'You have no access for updating this profile. Please login and try!!', 'code': 401 });
            }

            // User is logged in, fetch profile data
            // const profile_data = await User.findOne({ _id: req.body.session.userId }).exec();
            const session_data = await M_session.findOne({ user_id: req.body.session.userId }).exec();
            console.log(`in `)
            if (!session_data) {
                // Profile data not found, send an error response
                return res.send({ "message": 'Please Sign in!!', 'data': null, 'code': 401 });
            }
            const profile_data = await User.findOne({ _id: req.body.session.userId }).exec();
            // Check if the fields are provided in the request body before updating
            let { country, ad_remove, app_language, child_age, child_name } = req.body;
            if (country) profile_data.country = country;
            if (ad_remove) profile_data.ad_remove = ad_remove;
            if (app_language) profile_data.app_language = app_language;
            if (child_age) profile_data.child_age = child_age;
            if (child_name) profile_data.child_name = child_name;

            // Save the updated profile data
            await profile_data.save();
            res.send({ "message": 'Profile has been updated successfully!!', 'data': profile_data, 'code': 200 });
        } catch (err) {
            // Handle any errors that occur during the data retrieval or update process
            res.send({ "message": 'An error occurred while updating the profile.', 'data': err, 'code': 500 });
        }
    }

    // -----------------------Profile Update function End-----------------------------
    static async logout(req, res, next) {
        try {
            const { userId } = req.body;

            if (userId) {
                const user = await User.findOne({ _id: userId }).exec();
                // console.log(`in line 570..........${JSON.stringify(user)}`)
                if (user) {
                    const document = await Document.findOne({ email: user.email }).exec();
                    // console.log(`in line 573.....${JSON.stringify(document)}`)
                    if (document && document.document_verify == 'Reject') {
                        const sessionDeletion = await M_session.deleteOne({ user_id: userId });

                        if (sessionDeletion.deletedCount === 1) {
                            // console.log(`in line 578.....`)
                            req.session.destroy(async (err) => {
                                if (err) {
                                    return next(err);
                                } else {
                                    await User.deleteOne({ _id: userId });
                                    res.send({ "message": "Logout Successfully...", 'data': sessionDeletion, 'code': 200 });

                                }
                            });
                        } else {
                            res.send({ "message": "Already Logout!!", 'code': 401 });
                        }
                    } else {
                        req.session.destroy(async (err) => {
                            if (err) {
                                return next(err);
                            } else {
                                const sessionDeletion = await M_session.deleteOne({ user_id: userId });
                                if (user.role_id == 8) {
                                    await User.deleteOne({ _id: userId });
                                    res.send({ "message": "Logout Successfully...", 'data': sessionDeletion, 'code': 200 });
                                } else {
                                    res.send({ "message": "Logout Successfully...", 'data': sessionDeletion, 'code': 200 });
                                }
                            }
                        });
                    }
                } else {
                    res.send({ "message": "User not found.", 'code': 404 });
                }
            } else {
                res.send({ "message": "Missing userId.", 'code': 400 });
            }
        } catch (error) {
            console.error('An error occurred:', error);
            res.send({ "message": "An internal server error occurred.", 'data': error, "code": 500 });
        }
    }


    // -----------------------Teacher Signin Function Start ---------------------------------

    static async teacherSignIn(req, res) {
        try {
            // console.log(`in submitForm... ${JSON.stringify(req.body)}`)
            const { name, email, apps_data, phone_uid } = req.body;
            let lower_email = email.toLowerCase()
            if (lower_email == '' || phone_uid == '' || lower_email == null || phone_uid == null) {
                res.send({ "message": 'Please enter all fields', 'code': 204 });
            } else {

                let existingUser = await User.findOne({ email: lower_email });
                // let sameUser = await User.findOne($and[{ email: lower_email },{phone_uid:phone_uid}]);
                if (!existingUser) {
                    // ---------------------Mail Function Started------------------------
                    // console.log(`in line 22 |... ${keys.host}`);
                    const transporter = nodemailer.createTransport({
                        host: keys.host,
                        port: keys.port,
                        // ssl: false,
                        ssl: true,
                        // secure:true,
                        auth: {
                            user: keys.user,
                            pass: keys.pass
                        }
                    });

                    // Random Otp Generate Start----------------
                    function between(min, max) {
                        return Math.floor(Math.random() * (max - min + 1) + min);
                    }
                    var otp = between(100000, 999999);
                    // Random Otp Generate End----------------
                    async function main() {
                        const info = await transporter.sendMail({
                            from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                            to: lower_email,
                            subject: `Your verification code for your ${apps_data}`,
                            text: `${apps_data}`,
                            html: `<!doctype html>
                                <html>
                                    <head>
                                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                        <!-- Add CSS styles for your email -->
                                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                        <style>
                                            body {
                                                font-family: sans-serif;
                                                text-align: center;
                                            }
                                            .main {
                                                display: block;
                                                margin: auto;
                                                max-width: 600px;
                                            }
                                            img {
                                                max-width: 100%;
                                                margin-top:8%;
                                                height:10em;
                                            }
                                            .logo_img {
                                                max-width: 90%;
                                                margin-top:6%;
                                                height:2em;
                                            }
                                            .social-icons img {
                                                max-width: 80%;
                                                height:24px;
                                            }
                                            h3 {
                                                font-size: 18px;
                                                font-weight: bold;
                                                margin-top: 20px;
                                                color: #0563aa;
                                            }
                                            h1 {
                                                color: #0563aa;
                                                letter-spacing: 2px;
                                                font-size:3em;
                                            }
                                            p {
                                                font-size: 12px;
                                                color: #0563aa;
                                            }
                                            a{
                                                color:#0563aa;
                                            }
                                            .social-icons {
                                                color: #F4F6F6;
                                            }
                                            hr{
                                                color:#DDF9F8;
                                            }
                                        </style>
                                    </head>
                                    <body style="text-align:center;">
                                        <div class="main" >
                                            <img src="https://gunjanappstudios.com/public/mail/toddler.png" alt="Logo">
                                            <br>
                                            <br>
                                            <div style="background:#e3fffd; margin-left: 15%; margin-right: 15%; padding: 1% 0%; border-radius: 20px;">
                                                <h1>${otp}</h1>
                                            </div>
                                        </div>
                                        <br>
                                        <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                        <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>
                                        
                                        <div class="social-icons">
                                            <!-- Add your social icons here using Font Awesome classes -->
                                            <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                            <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                            <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                            <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                        </div>
                                        <hr>
                                        <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                    </body>
                                </html>`,
                        });

                        // console.log("Message sent: %s", info.messageId);
                    }
                    let newPerson = new User({
                        name: name,
                        email: lower_email,
                        otp_no: otp,
                        otp_verify: 'No',
                        login_count: 0,
                        role_id: 6,
                        apps_data: apps_data,
                        phone_uid: phone_uid
                    });
                    await main();
                    await newPerson.save();
                    res.send({ "message": "Mail has been sent successfully!!", "email": lower_email, 'code': 200 });
                    // -----------------------Mail Function End--------------------
                } else {
                    if (existingUser.role_id == 8) {
                        res.send({ "message": "Email Already registered as Parent!!", "data": null, 'code': 204 });
                    } else {
                        // -----------------------Mail Function End--------------------
                        let login_user = await M_session.find({ user_id: existingUser._id }).exec();
                        if (login_user.length > 0) {
                            res.send({ "message": "Already Logged In!", "data": existingUser, 'code': 202 });
                        } else {
                            const transporter = nodemailer.createTransport({
                                host: keys.host,
                                port: keys.port,
                                // ssl: false,
                                ssl: true,
                                // secure:true,
                                auth: {
                                    user: keys.user,
                                    pass: keys.pass
                                }
                            });

                            // Random Otp Generate Start----------------
                            function between(min, max) {
                                return Math.floor(Math.random() * (max - min + 1) + min);
                            }
                            var otp = between(100000, 999999);
                            // Random Otp Generate End----------------
                            async function main() {
                                const info = await transporter.sendMail({
                                    from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                                    to: lower_email,
                                    subject: `Your verification code for your ${apps_data}`,
                                    text: `${apps_data}`,
                                    html: `<!doctype html>
                                                <html>
                                                    <head>
                                                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                                        <!-- Add CSS styles for your email -->
                                                        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                                        <style>
                                                            body {
                                                                font-family: sans-serif;
                                                                text-align: center;
                                                            }
                                                            .main {
                                                                display: block;
                                                                margin: auto;
                                                                max-width: 600px;
                                                            }
                                                            img {
                                                                max-width: 100%;
                                                                margin-top:8%;
                                                                height:10em;
                                                            }
                                                            .logo_img {
                                                                max-width: 90%;
                                                                margin-top:6%;
                                                                height:2em;
                                                            }
                                                            .social-icons img {
                                                                max-width: 80%;
                                                                height:24px;
                                                            }
                                                            h3 {
                                                                font-size: 18px;
                                                                font-weight: bold;
                                                                margin-top: 20px;
                                                                color: #0563aa;
                                                            }
                                                            h1 {
                                                                color: #0563aa;
                                                                letter-spacing: 2px;
                                                                font-size:3em;
                                                            }
                                                            p {
                                                                font-size: 12px;
                                                                color: #0563aa;
                                                            }
                                                            a{
                                                                color:#0563aa;
                                                            }
                                                            .social-icons {
                                                                color: #F4F6F6;
                                                            }
                                                            hr{
                                                                color:#DDF9F8;
                                                            }
                                                        </style>
                                                    </head>
                                                    <body style="text-align:center;">
                                                        <div class="main" >
                                                            <img src="https://gunjanappstudios.com/public/mail/toddler.png" alt="Logo">
                                                            <br>
                                                            <br>
                                                            <div style="background:#e3fffd; margin-left: 15%; margin-right: 15%; padding: 1% 0%; border-radius: 20px;">
                                                                <h1>${otp}</h1>
                                                            </div>
                                                        </div>
                                                        <br>
                                                        <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                                        <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>

                                                        <div class="social-icons">
                                                            <!-- Add your social icons here using Font Awesome classes -->
                                                            <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                                            <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                                            <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                                            <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                                        </div>
                                                        <hr>
                                                        <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                                    </body>
                                                </html>`,
                                });

                                // console.log("Message sent: %s", info.messageId);
                            }
                            if (phone_uid) existingUser.phone_uid = phone_uid;
                            existingUser.otp_no = otp;
                            existingUser.otp_verify = 'No';
                            await main();
                            await existingUser.save();
                            res.send({ "message": "Otp has been sent successfully!!", "email": lower_email, 'code': 200 });
                            // -----------------------Mail Function End--------------------
                        }
                        // -----------------------Mail Function End--------------------
                    }
                }
            }
        } catch (error) {
            res.send({ "message": "An error occurred while checking the existing user.", "message": error, 'code': 500 });
        }
    }
    // -----------------------Teacher Signin Function End -----------------------------------
    // -----------------------Teacher otpVerify Function Start -----------------------------------
    static async otpVerify(req, res) {
        try {
            let { email, otp, phone_uid } = req.body;
            let lower_email = email.toLowerCase();

            const user = await User.findOne({ email: lower_email, phone_uid: phone_uid }).exec();
            if (!user) {
                res.send({ "message": "User not found.", 'code': 404 });
                return;
            }

            const sessionData = await M_session.findOne({ user_id: user._id }).exec();

            if (sessionData) {
                const userData = await User.findOne({ _id: sessionData.user_id }).exec();
                let document = await Document.findOne({ email: userData.email }).exec();

                if (!document || !document.document_name || !document.document_obj) {
                    const transporter = nodemailer.createTransport({
                        host: keys.host,
                        port: keys.port,
                        // ssl: false,
                        ssl: true,
                        // secure:true,
                        auth: {
                            user: keys.user,
                            pass: keys.pass
                        }
                    });

                    // Random Otp Generate Start----------------
                    function between(min, max) {
                        return Math.floor(Math.random() * (max - min + 1) + min);
                    }
                    // Random Otp Generate End----------------

                    res.send({ "message": "Please Upload Your Document!", "data": user, "session": req.session, "code": 202 });
                } else {
                    if (document.document_verify === 'Yes') {
                        res.send({ "message": "Welcome to Dashboard!", "data": user, "session": req.session, "code": 200 });
                    } else if (document.document_verify === 'Reject') {
                        res.send({ "message": "Your Document has been Rejected!!", "data": user, "session": req.session, "code": 403 });
                    } else {
                        res.send({ "message": "Document already Submitted!! Please Wait for Confirmation...", "data": user, "session": req.session, "code": 203 });
                    }
                }
                // res.send({ "message": "Already Logged In!", "data": userData, 'code': 202 });
            } else {
                if (user.otp_no == otp && user.otp_verify === 'No') {
                    user.otp_verify = 'Yes';
                    user.login_count = (user.login_count || 0) + 1;
                    await user.save();

                    req.session.userId = user._id;

                    const oneDayInMilliseconds = 1000 * 60 * 60 * 24 * 365; // One Year in milliseconds
                    const expirationTime = new Date(Date.now() + oneDayInMilliseconds);

                    const mSession = new M_session({
                        session: req.session.cookie,
                        user_id: req.session.userId,
                        expires: expirationTime.toISOString(),
                        expireAt: expirationTime
                    });

                    await mSession.save();

                    // Assuming Document is correctly defined and imported
                    let document = await Document.findOne({ email: user.email }).exec();

                    if (!document || !document.document_name || !document.document_obj) {
                        const transporter = nodemailer.createTransport({
                            host: keys.host,
                            port: keys.port,
                            // ssl: false,
                            ssl: true,
                            // secure:true,
                            auth: {
                                user: keys.user,
                                pass: keys.pass
                            }
                        });

                        // Random Otp Generate Start----------------
                        function between(min, max) {
                            return Math.floor(Math.random() * (max - min + 1) + min);
                        }
                        // Random Otp Generate End----------------

                        res.send({ "message": "Please Upload Your Document!", "data": user, "session": req.session, "code": 202 });
                    } else {
                        if (document.document_verify === 'Yes') {
                            res.send({ "message": "Welcome to Dashboard!", "data": user, "session": req.session, "code": 200 });
                        } else if (document.document_verify === 'Reject') {
                            res.send({ "message": "Your Document has been Rejected!!", "data": user, "session": req.session, "code": 403 });
                        } else {
                            res.send({ "message": "Document already Submitted!! Please Wait for Confirmation...", "data": user, "session": req.session, "code": 203 });
                        }
                    }
                } else {
                    res.send({ "message": "Wrong Otp Or Already Verified!!", 'code': 400 });
                }
            }
        } catch (err) {
            res.send({ "message": "An error occurred while processing the request.", "data": err, "code": 500 });
        }
    }


    // -----------------------Teacher otpVerify Function End -----------------------------------
    // -----------------------Teacher uploadDocument Function Start -----------------------------------
    static async uploadDocument(req, res) {
        try {
            const { email, document_obj, document_name } = req.body;
            // const emailUser = await User.findOne({ $and:{email: email, role_id:6} }).exec();
            const emailUser = await User.findOne({ $and: [{ email: email, role_id: 6 }] }).exec();

            if (!emailUser) {
                return res.send({ 'message': 'Unauthorized: Please log in to access this page.', 'code': 401 });
            }

            const sessionData = await M_session.findOne({ user_id: emailUser._id }).exec();
            if (!sessionData) {
                return res.send({ "message": 'Please Sign in!!', 'data': null, 'code': 401 });
            }

            let existgame = await Document.findOne({ email: email }).exec();

            if (!existgame) {
                console.log(`in line 120......`);
                let imgAud = new Document({
                    email: email,
                    document_obj: document_obj,
                    document_name: document_name,
                    document_verify: 'No'
                });

                // Decode Base64 data and save to the server (if needed)
                if (document_obj) {
                    // Validate the file type and content before saving
                    const imgBuffer = Buffer.from(document_obj, 'base64');
                    const imgFileName = document_name; // Define a filename or generate one dynamically
                    const imgFilePath = `${fileSavePath}/${imgFileName}`;

                    // Save the imgBuffer to the specified path
                    fs.writeFileSync(imgFilePath, imgBuffer);
                }
                const transporter = nodemailer.createTransport({
                    host: keys.host,
                    port: keys.port,
                    // ssl: false,
                    ssl: true,
                    // secure:true,
                    auth: {
                        user: keys.user,
                        pass: keys.pass
                    }
                });

                // Random Otp Generate Start----------------
                function between(min, max) {
                    return Math.floor(Math.random() * (max - min + 1) + min);
                }
                // Random Otp Generate End----------------
                async function main() {
                    const info = await transporter.sendMail({
                        from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                        to: emailUser.email,
                        subject: `Thank You for Your Access Request - Pending Verification!`,
                        text: `${emailUser.apps_data}`,
                        html: `<!doctype html>
                                    <html>
                                        <head>
                                            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                            <!-- Add CSS styles for your email -->
                                            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                            <style>
                                                body {
                                                    font-family: sans-serif;
                                                    
                                                }
                                                .main {
                                                    display: block;
                                                    margin: auto;
                                                    max-width: 600px;
                                                }
                                                h3 {
                                                    font-size: 18px;
                                                    font-weight: bold;
                                                    margin-top: 20px;
                                                    color: #0563aa;
                                                }
                                                h1 {
                                                    color: #0563aa;
                                                    letter-spacing: 2px;
                                                    font-size:3em;
                                                }
                                                p {
                                                    font-size: 12px;
                                                    color: #0563aa;
                                                }
                                                .social-icons img {
                                                    max-width: 80%;
                                                    height:24px;
                                                }
                                            </style>
                                        </head>
                                        <body>
                                            <div class="main" >
                                                <h3>Dear ${emailUser.name} ,</h3>
                                                <h4>I hope this email finds you well. Thank you for your recent submission of identification documents for access to ElePant World app. We appreciate your interest and dedication to being a part of our educational community.</h4>
                                                <h4>Your submitted identification documents are currently under review by our team. Please allow us a short period to carefully verify the information provided. We understand the importance of a swift response and will make every effort to expedite this process.</h4>
                                                
                                                <h4>If the ID is found to be valid, you will receive a subsequent email confirming your access to ElePant World app. In the meantime, we invite you to explore our available free content. We believe that even in the absence of full access, you'll find valuable resources that can enhance your teaching experience.</h4>
                                                
                                                <h4>We understand the anticipation and are committed to keeping you informed throughout this process. If you have any questions or concerns, please do not hesitate to reach out to our support team at  support@gunjanappstudios.com.</h4>
                                                <h4>Thank you for your patience and understanding as we work to ensure the security and integrity of our platform.
                                                </h4>
                                                <h4>Best regards,<br>Support Team<br>GunjanApps Studios</h4>
                                                <br>
                                                <div style="text-align:center;">
                                                    <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                                    <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>
                                                    
                                                    <div class="social-icons">
                                                        <!-- Add your social icons here using Font Awesome classes -->
                                                        <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                                        <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                                        <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                                        <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                                    </div>
                                                    <hr>
                                                    <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                                </div>
                                            </div>
                                        </body>
                                    </html>`,
                    });

                    // console.log("Message sent: %s", info.messageId);
                }
                await main();
                await imgAud.save();
                res.send({ 'message': "Document has been saved successfully!! Please Wait for Confirmation...", "data": imgAud, "code": 200 });
            } else {
                console.log(`in line 152......`);
                if (document_obj) {
                    existgame.document_obj = document_obj;

                    // Decode Base64 data and save to the server (if needed)
                    const imgBuffer = Buffer.from(document_obj, 'base64');
                    const imgFileName = document_name;
                    const imgFilePath = `${fileSavePath}/${imgFileName}`;

                    // Save the imgBuffer to the specified path
                    fs.writeFileSync(imgFilePath, imgBuffer);
                }

                if (document_name) existgame.document_name = document_name;
                existgame.document_verify = 'No'
                await existgame.save();
                res.send({ 'message': 'Document has been updated successfully!! Please Wait for Confirmation...', 'data': existgame, "code": 200 });
            }
        } catch (error) {
            // Handle errors appropriately
            console.error('An error occurred:', error);
            res.send({ 'message': 'An internal server error occurred.', 'data': error, "code": 500 });
        }
    }

    // -----------------------Teacher uploadDocument Function End -----------------------------------
    // -----------------------Teacher documentStatus Function Start -----------------------------------
    static async documentStatus(req, res) {
        try {
            let { email, phone_uid } = req.body;
            let lower_email = email.toLowerCase();

            const user = await User.findOne({ email: lower_email }).exec();
            if (!user) {
                res.send({ "message": "User not found.", 'code': 404 });
                return;
            }

            const sessionData = await M_session.findOne({ user_id: user._id }).exec();

            if (sessionData) {
                const userData = await User.findOne({ _id: sessionData.user_id }).exec();
                let document = await Document.findOne({ email: userData.email }).exec();

                if (!document || !document.document_name || !document.document_obj) {
                    const transporter = nodemailer.createTransport({
                        host: keys.host,
                        port: keys.port,
                        // ssl: false,
                        ssl: true,
                        // secure:true,
                        auth: {
                            user: keys.user,
                            pass: keys.pass
                        }
                    });

                    // Random Otp Generate Start----------------
                    function between(min, max) {
                        return Math.floor(Math.random() * (max - min + 1) + min);
                    }
                    // Random Otp Generate End----------------

                    res.send({ "message": "Please Upload Your Document!", "data": user, "session": req.session, "code": 202 });
                } else {
                    if (document.document_verify === 'Yes') {
                        res.send({ "message": "Welcome to Dashboard!", "data": user, "session": req.session, "code": 200 });
                    } else if (document.document_verify === 'Reject') {
                        res.send({ "message": "Your Document has been Rejected!!", "data": user, "session": req.session, "code": 403 });
                    } else {
                        res.send({ "message": "Document already Submitted!! Please Wait for Confirmation...", "data": user, "session": req.session, "code": 203 });
                    }
                }
            } else {
                res.send({ "message": "Please Login to Get Access This Page", "data": null, "code": 204 });
            }
        } catch (err) {
            res.send({ "message": "An error occurred while processing the request.", "data": err, "code": 500 });
        }
    }
    // -----------------------Teacher documentStatus Function End -----------------------------------
    // -----------------------Teacher documentVerify Function Start -----------------------------------
    static async documentVerify(req, res) {
        try {
            const { email, document_verify, status_code } = req.body;

            if (document_verify !== "admin_security_code") {
                res.send({ 'message': 'You Have No Access !!', 'data': null, "code": 403 });
                return;
            }

            const emailUser = await User.findOne({ $and: [{ email: email, role_id: 6 }] }).exec();
            if (!emailUser) {
                return res.send({ 'message': 'User Not Available.', 'code': 401 });
            }

            let existdoc = await Document.findOne({ $and: [{ email: email, document_verify: 'No' }] }).exec();
            let existgame = await Document.findOne({ $and: [{ email: email, document_verify: 'Yes' }] }).exec();
            let rejectDoc = await Document.findOne({ $and: [{ email: email, document_verify: 'Reject' }] }).exec();

            if (existgame) {
                res.send({ 'message': "Document Already Verified!!", "data": existgame, "code": 200 });
            } else if (rejectDoc) {
                res.send({ 'message': "Document Rejected!!", "data": rejectDoc, "code": 403 });
            } else {
                if (status_code === 1) {
                    const transporter = nodemailer.createTransport({
                        host: keys.host,
                        port: keys.port,
                        // ssl: false,
                        ssl: true,
                        // secure:true,
                        auth: {
                            user: keys.user,
                            pass: keys.pass
                        }
                    });

                    // Random Otp Generate Start----------------
                    function between(min, max) {
                        return Math.floor(Math.random() * (max - min + 1) + min);
                    }
                    var otp = between(100000, 999999);
                    // Random Otp Generate End----------------
                    async function main() {
                        const info = await transporter.sendMail({
                            from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                            to: emailUser.email,
                            subject: `Welcome to ElePant World – Your Free Premium Access Has Been Granted!`,
                            text: `${emailUser.apps_data}`,
                            html: `<!doctype html>
                                        <html>
                                            <head>
                                                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                                <!-- Add CSS styles for your email -->
                                                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                                <style>
                                                    body {
                                                        font-family: sans-serif;
                                                        
                                                    }
                                                    .main {
                                                        display: block;
                                                        margin: auto;
                                                        max-width: 600px;
                                                    }
                                                    h3 {
                                                        font-size: 18px;
                                                        font-weight: bold;
                                                        margin-top: 20px;
                                                        color: #0563aa;
                                                    }
                                                    h1 {
                                                        color: #0563aa;
                                                        letter-spacing: 2px;
                                                        font-size:3em;
                                                    }
                                                    p {
                                                        font-size: 12px;
                                                        color: #0563aa;
                                                    }
                                                    .social-icons img {
                                                        max-width: 80%;
                                                        height:24px;
                                                    }
                                                </style>
                                            </head>
                                            <body>
                                                <div class="main" >
                                                    <h3>Dear ${emailUser.name} ,</h3>
                                                    <h4>We hope this message finds you well and filled with excitement for the upcoming academic journey. </h4>
                                                    <h4>As a token of our appreciation for your invaluable role in shaping the minds of tomorrow, we are delighted to offer you complimentary FREE access to our premium content in ElePant World. Dive into a world of boundless knowledge, exclusive resources, and innovative tools designed to empower and inspire both you and your students.</h4>
                                                    
                                                    <h4>Your dedication to education has not gone unnoticed, and we believe that together, we can create an enriching learning environment. If you have any questions, feedback, or suggestions, our team is here to assist you every step of the way.</h4>
                                                    
                                                    <h4>Thank you for being a part of the ElePant community. We look forward to embarking on this educational journey with you.</h4>
                                                    <h4>Best regards,<br>Gunjan<br>Co-Founder<br>GunjanApps Studios</h4>
                                                    <br>
                                                    <div style="text-align:center;">
                                                        <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                                        <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>
                                                        
                                                        <div class="social-icons">
                                                            <!-- Add your social icons here using Font Awesome classes -->
                                                            <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                                            <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                                            <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                                            <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                                        </div>
                                                        <hr>
                                                        <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                                    </div>
                                                </div>
                                            </body>
                                        </html>`,
                        });

                        // console.log("Message sent: %s", info.messageId);
                    }
                    existdoc.document_verify = 'Yes'
                    await main();
                    await existdoc.save();
                    res.send({ 'message': 'Document has been Verified successfully!!', 'data': existdoc, "code": 200 });
                } else {
                    const transporter = nodemailer.createTransport({
                        host: keys.host,
                        port: keys.port,
                        // ssl: false,
                        ssl: true,
                        // secure:true,
                        auth: {
                            user: keys.user,
                            pass: keys.pass
                        }
                    });
                    // Random Otp Generate Start----------------
                    function between(min, max) {
                        return Math.floor(Math.random() * (max - min + 1) + min);
                    }
                    var otp = between(100000, 999999);
                    // Random Otp Generate End----------------
                    async function main() {
                        const info = await transporter.sendMail({
                            from: '"Gunjan Apps" <noreply@gunjanappstudios.com>',
                            to: emailUser.email,
                            subject: `Access Request Update - Additional Information Required!`,
                            text: `${emailUser.apps_data}`,
                            html: `<!doctype html>
                                        <html>
                                            <head>
                                                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                                                <!-- Add CSS styles for your email -->
                                                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
                                                <style>
                                                    body {
                                                        font-family: sans-serif;
                                                        
                                                    }
                                                    .main {
                                                        display: block;
                                                        margin: auto;
                                                        max-width: 600px;
                                                    }
                                                    h3 {
                                                        font-size: 18px;
                                                        font-weight: bold;
                                                        margin-top: 20px;
                                                        color: #0563aa;
                                                    }
                                                    h1 {
                                                        color: #0563aa;
                                                        letter-spacing: 2px;
                                                        font-size:3em;
                                                    }
                                                    p {
                                                        font-size: 12px;
                                                        color: #0563aa;
                                                    }
                                                    .social-icons img {
                                                        max-width: 80%;
                                                        height:24px;
                                                    }
                                                </style>
                                            </head>
                                            <body>
                                                <div class="main" >
                                                    <h3>Dear ${emailUser.name} ,</h3>
                                                    <h4>I trust this email finds you well. Thank you for your interest in ElePant World and for submitting your identification documents for access verification.</h4>
                                                    <h4>After careful review, we regret to inform you that the ID proof submitted does not meet our validation criteria. We understand the importance of providing a seamless and secure experience for all our users, and unfortunately, the document provided does not match our required standards.</h4>
                                                    
                                                    <h4>To proceed with your access request, we kindly request you to submit a valid and recognized form of identification, which can clearly show your school name and a valid teacher ID number.</h4>
                                                    
                                                    <h4>We understand that this may be an inconvenience, and we appreciate your understanding as we work to maintain the security and integrity of our platform.</h4>
                                                    <h4>Once you have the necessary information ready, please resubmit your identification documents through our apps settings section. If you encounter any challenges or have questions, feel free to reach out to our support team at support@gunjanappstudios.com.</h4>
                                                    <h4>Thank you for your understanding, and we look forward to assisting you further in gaining access to ElePant World app.</h4>
                                                    <h4>Best regards,<br>Support Team<br>GunjanApps Studios</h4>
                                                    <br>
                                                    <div style="text-align:center;">
                                                        <img class="logo_img" src="https://gunjanappstudios.com/public/mail/logo.png" alt="Logo">
                                                        <p>Please do not reply to this email. Emails sent to this address will not be answered. If you have any questions, <a href="https://gunjanappstudios.com/contact">Contact Us</a>.</p>
                                                        
                                                        <div class="social-icons">
                                                            <!-- Add your social icons here using Font Awesome classes -->
                                                            <a href="https://www.linkedin.com/company/gunjanappstudios/"><img src="https://gunjanappstudios.com/public/mail/linkedin.png"></a>
                                                            <a href="https://www.youtube.com/c/KidsEducationalTV/"><img src="https://gunjanappstudios.com/public/mail/yt.png"></a>
                                                            <a href="https://www.instagram.com/gunjanapps_studios/"><img src="https://gunjanappstudios.com/public/mail/insta.png"></a>
                                                            <a href="https://www.facebook.com/gunjanappsstudios"><img src="https://gunjanappstudios.com/public/mail/fb.png"></a>
                                                        </div>
                                                        <hr>
                                                        <a href="https://gunjanappstudios.com/privacy-policy/#privacy-policy">Privacy Policy</a>
                                                    </div>
                                                </div>
                                            </body>
                                        </html>`,
                        });

                        // console.log("Message sent: %s", info.messageId);
                    }
                    existdoc.document_verify = 'Reject';
                    await main();
                    await existdoc.save();
                    res.send({ 'message': 'Document has been Rejected successfully!!', 'data': existdoc, "code": 200 });
                }
            }
        } catch (error) {
            // Handle errors appropriately
            console.error('An error occurred:', error);
            res.send({ 'message': 'An internal server error occurred.', 'data': error, "code": 500 });
        }
    }
    // -----------------------Teacher documentVerify Function End -----------------------------------
    // -----------------------Teacher documentFetch Function Start -----------------------------------
    static async documentFetch(req, res) {
        try {
            const { email, document_verify } = req.body;

            if (document_verify !== "admin_security_code_fetch") {
                res.send({ 'message': 'You Have No Access !!', 'data': null, "code": 403 });
                return;
            }

            const emailUser = await User.findOne({ $and: [{ email: email, role_id: 6 }] }).exec();
            if (!emailUser) {
                return res.send({ 'message': 'User Not Available.', 'code': 401 });
            }

            let existdoc = await Document.findOne({ $and: [{ email: email }] }).exec();

            if (existdoc) {
                res.send({ 'message': "Document has been sent successfully!!", "data": existdoc, "code": 200 });
            } else {
                res.send({ 'message': "Document Not Available!!", "data": null, "code": 200 });
            }
        } catch (error) {
            console.error('An error occurred:', error);
            res.send({ 'message': 'An internal server error occurred.', 'data': error, "code": 500 });
        }
    }
    // -----------------------Teacher documentFetch Function End -----------------------------------

}

module.exports = userController

