var express = require("express");
const router = express.Router();
const db = require("../../utils/database");
const bcrypt = require("bcrypt");
const moment = require("moment");

router.post("/UserCreation", (req, res) => {
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  var department = req.body.departName;
  var assignedOfs = req.body.AssignedOFS;
  var assignedEDefect = req.body.AssignedEdefect;
  var assignedBos = req.body.AssignedBOS;
  var ofsRole = req.body.ofsRole;
  var bosRole = req.body.bosRole;
  var defectRole = req.body.defectRole;
  var isAdmin = req.body.isAdmin
  var clRole = req.body.clRole
  var  AssignedCL = req.body. AssignedCL
  const ofsDate = moment(new Date()).format("DD-MM-YYYY");

  // console.log("for isAdmin ===>", isAdmin);
  console.log("for DepartName ===>", department);

  bcrypt.hash(password, 14, function (err, hash) {
    if (err) {
      console.log(err);
      return res.json({
        message: "Error while hashing",
        error: err,
      });
    }
    // new Changes 30-sep
    else {
      // var query = `insert into finehhdi_fineAD.users (email,username,password,isAdmin,DepartName) values ("${email}","${username}","${hash}","${isAdmin}","${DepartName}");`;
      var query = `insert into finehhdi_fineAD.users (email,username,password,isAdmin,ofsDate,DepartName,AssignedOFS,AssignedEdefect,AssignedBOS,AssignedCL,ofsRole,bosRole,defectRole,clRole) 
        values ("${email}","${username}","${hash}","${isAdmin}","${ofsDate}","${department}",${assignedOfs},${assignedEDefect},${assignedBos},${AssignedCL},"${ofsRole}","${bosRole}","${defectRole}","${clRole}");`;
      console.log("query from inser into users ====>", query);
      db.query(query, (err, result) => {
        if (err) {
          console.log(err);
          if (err.code === "ENOTFOUND") {
            res.status(404).json({
              message: "Internet Connection Failed",
              results: "failed",
            });
          } else if (err.code === "ER_DUP_ENTRY") {
            res.status(409).json({
              message: "Duplicate User",
              results: "Failed",
            });
          }
        } else {
          if (err) {
            console.log(err);
            res.status(401).json({
              message: "User creation failed",
              results: "Failed",
            });
          } else {
            // let newQuery = `SELECT * from users where id = ${UserId}`;
            let newQuery = `SELECT * from finehhdi_fineAD.users where email = "${email}"`;
            db.query(newQuery, (err, data) => {
              console.log("error from SELECT users ==>", err);
              if (err) {
                res.status(500).send({
                  message: "Error from server",
                });
              } else {
                console.log("get data from users ===>", data);
                var UserId = data.map((item) => item.id);

                //userInDept query start
                let query = `INSERT into finehhdi_OFS.UsersInDepartments (DepartName, UserId, userName, userEmail )values ("${department}" ,"${UserId}","${username}" ,"${email}")`;
                console.log("query data from createUserdept ===>", query);
                db.query(query, (err, data) => {
                  if (err) {
                    console.log(err);
                  } else {
                    let queryForSetOFS = `SELECT * FROM finehhdi_OFS.ForSetOFS where DepartName= '${department}' AND DATE_FORMAT(STR_TO_DATE(Date,'%d-%m-%Y'),'%m-%Y') = DATE_FORMAT(STR_TO_DATE("${ofsDate}",'%d-%m-%Y'),'%m-%Y')`;
                    console.log(
                      "queryForSetOFS from setOFS Table ==>",
                      queryForSetOFS
                    );
                    db.query(queryForSetOFS, (err, data) => {
                      console.log("data from SELECT * ForSetOFS ==>", data);
                      if (err) {
                        console.log("error from SELECT * ForSetOFS ==>", err);
                        res.status(500).send({
                          message: "Error from server",
                        });
                      } else {
                        console.log('data checking for err purpose',data)
                        // console.log("data from ForSetOFS table ===>", data);
                        var ofsValueSetOFS = data.map((item) => item.ofsValue);
                        // // query for update ofsValue and remainingOfs value
                        let updateQuery = `UPDATE finehhdi_fineAD.users SET ofsValue=${Number( ofsValueSetOFS )},remainingOfs=${Number( ofsValueSetOFS )},ofsDate="${ofsDate}" where id=${UserId}`;
                        console.log(
                          "updateQuery from users SET ofsValue ===>",
                          updateQuery
                        );

                        db.query(updateQuery, (err, data) => {
                          if (err) {
                            console.log("error from update ofsValue ==>", err);
                          } else {
                            // inserting new data in ofsrecord
                            console.log('in last insert query',data)
                            if(ofsValueSetOFS == '' || ofsValueSetOFS== null){
                              var lastquery = `INSERT INTO finehhdi_OFS.OFSRecord (DepartName,UserId,Date,UserOfsAssigned,UserOfsRemaining) values ("${department}",${UserId},"${ofsDate}",${0},${0})`;
                            }
                            else{
                              var lastquery = `INSERT INTO finehhdi_OFS.OFSRecord (DepartName,UserId,Date,UserOfsAssigned,UserOfsRemaining) values ("${department}",${UserId},"${ofsDate}",${ofsValueSetOFS},${ofsValueSetOFS})`;
                            }
                            
                           console.log('last insert query',query)
                            db.query(lastquery, (err, data) => {
                              if (err) console.log(err);
                              else {
                                console.log("inserted in ofsrecord");
                              }
                            });
                            console.log(
                              "data from update ofsValue of user ===>",
                              data
                            );
                          }
                        });
                        console.log("select from ForSetOFS table successfully");
                      }
                    });
                    console.log("res.status(500) ==> ", err);
                    console.log(
                      "res.status(200) Data inserted in UsersInDepartment Successfully",
                      data
                    );
                    // res.status(200).send({
                    //   message: `Data inserted in UsersInDepartment Successfully`,
                    // });
                  }
                });

                // userInDept query end
              }
            });

            console.log(email);
            res.status(200).json({
              message: "User Created Successfully",
              results: "Success",
            });
          }
        }
      });
    }
  });
});
// router.post("/UserCreation", (req, res) => {
//     var email = req.body.email
//     var username = req.body.username
//     var password = req.body.password
//     var department = req.body.departName
//     var assignedOfs = req.body.AssignedOFS
//     var assignedEDefect = req.body.AssignedEdefect
//     var assignedBos = req.body.AssignedBOS
//     var ofsRole = req.body.ofsRole
//     var bosRole = req.body.bosRole
//     var defectRole = req.body.defectRole
//     const ofsDate = moment(new Date()).format("DD-MM-YYYY");
//     bcrypt.hash(password, 14, function (err, hash) {
//         if (err) {
//             console.log(err);
//             return res.json({
//                 message: "Error while hashing",
//                 error: err
//             })
//         }
//         // new Changes 30-sep
//         else {
//             var query = `insert into finehhdi_fineAD.users (email,username,password,ofsDate,DepartName,AssignedOFS,AssignedEdefect,AssignedBOS,ofsRole,bosRole,defectRole)
//             values ("${email}","${username}","${hash}","${ofsDate}","${department}",${assignedOfs},${assignedEDefect},${assignedBos},"${ofsRole}","${bosRole}","${defectRole}");`
//            console.log(query);
//             db.query(query, (err, result) => {
//                 if (err) {
//                     console.log("error ==>", err);
//                     if (err.code === "ER_DUP_ENTRY") {
//                         res.status(409).json({
//                             message: "Duplicate User",
//                             results: "Failed",
//                         });
//                     }
//                     else if (err.code === 'ENOTFOUND') {
//                         res.status(404).json({
//                             message: "Internet Connection Failed",
//                             results: 'failed'
//                         })

//                     }
//                     else {
//                         console.log(err);
//                         res.status(401).json({
//                             message: "dep creation failed",
//                             results: "Failed",
//                         });

//                     }
//                 }
//                 else {

//                     res.status(200).json({
//                         message: "dep Created Successfully",
//                         results: "Success",
//                     });

//                 }

//             })
//         }
//     })

// })

module.exports = router;
