var express = require("express");
const router = express.Router();
const db = require("../../utils/database");
const dbFuntion = require("../../utils/dbfunctions");
const { response } = require("express");
const path = require("path");
const multer = require("multer");
const fs = require("fs");
const moment = require("moment");
const bcrypt = require("bcrypt");

const storage = multer.diskStorage({
  // https://www.npmjs.com/package/multer#diskstorage
  destination: "public/uploads",
  filename: function (req, file, cb) {
    cb(null, `image-${new Date().getTime()}.${file.mimetype.split("/")[1]}`);
  },
});
var upload = multer({ storage: storage });

router.get("/getProfileImage", (req, res) => {
  console.log("getImgagsMulter get Images req running ==>");
  const uploadDirectory = path.join("uploads");

  fs.readdir(uploadDirectory, (err, files) => {
    if (err) {
      return res.status(500).json({
        error: err,
        message: "Erro from server",
      });
    }
    if (files.length === 0) {
      return res.status(401).json({
        message: "No Images uploaded!",
      });
    }
    return res.status(200).json({
      files: files,
      message: "get image succussfully",
    });
  });
});

router.post("/uploadImage", upload.any("image"), (req, res, next) => {
  console.log("req body ===>", req.body);

  // const url = 'https' + "://" + req.get("host");     .......when deploying use this
  const url = "https" + "://" + req.get("host");
  console.log("url ===>", url);
  const image = url + "/uploads/" + req.files[0].filename;
  console.log("image path ==>", image);
  const id = req.body.id;
  console.log("id  ==>", id);

  let uQuery = `update finehhdi_fineAD.users set 
    profileUrl="${image}"
    where id=${id}`;

  db.query(uQuery, (err, data) => {
    if (err) {
      console.log(err);
      res.status(401).json({
        message: "error! User cant be Updated proflie picture for somereason",
        results: "Failed",
      });
    } else {
      res.status(200).json({
        message: "User profile pic uploaded Successfully",
        results: "Success",
        data: data,
      });
    }
  });
});
router.post("/updateUser", (req, res) => {
  console.log("req.body ===>", req.body);
  const id = req.body.id;
  var email = req.body.email;
  var username = req.body.username;
  var ofsRole = req.body.ofsRole;
  var bosRole = req.body.bosRole;
  var defectRole = req.body.defectRole;
  var clRole = req.body.clRole;
  var DepartName = req.body.DepartName;
  // var ofsDate = req.body.ofsDate;
  var ofsDate = moment(new Date()).format("DD-MM-YYYY");
  var isAdmin = req.body.isAdmin;

  var password = req.body.password;

  var test = 0;
  // console.log('ofsDate Coming From User Table',ofsDate)
  // New Code For User Update Start
  let query = `SELECT DepartName,ofsValue from finehhdi_OFS.ForSetOFS WHERE DepartName = '${DepartName}' 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("second queryy ===========>", query);
  db.query(query, (err, data) => {
    console.log("data ki length", data.length);

    if (data.length === 0) {
      console.log("in if block");
      // update of user is also here cuz if user just want to update user whose dpermant has no setofs then he can do it
      let uQuer = `update finehhdi_fineAD.users set 
    email='${email}',
    username='${username}', 
    ofsRole='${ofsRole}',
    bosRole='${bosRole}',
    defectRole='${defectRole}',
    clRole='${clRole}',
    isAdmin='${isAdmin}',
    ofsDate = '${ofsDate}',
    DepartName = '${DepartName}'
    where id=${id}`;
      console.log("Checking first query ==>", uQuer);
      db.query(uQuer, (err, data) => {
        if (err) console.log(err);
        else {
          res.status(200).json({
            message: "User Updated Successfully",
            results: "Success",
            team: data,
          });
          console.log("user updated successfully");
        }
      });
      // res.status(504).json({
      //   message: "ofs not set",
      // });

      return;
    } else {
      console.log("1===>data from ForSetOFS ============>", data);
      if (err) {
        console.log(err);
        res.status(401).json({
          message: "error! ",
          results: "Failed",
        });
        if (err.code === "ER_DUP_ENTRY") {
          res.status(409).json({
            message: "Duplicate User",
            results: "Failed",
          });
        }
      } else {
        console.log("data from ForSetOFS ============>", data);
        let UpdatedUserOFSValue = data.map((item) => item.ofsValue);
        console.log("updateUserOFSValue ==============>", UpdatedUserOFSValue);
        let query = `Update finehhdi_fineAD.users set ofsValue = ${UpdatedUserOFSValue}, remainingOfs = ${UpdatedUserOFSValue} where id = ${id} `;
        console.log("Third query =====================>", query);
        db.query(query, (err, data) => {
          if (err) {
            console.log(err);
            res.status(401).json({
              message: "error! ",
              results: "Failed",
            });
          } else {
            // res.status(200).json({
            //   message: "User Updated Successfully",
            //   results: "Success",
            // });
            let query = `UPDATE finehhdi_OFS.UsersInDepartments SET DepartName="${DepartName}" where UserId = ${id}`;
            console.log("Fourth query ==================> ", query);
            db.query(query, (err, data) => {
              if (err) {
                console.log(err);
              } else {
                bcrypt.hash(password, 14, function (err, hash) {
                  console.log("password =========>", password);
                  console.log("hash =========>", hash);
                  if (err) {
                    return res.json({
                      message: "Error while hashing",
                      error: err,
                    });
                  } else {
                    console.log("successfully updtaed un iserindepart");
                    let uQuer = `update finehhdi_fineAD.users set 
                                 email='${email}',
                                 username='${username}', 
                                 password='${hash}', 
                                 ofsRole='${ofsRole}',
                                 bosRole='${bosRole}',
                                 defectRole='${defectRole}',
                                 clRole='${clRole}',
                                 isAdmin='${isAdmin}',
                                 ofsDate = '${ofsDate}',
                                 DepartName = '${DepartName}'
                                 where id=${id}`;
                    console.log("Checking first query ==>", uQuer);
                    db.query(uQuer, (err, data) => {
                      if (err) console.log(err);
                      else {
                        res.status(200).json({
                          message: "User Updated Successfully",
                          results: "Success",
                          team: data,
                        });

                        console.log("user updated successfully");
                      }
                    });
                  }
                });
              }
            });
            console.log("user Updated Successfull");
          }
        });
      }
    }
  });

  // New Code For User Update  End

  // res.status(200).json({
  //   message: "User Updated Successfully",
  //   results: "Success",
  //   // team: data,
  // });
});

module.exports = router;

// var express = require("express");
// const router = express.Router();
// const db = require("../../utils/database");
// const dbFuntion = require("../../utils/dbfunctions");
// const { response } = require("express");
// const path = require("path");
// const multer = require("multer");
// const fs = require("fs");
// const moment = require('moment')
// const storage = multer.diskStorage({
//   // https://www.npmjs.com/package/multer#diskstorage
//   destination: "public/uploads",
//   filename: function (req, file, cb) {
//     cb(null, `image-${new Date().getTime()}.${file.mimetype.split("/")[1]}`);
//   },
// });
// var upload = multer({ storage: storage });

// router.get("/getProfileImage", (req, res) => {
//   console.log("getImgagsMulter get Images req running ==>");
//   const uploadDirectory = path.join("uploads");

//   fs.readdir(uploadDirectory, (err, files) => {
//     if (err) {
//       return res.status(500).json({
//         error: err,
//         message: "Erro from server",
//       });
//     }
//     if (files.length === 0) {
//       return res.status(401).json({
//         message: "No Images uploaded!",
//       });
//     }
//     return res.status(200).json({
//       files: files,
//       message: "get image succussfully",
//     });
//   });
// });

// router.post("/uploadImage", upload.any("image"), (req, res, next) => {
//   console.log("req body ===>", req.body);

//   // const url = 'https' + "://" + req.get("host");     .......when deploying use this
//   const url = 'https' + "://" + req.get("host");
//   console.log("url ===>", url);
//   const image = url + "/uploads/" + req.files[0].filename;
//   console.log("image path ==>", image);
//   const id = req.body.id
//   console.log("id  ==>", id);


//   let uQuery = `update finehhdi_fineAD.users set 
//     profileUrl="${image}"
//     where id=${id}`;

//   db.query(uQuery, (err, data) => {
//     if (err) {
//       console.log(err);
//       res.status(401).json({
//         message: "error! User cant be Updated proflie picture for somereason",
//         results: "Failed",
//       });
//     } else {
//       res.status(200).json({
//         message: "User profile pic uploaded Successfully",
//         results: "Success",
//         data: data,
//       });
//     }
//   });

// });
// router.post("/updateUser", (req, res) => {
//   const id = req.body.id;
//   var email = req.body.email;
//   var username = req.body.username;
//   var ofsRole = req.body.ofsRole;
//   var bosRole = req.body.bosRole;
//   var defectRole = req.body.defectRole;
//   var clRole = req.body.clRole;
//   var DepartName = req.body.DepartName;
//   // var ofsDate = req.body.ofsDate;
//   var ofsDate = moment(new Date()).format("DD-MM-YYYY");
//   var isAdmin = req.body.isAdmin
//   var test = 0;
//   // console.log('ofsDate Coming From User Table',ofsDate)
//   // New Code For User Update Start
//   let query = `SELECT DepartName,ofsValue from finehhdi_OFS.ForSetOFS WHERE DepartName = '${DepartName}' 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("second queryy ===========>", query);
//   db.query(query, (err, data) => {
//     console.log("data ki length", data.length);

//     if (data.length === 0) {
//       console.log("in if block");
//       // update of user is also here cuz if user just want to update user whose dpermant has no setofs then he can do it
//       let uQuer = `update finehhdi_fineAD.users set 
//     email='${email}',
//     username='${username}', 
//     ofsRole='${ofsRole}',
//     bosRole='${bosRole}',
//     defectRole='${defectRole}',
//     clRole='${clRole}',
//     isAdmin='${isAdmin}',
//     ofsDate = '${ofsDate}',
//     DepartName = '${DepartName}'
//     where id=${id}`;
//                 console.log("Checking first query ==>", uQuer);
//                 db.query(uQuer, (err, data) => {
//                   if (err) console.log(err);
//                   else {
//                     res.status(200).json({
//                       message: "User Updated Successfully",
//                       results: "Success",
//                       team: data,
//                     });
//                     console.log("user updated successfully");
//                   }
//                 })
//       // res.status(504).json({
//       //   message: "ofs not set",
//       // });

//       return;
//     } else {
//       console.log("1===>data from ForSetOFS ============>", data);
//       if (err) {
//         console.log(err);
//         res.status(401).json({
//           message: "error! ",
//           results: "Failed",
//         });
//         if (err.code === "ER_DUP_ENTRY") {
//           res.status(409).json({
//             message: "Duplicate User",
//             results: "Failed",
//           });
//         }
//       } else {
//         console.log("data from ForSetOFS ============>", data);
//         let UpdatedUserOFSValue = data.map((item) => item.ofsValue);
//         console.log("updateUserOFSValue ==============>", UpdatedUserOFSValue);
//         let query = `Update finehhdi_fineAD.users set ofsValue = ${UpdatedUserOFSValue}, remainingOfs = ${UpdatedUserOFSValue} where id = ${id} `;
//         console.log("Third query =====================>", query);
//         db.query(query, (err, data) => {
//           if (err) {
//             console.log(err);
//             res.status(401).json({
//               message: "error! ",
//               results: "Failed",
//             });
//           } else {
//             // res.status(200).json({
//             //   message: "User Updated Successfully",
//             //   results: "Success",
//             // });
//             let query = `UPDATE finehhdi_OFS.UsersInDepartments SET DepartName="${DepartName}" where UserId = ${id}`;
//             console.log("Fourth query ==================> ", query);
//             db.query(query, (err, data) => {
//               if (err) {
//                 console.log(err);
//               } else {
//                 console.log("successfully updtaed un iserindepart");
//                 let uQuer = `update finehhdi_fineAD.users set 
//     email='${email}',
//     username='${username}', 
//     ofsRole='${ofsRole}',
//     bosRole='${bosRole}',
//     defectRole='${defectRole}',
//     clRole='${clRole}',
//     isAdmin='${isAdmin}',
//     ofsDate = '${ofsDate}',
//     DepartName = '${DepartName}'
//     where id=${id}`;
//                 console.log("Checking first query ==>", uQuer);
//                 db.query(uQuer, (err, data) => {
//                   if (err) console.log(err);
//                   else {
//                     res.status(200).json({
//                       message: "User Updated Successfully",
//                       results: "Success",
//                       team: data,
//                     });

//                     console.log("user updated successfully");
//                   }
//                 });
//               }
//             });
//             console.log("user Updated Successfull");
//           }
//         });
//       }
//     }
//   });

//   // New Code For User Update  End

//   // res.status(200).json({
//   //   message: "User Updated Successfully",
//   //   results: "Success",
//   //   // team: data,
//   // });
// });

// module.exports = router;
