const Homevisit = require("../models/homevisit");
const Doctor = require("../models/doctor");
let ejs = require("ejs");
let pdf = require("html-pdf");
let path = require("path");
const multer = require("multer");
const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString() + "-" + file.originalname);
  },
}); 

exports.savehomevisit = async function (req, res ,next) {
			  try {
				  console.log(req.query.doctorid);

		 let doctor = await Doctor.findOne({
            _id: req.query.doctorid,
        });
		console.log(req.query);
      if (doctor) {
		   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 == 'document'){
						documentfiles += ','; 
						documentfiles += req.files[key].path;
					}
					console.log(documentfiles,"abcsa");
				});
				  }
		  let homevisitsave = new Homevisit(
        {
            furtherrecommendation: req.query.furtherrecommendation,
            treatment: req.query.treatment,
			issues: req.query.issues,
			equipments: req.query.equipments,
			intime: req.query.intime,
			outtime: req.query.outtime,
			doctorid: req.query.doctorid,
			date: req.query.date,
			remark: req.query.remark,
			charges: req.query.charges,
			documentfiles: documentfiles,
			status: 'Complete',
        }
    );
		 homevisitsave.save(function (err) {
        if (err) {
            return next(err);
        }
		res.status(200).json({
              message:
                "Home Visit Has Beed Saved " ,
            });
      
			})
			});
      }
   }
		  catch (err) {
			console.log(err)
		}
};


exports.gethomevisit = async function (req, res ,next) {		
		try {
			let existingUser = await Homevisit.find({
            doctorid: req.body.doctor_id,
        });
      if (existingUser) {
		 
        res.status(200).json({
              message:
                "Home Visit Exist" ,
				status:true,
				data:existingUser
            });
      }
	  else{
		  res.status(400).json({
              message:
                "Home Visit Not Exist" ,status:false
            });
	  }
		}
		catch (err) {
			console.log(err)
		}
    
};
