public async Task<JsonResult> Invoice(Offer question)
        {
            var user = User.Identity.GetUserId();
            var sessionId = question.SessionId;
            var session = db.sessions.Where(c => c.SessionID == sessionId && c.TutorID.Value == new Guid(user)).First();
            if (session.Status == Status.Hired || session.Status==Status.Invoiced)
            {
                session.OfferedFees = question.amount;
                session.Status = Status.Invoiced;
                db.Entry(session).State = EntityState.Modified;

                DBEntities.Transaction tran = new DBEntities.Transaction();
                tran.TransactionID = Guid.NewGuid();
                tran.SessionID = sessionId;
                tran.Status = Status.Invoiced;
                tran.OfferedFees = question.amount;
                tran.PostedTime = DateTime.Now;
                db.transcations.Add(tran);

                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID = new Guid(User.Identity.GetUserId());
                obj.SessionID = sessionId;
                obj.PostedTime = DateTime.Now;
                obj.Details = " Automatically Generated Message: I have sent Invoice for the work for $" + question.amount + ". Press Accept Button if you are satisfied with the services and pay to tutor. Pressing Reject button will cause the admin to decide the dispute.";
                session.Replies.Add(obj);

                db.SaveChanges();

                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                //send message reply
                var username = User.Identity.Name;
                var imgsrc = db.Tutors.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(), obj.ReplyID.ToString(),false);
                SendChatTutorReciever(obj.SessionID.ToString(), username, message, context); //send message to urself 

                var student = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().question.student;
                var username2 = student.Username;
                SendChatStudentReiever(obj.SessionID.ToString(), username2, message, context); //send message to other person 

                //send button
                
                var message2 = "<button type =\"button\" id=\"accept\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#approveNewModal\" style=\"margin-right:5px\">Accept </button>";
                message2 = message2 + "<button type =\"button\" id=\"reject\" class=\"btn  btn-primary\" data-toggle=\"modal\" data-target=\"#rejectNewModal\">Reject </button>";

                   SendButtonStudent(sessionId.ToString(), username2, message2, context); //send message to other person 
                   SendNotification(username2, username, imgsrc, "I have sent Invoice of $" + question.amount,true, "Students", "Sessions", "SessionId=" + sessionId);
                
                //send email
                var email = db.Users.Where(c => c.Id == session.question.StudentID.ToString()).FirstOrDefault().Email;
                String subject = "Tutor sent Invoice on MezoExperts.com";
                String bodyText = username + " has sent invoice for $" + question.amount;
                string fileTemplate = "passwordreset.html";
                await sendEmail(email, subject, bodyText, fileTemplate, "");

                
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = question.amount }
                };
            }
            else
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "" }
                };
            }

        }
        public async Task<ActionResult> QuestionsReply(TutorQuestionDetails reply)
        {
            var userId= new Guid(User.Identity.GetUserId());
            var user = db.Tutors.Where(c => c.TutorID == userId).FirstOrDefault();
            var question = db.Questions.Where(c => c.QuestionID == reply.QuestionID);
            var postedQuestion = question.FirstOrDefault();
            var selectedSession = postedQuestion.Sessions.Where(c => c.TutorID.Value == userId).FirstOrDefault();
            if (selectedSession == null)
            { 
                Session obj = new Session();
                obj.SessionID = Guid.NewGuid();
                obj.TutorID = userId;
                //obj.StudentID = reply.StudentID;
                obj.QuestionID = reply.QuestionID;
                obj.PostedTime = DateTime.Now;
                obj.Status = Status.Posted;
                db.sessions.Add(obj);
            
                Reply rep = new Reply();
                rep.ReplyID =  Guid.NewGuid();
                rep.SessionID = obj.SessionID;
                rep.ReplierID = obj.TutorID.Value;
                rep.PostedTime = DateTime.Now;
                reply.replyDetails= reply.replyDetails.Replace(Environment.NewLine, "<br/>");
                rep.Details = reply.replyDetails;
                db.Replies.Add(rep);
                await db.SaveChangesAsync();

                SendNotification(postedQuestion.student.Username, user.Username, user.ProfileImage, "Replied to your question.",true, "Students", "Sessions", "SessionId=" + obj.SessionID);

                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = rep.ReplyID + "$" + rep.SessionID }
                };
            }
            else
            { 
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "null" }
                };
            }
        }
        public async Task<ActionResult> Chat(ChatModel reply)
        {
            Reply obj = new Reply();
            obj.ReplyID = Guid.NewGuid();
            obj.ReplierID = new Guid(User.Identity.GetUserId());
            obj.SessionID = reply.sessionID;
            obj.PostedTime = DateTime.Now;

          


            reply.replyDetail=reply.replyDetail.Replace(Environment.NewLine, "<br/>");
            obj.Details = reply.replyDetail;
            db.Replies.Add(obj);

            var session = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault();
            session.NewMessageStudent = true;
            db.Entry(session).State = EntityState.Modified;
            
            await db.SaveChangesAsync();

            string adjustedTimeTutor;
            string adjustedTimeStudent;
            DateTime TutorTime = obj.PostedTime.AddHours(7);
            DateTime StudentTime = obj.PostedTime.AddHours(7);
            if (!string.IsNullOrEmpty(session.tutor.Timezone))
            {
                string[] splited = session.tutor.Timezone.Split('$');
                string[] hoursMin = splited[1].Split(':');
                double minutes = (Convert.ToDouble(hoursMin[0]) * 60);
                if (minutes < 0)
                    minutes = minutes - Convert.ToDouble(hoursMin[1]);
                else
                    minutes = minutes + Convert.ToDouble(hoursMin[1]);

                TutorTime=TutorTime.AddMinutes(minutes);
            }
            adjustedTimeTutor = TutorTime.ToString();

            if (!string.IsNullOrEmpty(session.question.student.Timezone))
            {
                string[] splited = session.question.student.Timezone.Split('$');
                string[] hoursMin = splited[1].Split(':');
                double minutes = (Convert.ToDouble(hoursMin[0]) * 60);
                if (minutes < 0)
                    minutes = minutes - Convert.ToDouble(hoursMin[1]);
                else
                    minutes = minutes + Convert.ToDouble(hoursMin[1]);

               StudentTime= StudentTime.AddMinutes(minutes);
            }
            adjustedTimeStudent = StudentTime.ToString();


            var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
            var username = User.Identity.Name;
           
            //part moved up
            var student = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().question.student;
            var username2 = student.Username;
            var status = db.online.Where(c => c.Username == username2).FirstOrDefault().Status;

            var imgsrc = db.Tutors.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
            string message = generateMessage(username, obj.Details, imgsrc, adjustedTimeTutor, obj.ReplyID.ToString(), status);
            SendChatTutorReciever(obj.SessionID.ToString(),username, message, context); //send message to urself 

            string message2 = generateMessage(username, obj.Details, imgsrc, adjustedTimeStudent, obj.ReplyID.ToString(), status);
            SendChatStudentReiever(obj.SessionID.ToString(), username2, message2, context); //send message to other person 
            //context.Clients.All.test("hello world");

            return new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { result = obj.ReplyID + "$" + obj.SessionID }
            };

        }
        public async Task<JsonResult> Hire(Offer question)
        {
            var userId = User.Identity.GetUserId();
            var sessionId = question.SessionId;
            var session = db.sessions.Where(c => c.SessionID == sessionId && c.question.StudentID == new Guid(userId)).First();
            var user = session.question.student;
            if(user.CurrentBalance < session.OfferedFees)
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "You donot have enough funds to hire the expert.Go to Account Settings and add funds first." }
                };
            }
            else if(session.Status == Status.Offered)
            {
                session.Status = Status.Hired;
                var quest = session.question;
                quest.Status = Status.Hired;
                db.Entry(quest).State = EntityState.Modified;
                db.Entry(session).State = EntityState.Modified;

                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID = new Guid(User.Identity.GetUserId());
                obj.SessionID = sessionId;
                obj.PostedTime = DateTime.Now;
                obj.Details = " Automatically Generated Message: I have Hired you for " + session.OfferedFees + "$. You can start working on task." ;
                session.Replies.Add(obj);

                

                db.SaveChanges();

           
                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                var username = User.Identity.Name;
                var imgsrc = db.Students.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(), obj.ReplyID.ToString());
                SendChatMessageStudentReciever(obj.SessionID.ToString(), username, message, context); //send message to urself 
                var tutor = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().tutor;
                var username2 = tutor.Username;
                SendChatMessageTutorReciever(obj.SessionID.ToString(), username2, message, context); //send message to other person 

                //send button
               
                var message2 = "  <button type=\"button\" id=\"hire\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#invoiceNewModal\">Send Invoice</button>";
                                                                                       
                SendButtonStudent(sessionId.ToString(), username2, message2, context); //send message to other person 


                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "success" }
                };

            }
            else
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "fail" }
                };

            }
        }
        public async Task<ActionResult> Chat(ChatModel reply)
        {
                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID= new Guid(User.Identity.GetUserId());
                obj.SessionID = reply.sessionID;
                obj.PostedTime = DateTime.Now;
                obj.Details = reply.replyDetail;
            
                db.Replies.Add(obj);

                var session = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault();
                session.NewMessageTutor = true;
                db.Entry(session).State = EntityState.Modified;

                await db.SaveChangesAsync();

                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                var username = User.Identity.Name;
                var imgsrc = db.Students.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(),obj.ReplyID.ToString());
                SendChatMessageStudentReciever(obj.SessionID.ToString(), username, message, context); //send message to urself 
                var tutor = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().tutor;
                var username2 = tutor.Username;
                SendChatMessageTutorReciever(obj.SessionID.ToString(), username2, message, context); //send message to other person 

            return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = obj.ReplyID +"$" + obj.SessionID }
                };
           
        }
        public async Task<JsonResult> PostQuestion([Bind(Include = "QuestionID,StudentID,TutorID,Title,Details,Status,Amount,CategoryID,DueDate,PostedTime")] QuestionViewModel question)
        {
            if (ModelState.IsValid)
            {
                Question quest = Mapper.Map<QuestionViewModel, Question>(question);
                quest.QuestionID = Guid.NewGuid();
                quest.PostedTime = DateTime.Now;
                //initial posted Question Status
                quest.Status = Status.Posted;
                quest.TutorID = question.TutorID;

                if(question.TutorID!=null)
                {
                    Session obj = new Session();
                    obj.SessionID = Guid.NewGuid();
                    obj.TutorID = question.TutorID; 
                    obj.QuestionID = quest.QuestionID;
                    obj.PostedTime = DateTime.Now;
                    obj.Status = Status.Posted;
                    obj.NewMessageTutor = true;
                    db.sessions.Add(obj);

                    Reply rep = new Reply();
                    rep.ReplyID = Guid.NewGuid();
                    rep.SessionID = obj.SessionID;
                    rep.ReplierID = quest.StudentID;
                    rep.PostedTime = DateTime.Now;
                    rep.Details =quest.Title;
                    db.Replies.Add(rep);
                }


                //user posting question id
                quest.StudentID = new Guid(User.Identity.GetUserId());
                db.Questions.Add(quest);
                await db.SaveChangesAsync();

                var student=db.Students.Find(quest.StudentID);
       
                string response = quest.QuestionID +"$"+quest.Title+ "$" + student.ProfileImage + "%" + User.Identity.Name +  "$" + quest.Amount+"$"+quest.PostedTime+"$" + quest.DueDate ;
               
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = response }
                };
               
            }

            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
            return null;
            
        }
        public async Task<JsonResult> ApprovePayment(Offer question)
        {
            var user = User.Identity.GetUserId();
            var sessionId = question.SessionId;
            var session = db.sessions.Where(c => c.SessionID == sessionId && c.question.StudentID == new Guid(user)).First();
            if (session.Status == Status.Invoiced)
            {
                session.Status = Status.Approved;
                session.isClosed = true;
                var quest = session.question;
                quest.Status = Status.Approved;
                db.Entry(quest).State = EntityState.Modified;
                db.Entry(session).State = EntityState.Modified;
               
                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID = new Guid(User.Identity.GetUserId());
                obj.SessionID = sessionId;
                obj.PostedTime = DateTime.Now;
                obj.Details = " Automatically Generated Message: I have Approved the payment for " + session.OfferedFees + "$. ";
                session.Replies.Add(obj);

                db.SaveChanges();


                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                var username = User.Identity.Name;
                var imgsrc = db.Students.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(), obj.ReplyID.ToString());
                SendChatMessageStudentReciever(obj.SessionID.ToString(), username, message, context); //send message to urself 
                var tutor = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().tutor;
                var username2 = tutor.Username;
                SendChatMessageTutorReciever(obj.SessionID.ToString(), username2, message, context); //send message to other person 

                var message2 = " <button type=\"button\" id=\"accepted\" disabled class=\"btn btn-primary\">Accepted Invoice</button>";

                SendButtonStudent(sessionId.ToString(), username2, message2, context); //send message to other person 


                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "success" }
                };

            }
            else
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "fail" }
                };

            }
        }
        public async Task<JsonResult> SendOffer( Offer question)
        {
            var user = User.Identity.GetUserId();
            var sessionId = question.SessionId;
            var session = db.sessions.Where(c => c.SessionID ==sessionId && c.TutorID.Value ==new Guid(user)).First();
            if(session.Status==Status.Posted || session.Status == Status.Offered)
            { 
                session.OfferedFees = question.amount;
                session.Status = Status.Offered;
                db.Entry(session).State = EntityState.Modified;

                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID = new Guid(User.Identity.GetUserId());
                obj.SessionID = sessionId;
                obj.PostedTime = DateTime.Now;
                obj.Details = " Automatically Generated Message: I have sent offer to do your work for " + question.amount + "$. Press Hire Button if you are interested in my services.";
                session.Replies.Add(obj);
                db.SaveChanges();

                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                //send message reply
                var username = User.Identity.Name;
                var imgsrc = db.Tutors.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(), obj.ReplyID.ToString());
                SendChatTutorReciever(obj.SessionID.ToString(), username, message, context); //send message to urself 

                var student = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().question.student;
                var username2 = student.Username;
                SendChatStudentReiever(obj.SessionID.ToString(), username2, message, context); //send message to other person 
               
                //send button update
                var message2 = "<button type=\"button\" id=\"offer\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#hireNewModal\">Hire for ("+question.amount+"$)</button>";
                SendButtonStudent(sessionId.ToString(), username2, message2, context); //send message to other person 

                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = question.amount }
                };
            }
            else
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "" }
                };
            }

        }
 public async Task<ActionResult> QuestionsReply(TutorQuestionDetails reply)
 {
     var userId= new Guid(User.Identity.GetUserId());
     var question = db.Questions.Where(c => c.QuestionID == reply.QuestionID);
     var postedQuestion = question.FirstOrDefault();
     var selectedSession = postedQuestion.Sessions.Where(c => c.TutorID.Value == userId).FirstOrDefault();
     if (selectedSession == null)
     { 
         Session obj = new Session();
         obj.SessionID = Guid.NewGuid();
         obj.TutorID = userId;
         //obj.StudentID = reply.StudentID;
         obj.QuestionID = reply.QuestionID;
         obj.PostedTime = DateTime.Now;
         obj.Status = Status.Posted;
         db.sessions.Add(obj);
     
         Reply rep = new Reply();
         rep.ReplyID =  Guid.NewGuid();
         rep.SessionID = obj.SessionID;
         rep.ReplierID = obj.TutorID.Value;
         rep.PostedTime = DateTime.Now;
         rep.Details = reply.replyDetails;
         db.Replies.Add(rep);
         await db.SaveChangesAsync();
         return new JsonResult()
         {
             JsonRequestBehavior = JsonRequestBehavior.AllowGet,
             Data = new { result = rep.ReplyID + "$" + rep.SessionID }
         };
     }
     else
     { 
         return new JsonResult()
         {
             JsonRequestBehavior = JsonRequestBehavior.AllowGet,
             Data = new { result = "null" }
         };
     }
 }
        public async Task<JsonResult> Hire(Offer question)
        {
            var userId = User.Identity.GetUserId();
            var sessionId = question.SessionId;
            var session = db.sessions.Where(c => c.SessionID == sessionId && c.question.StudentID == new Guid(userId)).First();
            var user = session.question.student;
            if(user.CurrentBalance < session.OfferedFees)
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "You donot have enough funds to hire the expert.Go to Account Settings and add funds first." }
                };
            }
            else if(session.Status == Status.Offered)
            {
                session.Status = Status.Hired;
                var quest = session.question;
                quest.Status = Status.Hired;
                user.CurrentBalance = user.CurrentBalance - (float)session.OfferedFees;
                db.Entry(user).State = EntityState.Modified; 
                db.Entry(quest).State = EntityState.Modified;
                db.Entry(session).State = EntityState.Modified;

                //hire transaction
                DBEntities.Transaction tran = new DBEntities.Transaction();
                tran.TransactionID = Guid.NewGuid();
                tran.SessionID = sessionId;
                tran.Status = Status.Hired;
                tran.OfferedFees = question.amount;
                tran.PostedTime = DateTime.Now;
                db.transcations.Add(tran);

                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID = new Guid(User.Identity.GetUserId());
                obj.SessionID = sessionId;
                obj.PostedTime = DateTime.Now;
                obj.Details = " Automatically Generated Message: I have Hired you for $" + session.OfferedFees + ". You can start working on task." ;
                session.Replies.Add(obj);

                

                db.SaveChanges();

           
                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                var username = User.Identity.Name;
                var imgsrc = db.Students.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(), obj.ReplyID.ToString(),false);
                SendChatMessageStudentReciever(obj.SessionID.ToString(), username, message, context); //send message to urself 
                var tutor = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().tutor;
                var username2 = tutor.Username;
                SendChatMessageTutorReciever(obj.SessionID.ToString(), username2, message, context); //send message to other person 

                //send button
               
                var message2 = "  <button type=\"button\" id=\"hire\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#invoiceNewModal\">Send Invoice</button>";
                                                                                       
                SendButtonStudent(sessionId.ToString(), username2, message2, context); //send message to other person 
                SendNotification(username2, username,imgsrc, "I have hired you for $"+session.OfferedFees,true,"Tutors","Sessions", "SessionId="+sessionId);

                var email = db.Users.Where(c => c.Id == quest.TutorID.ToString()).FirstOrDefault().Email;
                String subject = "Hired on MezoExperts.com";
                String bodyText = username + " has hired you for the job.";
                string fileTemplate = "passwordreset.html";
                await sendEmail(email, subject, bodyText,fileTemplate,"");
                
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "success" }
                };

            }
            else
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "fail" }
                };

            }
        }
        public async Task<JsonResult> ApprovePayment(Offer question)
        {
            var user = User.Identity.GetUserId();
            var sessionId = question.SessionId;
            var session = db.sessions.Where(c => c.SessionID == sessionId && c.question.StudentID == new Guid(user)).First();
            if (session.Status == Status.Invoiced)
            {
                session.Status = Status.Approved;
                session.isClosed = true;
                var quest = session.question;
                quest.Status = Status.Approved;
                db.Entry(quest).State = EntityState.Modified;
                db.Entry(session).State = EntityState.Modified;

                DBEntities.Transaction tran = new DBEntities.Transaction();
                tran.TransactionID = Guid.NewGuid();
                tran.SessionID = sessionId;
                tran.Status = Status.Approved;
                tran.OfferedFees = question.amount;
                tran.PostedTime = DateTime.Now;
                db.transcations.Add(tran);

                Reply obj = new Reply();
                obj.ReplyID = Guid.NewGuid();
                obj.ReplierID = new Guid(User.Identity.GetUserId());
                obj.SessionID = sessionId;
                obj.PostedTime = DateTime.Now;
                obj.Details = " Automatically Generated Message: I have Approved the payment for " + session.OfferedFees + "$. ";
                session.Replies.Add(obj);

                var tutor = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().tutor;
                tutor.CurrentEarning = tutor.CurrentEarning + (float)session.OfferedFees;
                db.Entry(tutor).State = EntityState.Modified; 

                db.SaveChanges();


                var context = GlobalHost.ConnectionManager.GetHubContext<TutorStudentChat>();
                var username = User.Identity.Name;
                var imgsrc = db.Students.Where(c => c.Username == username).FirstOrDefault().ProfileImage;
                string message = generateMessage(username, obj.Details, imgsrc, obj.PostedTime.ToString(), obj.ReplyID.ToString(),false);
                SendChatMessageStudentReciever(obj.SessionID.ToString(), username, message, context); //send messageFp to urself 
                //var tutor = db.sessions.Where(c => c.SessionID == obj.SessionID).FirstOrDefault().tutor;
                var username2 = tutor.Username;
                SendChatMessageTutorReciever(obj.SessionID.ToString(), username2, message, context); //send message to other person 

                var message2 = " <button type=\"button\" id=\"accepted\" disabled class=\"btn btn-primary\">Accepted Invoice</button>";

                SendButtonStudent(sessionId.ToString(), username2, message2, context); //send message to other person 
                SendNotification(username2, session.question.student.Username, session.question.student.ProfileImage, "I have approved the payment of $" + session.OfferedFees,true, "Tutors", "Sessions", "SessionId=" + sessionId);
                //close sessions
                DeleteSessionMessageTutor(sessionId.ToString(), username2, "", context);
                DeleteSessionMessageTutor(sessionId.ToString(), username, "", context);

                var email = db.Users.Where(c => c.Id == quest.TutorID.ToString()).FirstOrDefault().Email;
                String subject = "Invoice Approved on MezoExperts.com";
                String bodyText = username + " approved the Invoice.";
                string FileTemplate = "passwordreset.html";
                await sendEmail(email, subject, bodyText, FileTemplate, "");


                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "success" }
                };

            }
            else
            {
                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = "fail" }
                };

            }
        }
        public async Task<JsonResult> PostQuestion([Bind(Include = "QuestionID,StudentID,TutorID,Title,Details,Status,Amount,CategoryID,DueDate,PostedTime")] QuestionViewModel question)
        {
            if (ModelState.IsValid)
            {
                Question quest = Mapper.Map<QuestionViewModel, Question>(question);
                quest.QuestionID = Guid.NewGuid();
                quest.PostedTime = DateTime.Now;
                //initial posted Question Status
                quest.Status = Status.Posted;
                quest.TutorID = question.TutorID;
                quest.Details=quest.Details.Replace(Environment.NewLine, "<br/>");

                bool singleTutor = false;
                string sessionId = null;
                string postId = quest.QuestionID.ToString();
                if(question.TutorID!=null)
                {
                    singleTutor = true;
                    Session obj = new Session();
                    obj.SessionID = Guid.NewGuid();
                    sessionId = obj.SessionID.ToString();
                    obj.TutorID = question.TutorID; 
                    obj.QuestionID = quest.QuestionID;
                    obj.PostedTime = DateTime.Now;
                    obj.Status = Status.Posted;
                    obj.NewMessageTutor = true;
                    db.sessions.Add(obj);

                    Reply rep = new Reply();
                    rep.ReplyID = Guid.NewGuid();
                    rep.SessionID = obj.SessionID;
                    rep.ReplierID = quest.StudentID;
                    rep.PostedTime = DateTime.Now;
                    rep.Details =quest.Title;
                    db.Replies.Add(rep);
                }


                //user posting question id
                quest.StudentID = new Guid(User.Identity.GetUserId());
                db.Questions.Add(quest);
                await db.SaveChangesAsync();

                var student=db.Students.Find(quest.StudentID);
       
                string response = quest.QuestionID +"$"+quest.Title+ "$" + student.ProfileImage + "%" + User.Identity.Name +  "$" + quest.Amount+"$"+quest.PostedTime+"$" + quest.DueDate ;

               
                //send emails
                if (singleTutor == false)
                {
                    var tutors = db.Tutors.Where(c => c.IsCompletedProfile == true).ToList();
                    var allusers = db.Users.ToList();

                   

                            foreach (var v in tutors)
                            {
                               
                                    var emailUser = allusers.Where(c => c.UserName == v.Username).FirstOrDefault();
                                    SendNotification(emailUser.UserName, student.Username, student.ProfileImage, "New Question posted.",true, "Tutors", "QuestionDetails", "PostId=" + postId);

                                    if (emailUser != null)
                                    {
                                        // Send the emails here
                                        var email = emailUser.Email;
                                        String subject = "New Question Posted on MezoExperts.com";
                                        String bodyText = question.Title;
                                        String optional = quest.Details;
                                        string FileTemplate = "email.html";
                                        await sendEmail(email, subject, bodyText, FileTemplate, optional);
                                    }
                        }
                    

                }
                else
                {
                        var tutor = db.Users.Find(quest.TutorID.ToString());
                      
                        SendNotification(tutor.UserName, student.Username, student.ProfileImage, "I have a new task for you.",true, "Tutors", "Sessions", "SessionId=" + sessionId);

                        var email = tutor.Email;
                        String subject = "New Question Posted on MezoExperts.com";
                        String bodyText = question.Title;
                        String optional = quest.Details;
                        string FileTemplate = "email.html";
                        await sendEmail(email, subject, bodyText, FileTemplate, optional);
                    
                }

                return new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new { result = response }
                };
               
            }

            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
            return null;
            
        }