const Doctor = require("../models/doctor");
const Order = require("../models/order");
const Member = require("../models/member");
let ejs = require("ejs");
let pdf = require("html-pdf");
let path = require("path");
const multer = require("multer");
const mongoose = require("mongoose");
const request = require('request');
var nodemailer = require('nodemailer');

const ObjectId = mongoose.Types.ObjectId;
const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString() + "-" + file.originalname);
  },
});
exports.getDoctors = (req, res, next) => {
  Doctor.find()
    .then((doctors) => {
      res.status(200).json(doctors);
    })
    .catch((err) => console.log(err));
};

exports.bookDoctor = (req, res, next) => {
  Doctor.findOne()
    .where("_id")
    .equals(req.query.doctorId)
    .then((doctor) => {
      if (doctor) {
		
		 console.log(req.query.userData);
		
		  /* let ordersave = new Order({
            userId: member._id,
            doctorId: doctor._id,
			usercheckup: req.query.userData,
			status: 'pending',
        });
		 ordersave.save(function (err) {
        if (err) {
            return next(err);
        }
		res.status(200).json({
              message:
                "Doctor has been booked " ,
            });
      
			}) */
			
			
			Order.findOneAndUpdate(
          {
            userId: req.query.userId,
          },
          {
            $push: {
              doctors: {
                id: doctor._id,
                name: doctor.name,
                price: doctor.price,
                type: "Doctor",
				remarks: req.query.userData[0].Remarks,
				primaryhealthissue: req.query.userData[1].Primary_Health_Issue,
				preferredlanguage: req.query.userData[2].Preferred_Language,
				modeofservice: req.query.userData[3].ModeOfService,
				symptoms: req.query.userData[4].Symptoms,
				postalcode: req.query.userData[5].postalCode,
				address: req.query.userData[5].address,
				long: req.query.userData[5].long,
				lat: req.query.userData[5].lat,
				status: "pending",
                bookedAt: new Date(parseInt(req.query.bookedAt)),
              },
            },
          },
          { upsert: true, new: true }
        )
          .then((order) => {
            res.status(200).json({
              message:
                "Doctor has been booked with id:\n" +
                order.doctors[order.doctors.length - 1]._id,
            });
          })
          .catch((err) => console.log(err));
			
			
			
      }
    })
    .catch((err) => console.log(err));
};

exports.sendotp = async function (req, res ,next) {		
		try {
			let existingUser = await Doctor.findOne({
            mobile: req.body.mobilenumber,
        });
      if (existingUser) {
		  var otp = Math.floor(1000 + Math.random() * 9000);
		  
		  let doc = await Doctor.findOneAndUpdate({
            mobile: req.body.mobilenumber,
          }, {otp:otp}, {
  new: true
});
        res.status(200).json({
              message:
                "Otp Send Successfuly" ,
				otpvalue:otp
            });
      }
	  else{
		  res.status(200).json({
              message:
                "This Number doesn't exist in database" ,
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};


exports.checkdoctorexist = async function (req, res ,next) {		
		try {
			let existingUser = await Doctor.findOne({
            mobile: req.body.mobilenumber,
        });
      if (existingUser) {
		 
        res.status(200).json({
              message:
                "Doctor Exist" ,
				status:true,
				data:existingUser
            });
      }
	  else{
		  res.status(400).json({
              message:
                "Doctor Not Exist" ,status:false
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};


exports.doctordeviceidupdate = async function (req, res ,next) {		
		try {
			
			let existingUser = await Doctor.findOne({
            mobile: req.body.mobilenumber,
        });
      if (existingUser) {		  
		  let doc = await Doctor.findOneAndUpdate({
            mobile: req.body.mobilenumber,
          }, {deviceid:req.body.deviceid}, {
  new: true
}); 
        res.status(200).json({
              message:
                "Doctor Updated" ,
				
            });
      }
	  else{
		  res.status(200).json({
              message:
                "Doctor doesnot exist" ,
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};


exports.otpverify = async function (req, res ,next) {		
		try {
			let existingUser = await Doctor.findOne({
            mobile: req.body.mobilenumber,
			otp: req.body.otp,
        });
      if (existingUser) {		  
		  let doc = await Doctor.findOneAndUpdate({
            mobile: req.body.mobilenumber,
          }, {otpstatus:'1',loggedintime:'1'}, {
  new: true
});
        res.status(200).json({
              message:
                "Otp Verified" ,
				data:doc
            });
      }
	  else{
		  res.status(200).json({
              message:
                "Otp Not Verified" ,
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};




exports.doctorstatusupdate = async function (req, res ,next) {		
		try {
			
			let existingUser = await Doctor.findOne({
            mobile: req.body.mobilenumber,
        });
      if (existingUser) {		  
		  let doc = await Doctor.findOneAndUpdate({
            mobile: req.body.mobilenumber,
          }, {status:req.body.status,statusservices:req.body.statusservices}, {
  new: true
});
        res.status(200).json({
              message:
                "Doctor Updated" ,
				
            });
      }
	  else{
		  res.status(200).json({
              message:
                "Doctor doesnot exist" ,
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};


exports.doctorbankdetailsupdate = async function (req, res ,next) {		
		try {
			
			let existingUser = await Doctor.findOne({
            mobile: req.body.mobilenumber,
        });
      if (existingUser) {		  
		  let doc = await Doctor.findOneAndUpdate({
            mobile: req.body.mobilenumber,
          }, {accountname:req.body.accountname,accountnumber:req.body.accountnumber,ifsccode:req.body.ifsccode,upipin:req.body.upipin}, {
  new: true
});
        res.status(200).json({
              message:
                "Doctor Updated" ,
				
            });
      }
	  else{
		  res.status(200).json({
              message:
                "Doctor doesnot exist" ,
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};



exports.previoususerprecription = async function (req, res ,next) {

	  console.log(req.body.userid);
	 Order.aggregate([
  {
    $match: { userId: ObjectId(req.body.userid) }
  },{$lookup:{ from: 'members', localField:'userId', 
        foreignField:'_id',as:'userdata'}}
]).exec((err, result)=>{
      if (err) {
          console.log("error" ,err)
      }
      if (result) {
          res.status(200).json({
              precriptiondetails:result
            });
      }
	  else{
		  res.status(200).json({
              message:
                "This Precription Doesnot Exist" ,
            });
	  }
});
/*  let doctor = await Order.findOne({
            userId: req.body.userid,
        });
		if (doctor) {
          res.status(200).json({
              precriptiondetails:doctor
            });
      }
	  else{
		  res.status(200).json({
              message:
                "This Precription Doesnot Exist" ,
            });
	  } */

};
exports.doctorsms = async function (req, res ,next) {
	const options = {
  method: 'POST',
  url: 'http://nimbusit.info/api/pushsms.php',
  headers: {
  },
  body: {
     'user' :"103517",
          key :  "010042nW30WR5HcPUbEM",
           mobile:  7737126379,
          //'mobile'=>$numbers,
          sender : "PLNHTH",
          text : "Thank You For contacting us we will get back to you!",
          route : "default"
  },
  json: true  // JSON stringifies the body automatically
}
	request(options, function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
 // console.log('body:', body); // Print the HTML for the Google homepage.
});

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'jainamhealthcare@gmail.com',
    pass: 'punsher0411'
  }
});
var abc = "akshay";
var mailOptions = {
  from: 'jainamhealthcare@gmail.com',
  to: 'akshay.sharma6565@gmail.com',
  subject: 'RE:Welcome to Plan My Health and Educure Family',
  html:`<h4>Dear `+ abc +`</h4><p> Thank You being the part of plan myhealth family here are your following details: </p><p> Email:akshay.sharma@6565@gmail.com </p><p> Mobile Number:+91-7737126379 </p><br>`
};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});
	res.status(200).json({
              message:
                "Doctor Created successfully" ,
            });
	};	

exports.doctorregister = async function (req, res ,next) {
		  try {
			  let doctor = await Doctor.findOne({
            mobile: req.query.mobilenumber,
        });
      if (!doctor) {
			  var signatureimage = '' ;
			  var profileimage  = '' ;
			  var documentfiles = '';
			  let upload = await multer({ storage: fileStorage }).any();
			  let abc = await upload(req, res, function(err) {
				  console.log(req.files);
				  if(req.files != undefined){
				  Object.keys(req.files).forEach(function (key) {
					
					if(req.files[key].fieldname == 'imagesignature'){
						
						signatureimage = req.files[key].path;
					}
					else if(req.files[key].fieldname == 'profilepicture'){
						profileimage = req.files[key].path;
					}
					else if(req.files[key].fieldname == 'document'){
						documentfiles += ','; 
						documentfiles += req.files[key].path;
					}
					console.log(documentfiles,"abcsa");
				});
				  }
				console.log(documentfiles,"abcs");
				let doctorsave = new Doctor(
        {
            name: req.query.name,
            email: req.query.email,
			mobile: req.query.mobilenumber,
			dob: req.query.dob,
			gender: req.query.gender, 
			specialization: req.query.category,
			practice: req.query.practice,
			qualification: req.query.qualification,
			experience: req.query.experience,
			clinicname: req.query.clinicname,
			cityId: req.query.city,
			address: req.query.address,
			workingto: req.query.workingto,
			workingfrom: req.query.workingfrom,
			registrationno: req.query.regno,
			picture: profileimage,
			signature: signatureimage,
			documentfiles: documentfiles,
			latitude: req.query.latitude,
			longitude: req.query.longitude,
			modeofservices: req.query.modeofservices,
			accrediation: req.query.accrediation,
			specialities: req.query.specialities,
			language: req.query.language,
			facility: req.query.facility,
        }
    );
	doctorsave.save(function (err) {
        if (err) {
            return next(err);
        }
				var transporter = nodemailer.createTransport({
		  service: 'gmail',
		  auth: {
			user: 'jainamhealthcare@gmail.com',
			pass: 'punsher0411'
		  }
		});
		var abc = "akshay";
		var mailOptions = {
		  from: 'jainamhealthcare@gmail.com',
		  to: req.query.email,
		  subject: 'RE:Welcome to Plan My Health and Educure Family',
		  html:`<h4>Dear `+ req.query.name +`</h4><p> Welcome to plan my health family here are your following details: </p><p> Email:`+ req.query.email +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> DOB:`+ req.query.dob +` </p><p> Gender:`+ req.query.gender +` </p><p> Specialization:`+ req.query.specialization +` </p><p> Practice:`+ req.query.practice +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> Mobile Number:`+ req.query.mobilenumber +` </p><p> Best Regards:Plan My Health and Educure  </p><p> Contact Number:8356928929  </p><br>`
		};

		transporter.sendMail(mailOptions, function(error, info){
		  if (error) {
			console.log(error);
		  } else {
			console.log('Email sent: ' + info.response);
		  }
		});
		res.status(200).json({
              message:
                "Doctor Created successfully" ,
            });
      
    })
			});
			console.log(signatureimage,"abc");
			
	
	  }else{
		  res.status(200).json({
              message:
                "Doctor Already Exist" ,
            });
	  }	
			
			 
			
}
		  catch (err) {
			console.log(err)
		}
		  
		  
      
};	  


	exports.preceptionupdate = async function (req, res ,next) {
	
 
		  try {
		let doctor = await Doctor.findOne({
            _id: req.body.doctorid,
        });
      if (doctor) {  
		  console.log("i"+req.body.userid);
        Order.findOneAndUpdate(
          {
            "doctors._id": mongoose.Types.ObjectId(req.body.userid),
          },
          {
            $set: {
				"doctors.$.doctorfeedback":"abc",
                "doctors.$.doctorid": req.body.doctorid,
                "doctors.$.doctorname": req.body.doctorname,
                "doctors.$.medicine": req.body.medicine,
				"doctors.$.test": req.body.test,
				"doctors.$.diagnosis": req.body.diagnosis,
				"doctors.$.hospitalised": req.body.hospitalised,
				"doctors.$.specialist": req.body.specialist,
				"doctors.$.wellness": req.body.wellness,
				"doctors.$.remark": req.body.remark,
				"doctors.$.findings":req.body.findings,
				"doctors.$.followupdate":req.body.followupdate,
				"doctors.$.doctorcheckdate":req.body.doctorcheckdate,
				"doctors.$.doctorfeedback":req.body.doctorfeedback,
            },
          },
          { upsert: true, new: true }
        )
          .then((order) => {
			  var orderdoctorarray = [];
			 
			  var orderdetails  = order.doctors;
			   
			  for (var i = 0; i < orderdetails.length; i++) {
				  
				  if(orderdetails[i]._id == req.body.userid){
					 console.log(orderdetails[i]._id); 
					 orderdoctorarray.push(orderdetails[i])
				  }
			  }
			  console.log(orderdoctorarray);
			  let medicine = JSON.parse(orderdoctorarray[0].medicine);
			  let diagnosis = JSON.parse(orderdoctorarray[0].diagnosis);
			  let findings = JSON.parse(orderdoctorarray[0].findings);
			   console.log("hiiii");
			  let test = JSON.parse(orderdoctorarray[0].test);
			 console.log("hiiissi");
			  var redId = doctor.registrationno;
			  var qualification = doctor.qualification;
			  var followupdate = orderdoctorarray[0].followupdate;
			  var doctorcheckdate = orderdoctorarray[0].doctorcheckdate;
			  var signature = "http://3.15.233.253/";
			  var signatureimage = signature+doctor.signature;
			   var hospitalised = orderdoctorarray[0].hospitalised;
			  var specialist = orderdoctorarray[0].specialist;
			  var hospitalise = "";
			  if(hospitalised == "true"){
				   hospitalise = "Yes";
			  }else{
				  hospitalise = "No";
			  }
			  
			  let wellness = JSON.parse(orderdoctorarray[0].wellness);
			  let remark = orderdoctorarray[0].remark;
			  let doctorname = orderdoctorarray[0].doctorname;
			  
			  ejs.renderFile(path.join(__dirname, './views/', "report-template.ejs"), {medicine: medicine,redId: redId,signature: signatureimage,diagnosis:diagnosis,findings:findings,test:test,hospitalise:hospitalise,wellness:wellness,remark:remark,specialist:specialist,doctorname:doctorname,qualification:qualification,followupdate:followupdate,doctorcheckdate:doctorcheckdate}, (err, data) => {
				  if (err) {
					  console.log("error"+err);
          //res.send(err);let diagnosis = JSON.parse(order.doctorscheckup[0].diagnosis);
		  res.status(200).json({
              message:
                err,
            });
    } else {
		let options = {
            "height": "11.25in",
            "width": "8.5in",
            "header": {
                "height": "20mm"
            },
            "footer": {
                "height": "20mm",
            },
        };
		var length = 5;
		var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   var resul = result+".pdf"
        pdf.create(data, options).toFile(path.join(__dirname, '../pdf/', resul), async function (err, data) {
            if (err) {
				 console.log("ds error"+err);
				
                res.send(err);
				
            } else {
				console.log(data.filename);
				console.log(data.toString());
				 let doc = await Order.findOneAndUpdate({"doctors._id": mongoose.Types.ObjectId(req.body.userid),}, {"doctors.$.pdffile":data.filename,"doctors.$.status":'complete'}, { upsert: true, new: true });
				 console.log(data);
                //res.send("File created successfully");
				res.status(200).json({
              message:
                "Doctor has checked successfully ",filename : data
            });
            }
        });
	}
			 });
			 // res.status(200).json({
             // message:
              //  "Doctor has checked successfully ",
           // });
			
			  
			  console.log(order);
            
          })
          .catch((err) => console.log(err));
	  }
		  else{
		  res.status(200).json({
              message:
                "Doctor Not Found" ,
            });
	  }
	  
		  }
		  catch (err) {
			console.log(err)
		}
		  
		  
      
};


exports.preceptionpdf = async function (req, res ,next) {
	
 
		  try { 
		 
		 
		
			  
			  
			 
			  ejs.renderFile(path.join(__dirname, './views/', "pd.ejs"), (err, data) => {
				  if (err) {
					  console.log("error"+err);
          //res.send(err);
		  res.status(200).json({
              message:
                err,
            });
    } else {
		let options = {
            "height": "11.25in",
            "width": "8.5in",
            "header": {
                "height": "20mm"
            },
            "footer": {
                "height": "20mm",
            },
        };
		var length = 5;
		var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   var resul = result+".pdf"
        pdf.create(data, options).toFile(path.join(__dirname, '../pdf/', resul), function (err, data) {
            if (err) {
				 console.log("ds error"+err);
				
                res.send(err);
				
            } else {
				 console.log(data);
                //res.send("File created successfully");
				res.status(200).json({
              message:
                "okay",
            });
            }
        });
	}
			 });
			  
            
         
	  
	  
		  }
		  catch (err) {
			console.log(err)
		}
		  
		  
      
};
