const Doctor = require("../models/doctor");
const Order = require("../models/order");
const Member = require("../models/member");
const mongoose = require("mongoose");
exports.getorder  = async function (req, res ,next) {
  
	
	Order.aggregate([{$lookup:{ from: 'members', localField:'userId', 
        foreignField:'_id',as:'userdata'}},{ $project: {
      doctors: { $filter: {
          input: '$doctors',
          as: 'doctors',
		  cond : {
                $and : [
                   { $eq : [ "$$doctors.status", "pending" ] },
                   { $eq : [ "$$doctors.id", req.query.doctorid ] }
                ]
             }
      }}, userId: 1,userdata:1
      
  }},
]).exec(async (err, result)=>{
      if (err) {
          console.log("error" ,err)
      }
      if (result) {
		  
		  
          res.status(200).json({
              doctorlist:result
            });
      }
});

};


exports.doctorgetorder = (req, res, next) => {
  
	
	/* Order.aggregate([ { $match: {
      status: 'complete',doctorId:req.query.doctorid
	}},{$lookup:{ from: 'members', localField:'userId', 
        foreignField:'id',as:'userdata'}}, */
			
	Order.aggregate([{$lookup:{ from: 'members', localField:'userId', 
        foreignField:'_id',as:'userdata'}},{ $project: {
      doctors: { $filter: {
          input: '$doctors',
          as: 'doctors',
		  cond : {
                $and : [
                   { $eq : [ "$$doctors.status", "complete" ] },
                   { $eq : [ "$$doctors.id", req.query.doctorid ] }
                ]
             }
      }}, userId: 1,userdata:1
      
  }},
]).exec((err, result)=>{
      if (err) {
          console.log("error" ,err)
      }
      if (result) {
          res.status(200).json({
              doctorlist:result
            });
      }
});

};



exports.doctorgetorderdetails = async function(req, res, next)  {
  console.log(req.query.precriptionid);
	
	/* Order.aggregate([ { $match: {
      _id: mongoose.Types.ObjectId(req.query.precriptionid)
	}},{$lookup:{ from: 'members', localField:'userId', 
        foreignField:'id',as:'userdata'}}, */
  Order.aggregate([{ $match: {'_id':mongoose.Types.ObjectId(req.query.objectid)}},{$lookup:{ from: 'members', localField:'userId', 
        foreignField:'_id',as:'userdata'}},{ $project: {
       doctors: { $filter: {
          input: '$doctors',
          as: 'doctors',
          cond: { $eq: ["$$doctors._id", mongoose.Types.ObjectId(req.query.precriptionid)]}
      }}, userId: 1,userdata:1
      
  }},
]).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" ,
            });
	  }
});

};

