const formidable = require("formidable");
const validator = require("validator");
const fs = require("fs");
const bcrypt = require("bcrypt");
const axios = require("axios");
const User = require("../models/authModel");
const Kelompok = require("../models/kelompokModel");

class dashboardKetuaController {
  kelompokRegister = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const {
        judul,
        nama,
        skema,
        dosen,
        nim1,
        nama1,
        semester1,
        kelamin1,
        email1,
        telepon1,
        alamat1,
        studi1,
        fakultas1,
        nim2,
        nama2,
        semester2,
        kelamin2,
        email2,
        telepon2,
        alamat2,
        studi2,
        fakultas2,
        nim3,
        nama3,
        semester3,
        kelamin3,
        email3,
        telepon3,
        alamat3,
        studi3,
        fakultas3,
        nim4,
        nama4,
        semester4,
        kelamin4,
        email4,
        telepon4,
        alamat4,
        studi4,
        fakultas4,
      } = fields;

      try {
        const [user1, user2, user3, user4] = await Promise.all([
          User.findById(nim1),
          User.findById(nim2),
          User.findById(nim3),
          User.findById(nim4),
        ]);

        if (user1 || user2 || user3 || user4) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "NIM already exist",
            redirectUrl: "/dashboard",
          });
        } else {
          const anggota = [nim1, nim2, nim3, nim4];

          const limit = await User.findById(dosen);
          if (parseInt(limit.kuota) < 1) {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Kuota dosen habis",
              redirectUrl: "/dashboard",
            });
          } else {
            limit.kuota = `${parseInt(limit.kuota) - 1}`;
            limit.code = JSON.parse(limit.code);
            await User.findByIdAndUpdate(dosen, limit);
          }

          const createKelompok = new Kelompok(
            codeketua[0],
            judul,
            nama,
            skema,
            dosen,
            userInfo.nomor_induk,
            anggota,
            null,
            null,
            null,
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            ""
          );
          await createKelompok.save();

          const createUser = async (
            nim,
            nama,
            kelamin,
            semester,
            studi,
            fakultas,
            alamat,
            email,
            telepon
          ) => {
            const user = new User(
              nim,
              nama,
              kelamin,
              semester,
              studi,
              fakultas,
              alamat,
              email,
              telepon,
              await bcrypt.hash("uhamka123", 9),
              kelamin == "Perempuan" ? "mahasiswi.png" : "mahasiswa.png",
              "2",
              codeketua,
              ""
            );
            await user.save();
            // return user;
          };

          const users = await Promise.all([
            createUser(
              nim1,
              nama1,
              kelamin1,
              semester1,
              studi1,
              fakultas1,
              alamat1,
              email1,
              telepon1
            ),
            createUser(
              nim2,
              nama2,
              kelamin2,
              semester2,
              studi2,
              fakultas2,
              alamat2,
              email2,
              telepon2
            ),
            createUser(
              nim3,
              nama3,
              kelamin3,
              semester3,
              studi3,
              fakultas3,
              alamat3,
              email3,
              telepon3
            ),
            createUser(
              nim4,
              nama4,
              kelamin4,
              semester4,
              studi4,
              fakultas4,
              alamat4,
              email4,
              telepon4
            ),
          ]);

          const url =
            "https://bot.affidev.com/api/send-text?apikey=akusayangkamu";
          let message = `*──━•〔  KELOMPOK PKM  〕•━──*\n`;
          message += `Nama Kelompok: ${nama}\n`;
          message += `Judul PKM: ${judul}\n`;
          message += `Skema PKM: ${skema}\n\n`;

          message += `*──━•〔  ANGGOTA KELOMPOK  〕•━──*\n`;
          message += `NIM: ${nim1}\n`;
          message += `Nama: ${nama1}\n`;
          message += `Jenis Kelamin: ${kelamin1}\n`;
          message += `Semester: ${semester1}\n`;
          message += `Program Studi: ${studi1}\n`;
          message += `Fakultas: ${fakultas1}\n`;
          message += `Alamat: ${alamat1}\n`;
          message += `Email: ${email1}\n`;
          message += `Telepon: ${telepon1}\n`;
          message += `Password: uhamka123\n\n`;

          message += `NIM: ${nim2}\n`;
          message += `Nama: ${nama2}\n`;
          message += `Jenis Kelamin: ${kelamin2}\n`;
          message += `Semester: ${semester2}\n`;
          message += `Program Studi: ${studi2}\n`;
          message += `Fakultas: ${fakultas2}\n`;
          message += `Alamat: ${alamat2}\n`;
          message += `Email: ${email2}\n`;
          message += `Telepon: ${telepon2}\n`;
          message += `Password: uhamka123\n\n`;

          message += `NIM: ${nim3}\n`;
          message += `Nama: ${nama3}\n`;
          message += `Jenis Kelamin: ${kelamin3}\n`;
          message += `Semester: ${semester3}\n`;
          message += `Program Studi: ${studi3}\n`;
          message += `Fakultas: ${fakultas3}\n`;
          message += `Alamat: ${alamat3}\n`;
          message += `Email: ${email3}\n`;
          message += `Telepon: ${telepon3}\n`;
          message += `Password: uhamka123\n\n`;

          message += `NIM: ${nim4}\n`;
          message += `Nama: ${nama4}\n`;
          message += `Jenis Kelamin: ${kelamin4}\n`;
          message += `Semester: ${semester4}\n`;
          message += `Program Studi: ${studi4}\n`;
          message += `Fakultas: ${fakultas4}\n`;
          message += `Alamat: ${alamat4}\n`;
          message += `Email: ${email4}\n`;
          message += `Telepon: ${telepon4}\n`;
          message += `Password: uhamka123\n`;

          try {
            const response = await axios.post(url, {
              jid: userInfo.no_telpon + "@s.whatsapp.net",
              message: message,
            });

            console.log(response.data);
          } catch {
            console.log("Gagal mengirim notif ke ketua");
          }

          return res.render("sweet-alert", {
            icon: "success",
            message: "Your register successfull",
            redirectUrl: "/dashboard",
          });
        }
      } catch {
        return res.render("sweet-alert", {
          icon: "error",
          message: "Your register failed",
          redirectUrl: "/dashboard",
        });
      }
    });
  };

  editKelompok = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { revisijudul } = fields;
      try {
        const kel = await Kelompok.findById(codeketua[0]);
        kel.anggota = JSON.parse(kel.anggota);
        kel.judul = revisijudul;
        await Kelompok.findByIdAndUpdate(codeketua[0], kel);

        return res.render("sweet-alert", {
          icon: "success",
          message: "Your revisi successfull",
          redirectUrl: "/dashboard",
        });
      } catch {
        return res.render("sweet-alert", {
          icon: "error",
          message: "Gagal revisi",
          redirectUrl: "/dashboard",
        });
      }
    });
  };

  editDospem = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { revisidospem } = fields;
      try {
        const limit = await User.findById(revisidospem);
        if (parseInt(limit.kuota) < 1) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Kuota dosen habis",
            redirectUrl: "/dashboard",
          });
        } else {
          limit.kuota = `${parseInt(limit.kuota) - 1}`;
          limit.code = JSON.parse(limit.code);
          await User.findByIdAndUpdate(revisidospem, limit);

          const kel = await Kelompok.findById(codeketua[0]);
          kel.anggota = JSON.parse(kel.anggota);
          kel.dosen = revisidospem;
          kel.accdospem = null;
          await Kelompok.findByIdAndUpdate(codeketua[0], kel);

          return res.render("sweet-alert", {
            icon: "success",
            message: "Your revisi successfull",
            redirectUrl: "/dashboard",
          });
        }
      } catch {
        return res.render("sweet-alert", {
          icon: "error",
          message: "Gagal revisi",
          redirectUrl: "/dashboard",
        });
      }
    });
  };

  newAnggota = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const {
        nim,
        nama,
        semester,
        kelamin,
        email,
        telepon,
        alamat,
        studi,
        fakultas,
      } = fields;
      const user = await User.findById(nim);
      if (user) {
        return res.render("sweet-alert", {
          icon: "error",
          message: "NIM already exist",
          redirectUrl: "/register",
        });
      } else {
        try {
          const kel = await Kelompok.findById(codeketua[0]);
          const anggota = JSON.parse(kel.anggota);
          anggota.push(nim);
          kel.anggota = anggota;
          await Kelompok.findByIdAndUpdate(codeketua[0], kel);

          const createuser = new User(
            nim,
            nama,
            kelamin,
            semester,
            studi,
            fakultas,
            alamat,
            email,
            telepon,
            await bcrypt.hash("uhamka123", 9),
            kelamin == "Perempuan" ? "mahasiswi.png" : "mahasiswa.png",
            "2",
            codeketua,
            ""
          );
          await createuser.save();

          const url =
            "https://bot.affidev.com/api/send-text?apikey=akusayangkamu";
          let message = `*──━•〔  ANGGOTA BARU  〕•━──*\n`;
          message += `NIM: ${nim}\n`;
          message += `Nama: ${nama}\n`;
          message += `Jenis Kelamin: ${kelamin}\n`;
          message += `Semester: ${semester}\n`;
          message += `Program Studi: ${studi}\n`;
          message += `Fakultas: ${fakultas}\n`;
          message += `Alamat: ${alamat}\n`;
          message += `Email: ${email}\n`;
          message += `Telepon: ${telepon}\n`;
          message += `Password: uhamka123\n\n`;

          try {
            const response = await axios.post(url, {
              jid: userInfo.no_telpon + "@s.whatsapp.net",
              message: message,
            });

            console.log(response.data);
          } catch {
            console.log("Gagal mengirim notif ke ketua");
          }

          return res.render("sweet-alert", {
            icon: "success",
            message: "Your register successfull",
            redirectUrl: "/dashboard",
          });
        } catch {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Your register failed",
            redirectUrl: "/dashboard",
          });
        }
      }
    });
  };

  dropAnggota = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { code, nim } = fields;
      if (nim == "") {
        return res.render("sweet-alert", {
          icon: "error",
          message: "Anggota Tidak ada",
          redirectUrl: "/dashboard",
        });
      } else {
        try {
          const kel = await Kelompok.findById(codeketua[0]);
          let arr = JSON.parse(kel.anggota);
          let elementToRemove = nim;
          kel.anggota = arr.filter((item) => item !== elementToRemove);
          await Kelompok.findByIdAndUpdate(codeketua[0], kel);
          await User.findByIdAndDelete(nim);

          return res.render("sweet-alert", {
            icon: "success",
            message: "Your remove successfull",
            redirectUrl: "/dashboard",
          });
        } catch {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Your remove failed",
            redirectUrl: "/dashboard",
          });
        }
      }
    });
  };

  uploadLaporanSatu = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { laporansatu } = files;
      laporansatu.originalFilename = Date.now() + laporansatu.originalFilename;
      console.log(laporansatu.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${laporansatu.originalFilename}`;
      fs.copyFile(laporansatu.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.laporanSatu = laporansatu.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };

  uploadLaporanDua = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { laporandua } = files;
      laporandua.originalFilename = Date.now() + laporandua.originalFilename;
      console.log(laporandua.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${laporandua.originalFilename}`;

      fs.copyFile(laporandua.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.laporanDua = laporandua.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };

  uploadLaporanTiga = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { laporantiga } = files;
      laporantiga.originalFilename = Date.now() + laporantiga.originalFilename;
      console.log(laporantiga.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${laporantiga.originalFilename}`;

      fs.copyFile(laporantiga.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.laporanTiga = laporantiga.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };

  uploadRevisiSatu = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { revisisatu } = files;
      revisisatu.originalFilename = Date.now() + revisisatu.originalFilename;
      console.log(revisisatu.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${revisisatu.originalFilename}`;

      fs.copyFile(revisisatu.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.revisiSatu = revisisatu.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };

  uploadRevisiDua = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { revisidua } = files;
      revisidua.originalFilename = Date.now() + revisidua.originalFilename;
      console.log(revisidua.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${revisidua.originalFilename}`;

      fs.copyFile(revisidua.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.revisiDua = revisidua.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };

  uploadRevisiTiga = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { revisitiga } = files;
      revisitiga.originalFilename = Date.now() + revisitiga.originalFilename;
      console.log(revisitiga.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${revisitiga.originalFilename}`;

      fs.copyFile(revisitiga.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.revisiTiga = revisitiga.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };

  uploadFinalProject = async (req, res) => {
    const { id } = req.userInfo;
    const userInfo = await User.findById(id);
    const codeketua = JSON.parse(userInfo.code);

    const form = formidable({ multiples: true });
    form.parse(req, async (err, fields, files) => {
      const { finalproject } = files;
      finalproject.originalFilename =
        Date.now() + finalproject.originalFilename;
      console.log(finalproject.originalFilename);
      const disPath =
        __dirname + `/../view/assets/pdf/${finalproject.originalFilename}`;

      fs.copyFile(finalproject.filepath, disPath, async (err) => {
        if (err) {
          return res.render("sweet-alert", {
            icon: "error",
            message: "Upload failed please try again",
            redirectUrl: "/dashboard",
          });
        } else {
          try {
            const kel = await Kelompok.findById(codeketua[0]);
            kel.anggota = JSON.parse(kel.anggota);
            kel.finalProject = finalproject.originalFilename;
            await Kelompok.findByIdAndUpdate(codeketua[0], kel);

            return res.render("sweet-alert", {
              icon: "success",
              message: "Your upload successfull",
              redirectUrl: "/dashboard",
            });
          } catch {
            return res.render("sweet-alert", {
              icon: "error",
              message: "Your upload failed",
              redirectUrl: "/dashboard",
            });
          }
        }
      });
    });
  };
}

module.exports = new dashboardKetuaController();
