const db = require('../utils/db.js');
const bcrypt = require('bcryptjs')
const Jwt = require('jsonwebtoken')


// import controller function

const gets = async(req, res, next)=>{
    try {
        const userid = req.userid;
        const sql = `SELECT * FROM admin WHERE id != ?`;
        db.query(sql, [userid], (err, ress)=>{
            if(err) return res.status(400).json({message:err})
            if(ress.length===0) return res.status(400).json({message:'access list is empty!'})
            res.status(200).json({message:'get', data:ress})
        })
    } catch (error) {
        next(error)
    }
}
// dashboard
const dashboard = async(req, res, next)=>{
    try {
        const sql1 = `SELECT COUNT(id) AS total_exam FROM exam`;
        const sql2 = `SELECT COUNT(id) AS total_class FROM classes`;
        const sql3 = `SELECT COUNT(id) AS total_student FROM students`;
        const sql4 = `SELECT COUNT(id) AS total_admin FROM admin`;
        db.query(sql1, (er1,ress1)=>{
        db.query(sql2, (er2,ress2)=>{
        db.query(sql3, (er3,ress3)=>{
        db.query(sql4, (er4,ress4)=>{
        if(er1 || er2 || er3 || er4) return res.status(400).json({message:'Somthing went wrong!'})
          const data = {
            exam:ress1[0].total_exam,
            class:ress2[0].total_class,
            student:ress3[0].total_student,
            admin:ress4[0].total_admin,
          }
          res.status(200).json({message:'success', data})
        })
        })
        })
        })
    } catch (error) {
        next(error)
    }
}
// update admin
const updateadminprofile = async(req, res, next)=>{
    const id = req.userid;
    const {name, phone} = req.body;
    const filename = req.filename ? req.filename : null;
    const update = `UPDATE admin SET name = ?, avater = ?, phone = ? WHERE id = ?`;
    try {
        // name, phone, avater.
        db.query(update, [name, filename, phone, id], (err,result)=>{
            if(err) return res.status(400).json({message:err})
            res.status(200).json({message:'Profile is updated.'})
        })
    } catch (error) {
        next(error)
    }
}
const updateadminpassword = async(req, res, next)=>{
    const id = req.userid;
    const {oldpassword, newpassword} = req.body
    // check oldpassword.
    const check = `SELECT password FROM admin WHERE id = ?`;
    const update = `UPDATE admin SET password = ? WHERE id = ?`;
    try {
        db.query(check, [id], async(err1,result1)=>{
            const isPasswordValid = await bcrypt.compare(oldpassword, result1[0].password);
            if (!isPasswordValid) {
              return res.status(401).json({ message: 'Invalid your old password!'});
            }
        // new password
        const hashedPassword = await bcrypt.hash(newpassword, 10);
        db.query(update, [hashedPassword, id], (err, result2)=>{
            if(err) return res.status(400).json({message:err})
            res.status(200).json({message:'Password is successfully updated.'})
        })
        });
    } catch (error) {
        next(error)
    }
}

const register = async(req, res, next)=>{
    try {
        const {name, phone, password, role} = req.body
        const hashedPassword = await bcrypt.hash(password, 10);
        const check = `SELECT * FROM admin WHERE phone = ?`;
        const register = `INSERT INTO admin (name,avater,phone, password,role,token,status) VALUES(?,?,?,?,?,?,?)`;
        db.query(check, [phone], (err, result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length > 0){
            return res.status(400).json({message:'Admin account is alredy exits!'})
            }
            // all right. generate token, password encode.
            db.query(register, [name, ' ', phone, hashedPassword, role, ' ','1'], (err2, result2)=>{
                if(err2) return res.status(400).json({message:err2})
                res.status(201).json({message:'Access is created.', token:null}) 
            });
        }); 
    } catch (error) {
        next(error)
    }
}


const login = async(req, res, next)=>{
    const {phone, password} = req.body
    const check = `SELECT * FROM admin WHERE phone = ?`;
    try {
        db.query(check, [phone], async(err, result)=>{
            if(err) return res.status(400).json({message:err})
            if(result.length < 1){
                return res.status(401).json({message:'Invalid phone number'})
            }
            // compare password.
            const isPasswordValid = await bcrypt.compare(password, result[0].password);
            if (!isPasswordValid) {
              return res.status(401).json({ message: 'Invalid phone number or password!'});
            }
                // credential matched.
                const token = Jwt.sign(
                    {id:result[0].id, name:result[0].name, phone:result[0].phone},
                    process.env.JWT_SECRET_USER,
                    {expiresIn: process.env.JWT_EXPIRES_USER}
                ); // assigned userId, userPhone and userRole.
                res.status(200).json({message:'credential matched.', token:token})
        })
    } catch (error) {
        next(error)
    }
}

const details = async(req, res, next)=>{
    try {
        const adminid = req.userid; //req.userId;
        const sql = `SELECT * FROM admin WHERE id = ?`;
        const session = `SELECT session AS value, session AS label FROM session`;
        const classes = `SELECT id AS value, name AS label FROM classes`;
        const sections = `SELECT id AS value, name AS label FROM sections`;
        const departments = `SELECT id AS value, name AS label FROM departments`;
        const site = `SELECT * FROM site WHERE id = 1`;

        db.query(sql, [adminid], (err, result)=>{
            if(err) return res.status(400).json({message:err})
            db.query(session, (err1, result1)=>{
                if(err1) return res.status(400).json({message:err1})
            db.query(classes, (err2, result2)=>{
                if(err2) return res.status(400).json({message:err2})
            db.query(sections, (err3, result3)=>{
                if(err3) return res.status(400).json({message:err3})
            db.query(departments, (err4, result4)=>{
                if(err4) return res.status(400).json({message:err4})
             db.query(site, (err6, result6)=>{
            if(err6) return res.status(400).json({message:err6})
                const data = {
                    site:result6[0],
                    user:result[0],
                    sessions:result1,
                    classes:result2,
                    sections:result3,
                    departments:result4
                }
                res.status(200).json({message:'Login success',  data:data})
            });
            });
        });
    });
    });
        });
    } catch (error) {
        next(error)
    }
}


const deleteadmin = async(req, res, next)=>{
    try {
        const id = req.params.uid;
        const sql = `DELETE FROM admin WHERE id = ?`;
        // find image and unlink this.
        db.query(sql, [id], (err, result)=>{
            if(err) return res.status(400).json({message:err})
            res.status(200).json({message:'Account is successfully delete.'})
        })
    } catch (error) {
        next(error)
    }
}

module.exports = {gets, updateadminprofile, updateadminpassword, register, login, details, dashboard, deleteadmin}