  const User = require("../../models").users;
  require("dotenv").config();
  const Activity = require("../helpers/activity.helper")
  const Profile = require("../../models").profiles;
  const StudentSupervisor = require("../../models").student_supervisors;
  const Subscription = require("../../models").subscriptions;
  const CurrentSession = require("../../models").sessions;
  const Department = require("../../models").departments;
  const ODFORMS = require("../../models").odfel_forms;
  const Institute = require("../../models").institutes;
  const PaystackDetails = require("../../models").paystack_details;
  const sequelize = require("../../models").sequelize;
  const axios = require("axios");
  const { raw } = require("body-parser");

  function generateUUID() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }
  exports.Edit = async (req, res) => {
    try {
      let session_id;
      const session = await CurrentSession.findOne({ where: { status: true } });
    
      if (session) {
        session_id = session.id;
      }
      const {
        firstname,
        lastname,
        middlename,
        email,
        phone,
        supervisor,
        level,
        study_mode,
        department_id,
        reactivate,
        ppo_id
      } = req.body


      const updateProfileData = {
        ...req.body
      };
      
      

    const updateUserData = {
      ...req.body
    };

    if (reactivate === "Yes") {
      updateUserData.session_id = session_id;
      updateProfileData.session_id = session_id;
      await Subscription.destroy({where:{user_id:req.body.user_id}})
    }
    const updateProfile =  await Profile.update(updateProfileData, {
        where: {
          user_id: req.body.user_id
        }
      })

      const updateUser =  await User.update(updateUserData, {
          where: {
            id: req.body.user_id
          }
        })  

        if(supervisor){
          const checkStudentSuperVisor =  await StudentSupervisor.findOne({
            where:{student_user_id:req.body.user_id},
            raw:true
          });
          const superUpdate = {
            lecturer_user_id:supervisor
          };
          if (reactivate === "Yes") {
            superUpdate.session_id = session_id;
          }
          if(checkStudentSuperVisor){
            await StudentSupervisor.update(superUpdate,{where:{student_user_id:req.body.user_id}})
          }else{
            await StudentSupervisor.create({
              student_user_id:req.body.user_id,
              lecturer_user_id:supervisor,
              project_type_id: 1,
              session_id 
            })
          }
        }
      const saveActivity = await Activity("Profile", "Update profile information", req.body.firstname)


      if(updateUser && updateProfile && saveActivity){
          return res.status(200).send({
              statusCode: "200",
              success: true,
              message: 'Your information has been updated',
            })
      }else{
          return res.status(409).send({
              statusCode: "409",
              success: false,
              message: 'Error',
              error: `unabale to update your information, try again`
            })
      }

    

  }catch(e){
    res.status(500).send({
      statusCode: "500",
      success: false,
      message: "Error",
      error: e.message
    })
  }
  }
  exports.Profile = async(req, res) => {
    return res.render("student/profile.ejs") 
  }

  exports.getStarted = async (req, res) => {
    try {
      const {
        email,
        phone,
        username,
        department_id
      } = req.body


      if (!email) {
        return res.status(409).send({
          statusCode: "409",
          success: false,
          message: 'Error',
          error: 'email is required'
        })
      }

      if (!phone) {
          return res.status(409).send({
            statusCode: "409",
            success: false,
            message: 'Error',
            error: 'phone is required'
          })
        }
        // if (!department_id) {
        //   return res.status(409).send({
        //     statusCode: "409",
        //     success: false,
        //     message: 'Error',
        //     error: 'Department is required'
        //   })
        // }
      if (req.file == undefined) {
          return res.status(400).send("Please upload an valid file!");
        }
        let path = req.file.filename;
    const updateUserData = {
      email:email.toLowerCase().trim(),
      phone,
      first_login:true,
  }

      const updateUser =  await User.update(updateUserData, {
          where: {
            username
          }
        })  
      const mainUser = await User.findOne({where:{username:username}});
      await Profile.update({photo_path:path, department_id},{where:{user_id:mainUser.id}})

      const saveActivity = await Activity("Profile", "First time stup", username)


      if(updateUser && saveActivity){
          return res.status(200).send({
              statusCode: "200",
              success: true,
              message: 'Your information has been updated',
            })
      }else{
          return res.status(409).send({
              statusCode: "409",
              success: false,
              message: 'Error',
              error: `unabale to update your information, try again`
            })
      }

  }catch(e){
    console.log(e)
    res.status(500).send({
      statusCode: "500",
      success: false,
      message: "Error",
      error: e.message
    })
  }
  }

  exports.getODFELForm = async (req, res) => {
    try {
      const { department_id, username, email, firstname } = req.body;

      if (!email) {
        return res.status(400).send({
          success: false,
          message: 'Email is required',
        });
      }

      if (!username) {
        return res.status(400).send({
          success: false,
          message: 'Matric Number is required!',
        });
      }
      if (req.file === undefined) {
        return res.status(400).send("Please upload a valid file!");
      }

      let photo_path = `/avatar/${req.file.filename}`;

      const department = await Department.findOne({ where: { id: department_id } },);
      if(!department?.institute_id ){
        return res.status(400).send({
          success: false,
          message: 'Invalid Department!',
        });
      }
      const institute = await Institute.findOne({ where: { id: department?.institute_id } },);

      const New_Txn_Ref = generateUUID();

      const user = await ODFORMS.create(
        { ...req.body, amount: 500, department: department.name, institute: institute.name, txn_ref: New_Txn_Ref, photo_path },

      );

      const paystackKey = await PaystackDetails.findOne();
      const paystack = require("paystack")(paystackKey.TEST_SECRET_KEY);
      const transactionData = {
        name: firstname,
        email: email,
        amount: 700 * 100,
        reference: New_Txn_Ref,
        metadata: {
          transaction_id: user.id,
          is_odfel: true,
        },
        callback_url: `${req.protocol}://${req.headers.host}${req.url}`,
      };

      const paystackTransaction = await paystack.transaction.initialize(transactionData);

      // await transaction.commit();

      return res.send({
        success: true,
        user: user,
        message: "Registration in progress, proceed to payment",
        authorizationUrl: paystackTransaction?.data?.authorization_url,
      });
    } catch (e) {
      console.log(e);
      res.status(500).send({
        success: false,
        message: e.message,
      });
    }
  };
  exports.getODFELFormRecord = async (req, res) => {

    try {
      const { username } = req.body;

      if (!username) {
        return res.status(400).send({
          success: false,
          message: 'Matric Number is required!',
        });
      }
      const records = await ODFORMS.findAll({ where: { username } });
      return res.send({
        success: true,
        records
      });
    } catch (e) {
      console.log(e);
      res.status(500).send({
        success: false,
        message: e.message,
      });
    }
  };
  exports.getODFELFormRequery = async (req, res) => {

    try {
      const { id } = req.body;

      if (!id) {
        return res.status(400).send({
          success: false,
          message: 'ID is required!',
        });
      }
      const record = await ODFORMS.findOne({ where: { id } , raw:true});
      if (!record) {
        return res.status(200).send({
          success: false,
          message: 'Payment not found',
        });
      }
      const paystackKey = await PaystackDetails.findOne();
      const paystack = require("paystack")(paystackKey.TEST_SECRET_KEY);

      var paystackCallbackRes;
      await paystack.transaction
        .verify(record.txn_ref)
        .then((transaction) => {
          paystackCallbackRes = transaction.data;
        });
        if(paystackCallbackRes?.status == "success"){
          await ODFORMS.update({txn_status:"success"},{where: { id } , raw:true}); 
        }
        return res.send(paystackCallbackRes?.gateway_response);
    } catch (e) {
      console.log(e);
      res.status(500).send({
        success: false,
        message: e.message,
      });
    }
  };
  exports.uploadPassport = async (req, res) => {
    try {
      const {
        username
      } = req.body

      if (req.file == undefined) {
          return res.status(400).send("Please upload an valid file!");
        }
    let path = req.file.filename;

      const mainUser = await User.findOne({where:{username:username}});
      await Profile.update({photo_path:path},{where:{user_id:mainUser.id}})

      await Activity("Profile", "Passport Updated!", username)

      return res.status(200).send({
        statusCode: "200",
        success: true,
        message: 'Your information has been updated',
      })

  }catch(e){
    console.log(e)
    res.status(500).send({
      statusCode: "500",
      success: false,
      message: "Error",
      error: e.message
    })
  }
  }
  exports.saveNewScore = async (req, res) => {
    try {
      const { level_id, study_mode_id, username, department_id } = req.body;

      if (!username) {
        return sendError(res, 'Username is required', 409);
      }

      // if (!department_id) {
      //   return sendError(res, 'Department is required', 409);
      // }

      // if (!level_id) {
      //   return sendError(res, 'Level is required', 409);
      // }

      const mainUser = await User.findOne({ where: { username } });

      await Profile.update(
        { department_id, level_id, study_mode_id },
        { where: { user_id: mainUser.id } }
      );

      const saveActivity = await Activity('Profile', 'First time setup', username);

      if (saveActivity) {
        return sendSuccess(res, 'Your information has been updated');
      } else {
        return sendError(res, 'Unable to update your information, try again', 409);
      }
    } catch (e) {
      console.error('Error:', e);
      return sendError(res, e.message, 500);
    }
  };

  function sendError(res, errorMessage, statusCode) {
    return res.status(statusCode).json({
      statusCode: statusCode.toString(),
      success: false,
      message: 'Error',
      error: errorMessage,
    });
  }

  function sendSuccess(res, successMessage) {
    return res.status(200).json({
      statusCode: '200',
      success: true,
      message: successMessage,
    });
  }