public JsonResult saveExaminationData(SaveDocotor Doctormodel)
        {
            try
            {
                ArogyaParivarEntities context = new ArogyaParivarEntities();

                T_Examination modelScreenings = new T_Examination()
                {
                    ComplaintID         = Doctormodel.ChiefComplaintID,
                    PresentingComplaint = Doctormodel.HistoryPresentingComplaint,
                    PastMedicalHistory  = Doctormodel.PastMedicalHistory,
                    PastSurgicalHistory = Doctormodel.PastSurgicalHistory,
                    FamilyHistory       = Doctormodel.FamilyHistory,
                    CurrentMedication   = Doctormodel.CurrentMedication,
                    Diagnosis           = Doctormodel.Diagnosis,
                    Tests         = Doctormodel.Tests,
                    TreatmentPlan = Doctormodel.TreatMentPlan,
                    ArogyaID      = Session["arogyid"].ToString(),
                    Token_Number  = Convert.ToInt32(Session["Token"]),
                    CreateDate    = DateTime.Now,
                    Active        = true,
                    UserID        = Convert.ToInt32(Session["UserID"]),
                    ScreeningID   = Doctormodel.ScreeningoutcomeID
                };
                context.T_Examination.Add(modelScreenings);
                context.SaveChanges();
                return(Json("Data Saved", JsonRequestBehavior.AllowGet));
            }
            catch
            {
                return(Json(-1, JsonRequestBehavior.AllowGet));
            }
        }
        public IList <DashBordModel> GetNurseDashbord()
        {
            IList <DashBordModel> BookList = new List <DashBordModel>();
            ArogyaParivarEntities context  = new ArogyaParivarEntities();



            var query = from token in context.T_Token

                        from reg in context.T_PatientInfo
                        .Where(x => x.ArogyaID == token.ArogyaID)

                        from scr in context.T_Screenings
                        .Where(x => x.ArogyaID == token.ArogyaID).DefaultIfEmpty()
                        from gender in context.M_Gender
                        .Where(x => x.ID == reg.FK_GenderID)
                        where  EntityFunctions.TruncateTime(token.Tokem_Date).Value == EntityFunctions.TruncateTime(DateTime.Now).Value&&
                        scr.ArogyaID == null
                        // where patient.FirstName.Contains(searchString) || patient.SurName.Contains(searchString) || patient.ContactNumber.Contains(searchString)
                        select new DashBordModel
            {
                Tokem_Date  = token.Tokem_Date,
                ArogyaID    = token.ArogyaID,
                PatientName = reg.FirstName + reg.SurName,
                TokenNumber = token.Token_Number,
                GenderName  = gender.Gender,
                Age         = reg.Age
            };



            return(BookList = query.Distinct().ToList());
        }
        public JsonResult saveMedicationData(string DrugName, int Doseid, int Frequencyid, string Duration, int Routid, string Instruction)
        {
            try
            {
                int savedata = 0;
                ArogyaParivarEntities context = new ArogyaParivarEntities();

                T_Medication modelScreening = new T_Medication()
                {
                    DrugName           = DrugName,
                    DoseID             = Doseid,
                    FrequencyID        = Frequencyid,
                    Duration           = Duration,
                    RouteID            = Routid,
                    SpecialInstruction = Instruction,
                    ArogyaID           = Session["arogyid"].ToString(),
                    Token_Number       = Convert.ToInt32(Session["Token"]),
                    CreateDate         = DateTime.Now,
                    UserID             = Convert.ToInt32(Session["UserID"])
                };
                context.T_Medication.Add(modelScreening);
                context.SaveChanges();
                dynamic obj = new ExpandoObject();
                obj.Token    = modelScreening.Token_Number;
                obj.Arogyaid = modelScreening.ArogyaID;
                obj.date     = modelScreening.CreateDate;
                return(Medication(obj.Arogyaid, obj.Token, obj.date));
                // Json(obj, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return(Json(-1, JsonRequestBehavior.AllowGet));
            }
        }
        public JsonResult Medication(string argid, int token, DateTime dt)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();

            var query = context.SP_GetMedicationDetailsByArogyaID(argid, token, dt);

            return(Json(query, JsonRequestBehavior.AllowGet));
        }
        public IList<DashBordModel> GetDoctorDashbord()
        {
            IList<DashBordModel> BookList = new List<DashBordModel>();
            ArogyaParivarEntities context = new ArogyaParivarEntities();


            var query = from token in context.T_PatientInfo

                        from reg in context.T_Screenings
                      .Where(x => x.ArogyaID == token.ArogyaID)

                        from scr in context.T_Examination
                       .Where(x => x.ArogyaID == token.ArogyaID).DefaultIfEmpty()


                        from reg1 in context.M_PComplaints
                        .Where(x => x.ID == reg.ComplaintID)
                        from gender in context.M_Gender
                        .Where(x => x.ID == token.FK_GenderID)

                        where EntityFunctions.TruncateTime(reg.CreateDate).Value == EntityFunctions.TruncateTime(DateTime.Now).Value && reg.ScreenOutcomeID == 1 || reg.ScreenOutcomeID == 3
                        && scr.ArogyaID == null
                        // where patient.FirstName.Contains(searchString) || patient.SurName.Contains(searchString) || patient.ContactNumber.Contains(searchString)
                        select new DashBordModel
                        {
                            Tokem_Date = reg.CreateDate,
                            ArogyaID = token.ArogyaID,
                            PatientName = token.FirstName + token.SurName,
                            TokenNumber = reg.Token_Number,
                            Age = token.Age,
                            GenderName = gender.Gender,
                            ComplaintName = reg1.M_PresentingComplainting,
                            screeningoutcomeID = reg.ScreenOutcomeID.Value

                        };

            BookList = query.Distinct().ToList();
            if (BookList.Count > 0)
            {
                var updatelist = BookList.Where(x => x.screeningoutcomeID == 3).ToList();
                if (updatelist != null && updatelist.Count > 0)
                    updatelist[0].rowcolor = "Follow Up";


            }

            return BookList;


        }
        public IList <DashBordModel> GetDoctorDashbord()
        {
            IList <DashBordModel> BookList = new List <DashBordModel>();
            ArogyaParivarEntities context  = new ArogyaParivarEntities();


            var query = from token in context.T_PatientInfo

                        from reg in context.T_Screenings
                        .Where(x => x.ArogyaID == token.ArogyaID)

                        from scr in context.T_Examination
                        .Where(x => x.ArogyaID == token.ArogyaID).DefaultIfEmpty()


                        from reg1 in context.M_PComplaints
                        .Where(x => x.ID == reg.ComplaintID)
                        from gender in context.M_Gender
                        .Where(x => x.ID == token.FK_GenderID)

                        where EntityFunctions.TruncateTime(reg.CreateDate).Value == EntityFunctions.TruncateTime(DateTime.Now).Value&& reg.ScreenOutcomeID == 1 || reg.ScreenOutcomeID == 3 &&
                        scr.ArogyaID == null
                        // where patient.FirstName.Contains(searchString) || patient.SurName.Contains(searchString) || patient.ContactNumber.Contains(searchString)
                        select new DashBordModel
            {
                Tokem_Date         = reg.CreateDate,
                ArogyaID           = token.ArogyaID,
                PatientName        = token.FirstName + token.SurName,
                TokenNumber        = reg.Token_Number,
                Age                = token.Age,
                GenderName         = gender.Gender,
                ComplaintName      = reg1.M_PresentingComplainting,
                screeningoutcomeID = reg.ScreenOutcomeID.Value
            };

            BookList = query.Distinct().ToList();
            if (BookList.Count > 0)
            {
                var updatelist = BookList.Where(x => x.screeningoutcomeID == 3).ToList();
                if (updatelist != null && updatelist.Count > 0)
                {
                    updatelist[0].rowcolor = "Follow Up";
                }
            }

            return(BookList);
        }
        public IList<DashBordModel> GetNurseDashbord()
        {
            IList<DashBordModel> BookList = new List<DashBordModel>();
            ArogyaParivarEntities context = new ArogyaParivarEntities();

     



            var query = from token in context.T_Token

                        from reg in context.T_PatientInfo
                        .Where(x=>x.ArogyaID == token.ArogyaID)

                       from scr in context.T_Screenings
                        .Where(x=>x.ArogyaID == token.ArogyaID).DefaultIfEmpty()
                        from gender in context.M_Gender
                        .Where(x => x.ID == reg.FK_GenderID)
                        where  EntityFunctions.TruncateTime( token.Tokem_Date).Value == EntityFunctions.TruncateTime(DateTime.Now).Value &&
                          scr.ArogyaID ==null
                        // where patient.FirstName.Contains(searchString) || patient.SurName.Contains(searchString) || patient.ContactNumber.Contains(searchString)
                        select new DashBordModel
                        {
                            Tokem_Date = token.Tokem_Date,
                            ArogyaID = token.ArogyaID,
                            PatientName = reg.FirstName + reg.SurName,
                            TokenNumber = token.Token_Number,
                            GenderName = gender.Gender,
                            Age = reg.Age
                            

                        };

        
           
            return BookList = query.Distinct().ToList();


        }
        public ActionResult VideoCasesheet(string arogyaID)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();
            List<Episode> episodes = new List<Episode>();
            List<Episode> finalEpisodes = new List<Episode>();

            EncounterSummaryBll encounterSummaryBll = new EncounterSummaryBll();

            List<EncounterSummaryModel> encounters = encounterSummaryBll.GetEncounterList(arogyaID).OrderBy(x => x.CreateDate.Value).ToList();
            List<T_Appointments> appointments = encounterSummaryBll.GetAppointmentList(arogyaID);

            foreach (EncounterSummaryModel encounter in encounters)
            {
                Episode episode;
                var eps = episodes.FindAll(x => x.ComplaintID == encounter.ComplaintID.Value);
                if (eps.Count == 0)
                {
                    episode = new Episode { ComplaintID = encounter.ComplaintID.Value, ComplaintName = encounter.ComplaintName, LastModifiedDate = encounter.CreateDate.Value };
                    episode.encounterSummaryList.Add(encounter);
                    episodes.Add(episode);
                }
                else
                {
                    if (encounter.CreateDate.Value.Date.Subtract(eps[eps.Count - 1].LastModifiedDate.Date).Days < 30
                        || appointments.Where(x => encounter.CreateDate.Value.Date.Subtract(x.ApptDate.Value.Date).Days < 30
                                                    && x.ApptDate.Value.Date.Subtract(eps[eps.Count - 1].LastModifiedDate.Date).Days > 0
                                                    && x.ComplaintID == encounter.ComplaintID
                                             ).ToList().Count > 0)
                    {
                        eps[eps.Count - 1].LastModifiedDate = encounter.CreateDate.Value;
                        eps[eps.Count - 1].encounterSummaryList.Add(encounter);
                    }
                    else
                    {
                        episode = new Episode { ComplaintID = encounter.ComplaintID.Value, ComplaintName = encounter.ComplaintName, LastModifiedDate = encounter.CreateDate.Value };
                        episode.encounterSummaryList.Add(encounter);
                        episodes.Add(episode);
                    }
                }
            }
            episodes = episodes.OrderByDescending(x => x.LastModifiedDate).ToList();
            ViewBag.Episodes = JsonConvert.SerializeObject(episodes);
            return View();
        }
        public JsonResult Allrgy(int tokenNumber, string arogyaID)
        {

            ArogyaParivarEntities context = new ArogyaParivarEntities();
            var query2 = from allergy in context.T_Allergies

                         from at in context.M_AllergyType
                         .Where(x => x.ID == allergy.AllergenID).DefaultIfEmpty()
                         //on allergy.AllergenID equals at.ID

                         from ar in context.M_Reaction
                         .Where(x => x.ID == allergy.ReactionID).DefaultIfEmpty()
                         //on allergy.ReactionID equals ar.ID

                         from asev in context.M_Severity
                         .Where(x => x.ID == allergy.SeverityID).DefaultIfEmpty()
                         //on allergy.SeverityID equals asev.ID

                         from ast in context.M_Status
                         .Where(x => x.ID == allergy.StatusID).DefaultIfEmpty()
                         //on allergy.StatusID equals ast.ID

                         where allergy.Token_Number == tokenNumber
                            && EntityFunctions.TruncateTime(allergy.CreateDate).Value == EntityFunctions.TruncateTime(DateTime.Now).Value
                            && allergy.ArogyaID == arogyaID
                         select new Allergy
                         {
                             AllergyType = at.AllergyType,

                             ReactionName = ar.Reaction,
                             SeverityrName = asev.Severity,
                             Status = ast.M_StatusName,
                             CreateDate = allergy.CreateDate.Value
                             //CreateDateString=allergy.CreateDate.Value.ToString("dd/MM/yyyy")
                         };

            return Json(query2.ToList(), JsonRequestBehavior.AllowGet);

        }
        public ActionResult PatientHealthRecord(Screening model, string command)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();
            try
            {
                try
                {



                    T_Vitals Vitals = new T_Vitals()
                    {
                        Height = model.Height,
                        Weight = model.Weight,
                        BMI = model.BMI,
                        SysBP = model.SysBP,
                        DiaBP = model.DiaBP,
                        Temparature = model.Temparature,
                        Pulse = model.Pulse,
                        Respiratory = model.Respiratory,
                        Token_Number = 1

                    };

                    T_Screenings screenings = new T_Screenings()
                    {
                        ComplaintID = model.ComplaintID,
                        CheckListID = model.CheckListID,
                        PresentingComplaint = model.PresentingComplaint,
                        PastMedicalHistory = model.PastMedicalHistory,
                        PastSurgicalHistory = model.PastSurgicalHistory,
                        FamilyHistory = model.FamilyHistory,
                        CurrentMedication = model.CurrentMedication,
                        ECGOutcomeID = model.ECGOutcomeID,
                        ScreenOutcomeID = model.ScreenOutcomeID,
                        SpecialtyID = model.SpecialtyID,
                        AppointDate = model.AppointDate,
                        CreateDate = model.CreateDate,
                        Token_Number = 1
                    };
                    context.T_Screenings.Add(screenings);
                    context.SaveChanges();
                    return RedirectToAction("PatientSearch");

                }
                catch
                {
                    return View(model);
                }


            }
            catch
            {
                return View(model);
            }
        }
        public JsonResult saveScreenData(Screening model)
        {



            try
            {

                ArogyaParivarEntities context = new ArogyaParivarEntities();




                T_Screenings modelScreenings = new T_Screenings()
                {
                    PresentingComplaint = model.PresentingComplaint,
                    PastMedicalHistory = model.PastMedicalHistory,
                    PastSurgicalHistory = model.PastSurgicalHistory,
                    FamilyHistory = model.FamilyHistory,
                    CurrentMedication = model.CurrentMedication,
                    ECGOutcomeID = model.ECGOutcomeID,
                    ScreenOutcomeID = model.ScreenOutcomeID,
                    ArogyaID = Session["strArogyaID"].ToString(),
                    Token_Number = Convert.ToInt32(Session["intTokenNumber"].ToString()),
                    ComplaintID = model.ComplaintID,
                    CheckListID = model.chkId,
                    CreateDate = DateTime.Now,
                    UserID = Convert.ToInt32(Session["UserID"]),
                };

                context.T_Screenings.Add(modelScreenings);
                context.SaveChanges();


                return Json(1, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult saveData(int AllrgyTypid, int Reactionid, int Severityid, int Statusid)
        {
            try
            {

                ArogyaParivarEntities context = new ArogyaParivarEntities();

                T_Allergies modelScreening = new T_Allergies()
                  {
                      AllergenID = AllrgyTypid,
                      ReactionID = Reactionid,
                      SeverityID = Severityid,
                      StatusID = Statusid,
                      ArogyaID = Session["strArogyaID"].ToString(),
                      Token_Number = Convert.ToInt32(Session["intTokenNumber"].ToString()),
                      CreateDate = DateTime.Now,
                      UserID = Convert.ToInt32(Session["UserID"])
                  };
                context.T_Allergies.Add(modelScreening);
                context.SaveChanges();
                return Allrgy(Convert.ToInt32(Session["intTokenNumber"]), Session["strArogyaID"].ToString());
            }
            catch
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult saveVitaltData(Screening model)
        {
            try
            {

                ArogyaParivarEntities context = new ArogyaParivarEntities();
                T_Vitals modelVitals = new T_Vitals()
                {
                    Height = model.Height,
                    Weight = model.Weight,
                    BMI = model.BMI,
                    SysBP = model.SysBP,
                    Pulse = model.Pulse,
                    DiaBP = model.DiaBP,
                    Temparature = model.Temparature,
                    Respiratory = model.Respiratory,
                    ArogyaID = Session["strArogyaID"].ToString(),
                    UserID = Convert.ToInt32(Session["UserID"]),
                    Token_Number = Convert.ToInt32(Session["intTokenNumber"].ToString()),
                    CreateDate = DateTime.Now,
                };
                context.T_Vitals.Add(modelVitals);
                context.SaveChanges();
                return Json(1, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult CadSaveData(Screening model)
        {
            //string str = "Anemia";

            ArogyaParivarEntities context = new ArogyaParivarEntities();
            double k = 0.0;
            try
            {
                for (int i = 1; i <= 7; i++)
                {
                    k += model.Cadmiaradio[i - 1] * model.CadmiaWeightage[i - 1] / 100.0;

                    T_ChkAnemia chkanemia = new T_ChkAnemia()
                    {

                        ChkID = i,
                        AnsID = model.Cadmiaradio[i - 1],
                        ArogyaID = Session["strArogyaID"].ToString(),
                        Token_Number = Convert.ToInt32(Session["intTokenNumber"].ToString()),
                        CreateDate = DateTime.Now,
                        UserID = Convert.ToInt32(Session["UserID"])


                    };

                    context.T_ChkAnemia.Add(chkanemia);
                    context.SaveChanges();
                }

                return Json(new { score = k }, JsonRequestBehavior.AllowGet);

            }
            catch
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult saveMedicationData(string DrugName, int Doseid, int Frequencyid, string Duration, int Routid, string Instruction)
        {
            try
            {
                int savedata = 0;
                ArogyaParivarEntities context = new ArogyaParivarEntities();

                T_Medication modelScreening = new T_Medication()
                {
                    DrugName = DrugName,
                    DoseID = Doseid,
                    FrequencyID = Frequencyid,
                    Duration = Duration,
                    RouteID = Routid,
                    SpecialInstruction = Instruction,
                    ArogyaID = Session["arogyid"].ToString(),
                    Token_Number = Convert.ToInt32(Session["Token"]),
                    CreateDate = DateTime.Now,
                    UserID = Convert.ToInt32(Session["UserID"])


                };
                context.T_Medication.Add(modelScreening);
                context.SaveChanges();
                dynamic obj = new ExpandoObject();
                obj.Token = modelScreening.Token_Number;
                obj.Arogyaid = modelScreening.ArogyaID;
                obj.date = modelScreening.CreateDate;
                return Medication(obj.Arogyaid, obj.Token, obj.date);
                // Json(obj, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult Medication(string argid, int token, DateTime dt)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();

            var query = context.SP_GetMedicationDetailsByArogyaID(argid, token, dt);

            return Json(query, JsonRequestBehavior.AllowGet);
        }
        public ActionResult PatientHealthRecord(string arogyaID, int tokenNumber)
        {

            ArogyaParivarEntities context = new ArogyaParivarEntities();
            Screening model = new Screening();


            string searchString = "";

            if (arogyaID != "")
            {
                searchString = arogyaID;
            }
            Session["strArogyaID"] = arogyaID;
            Session["intTokenNumber"] = tokenNumber;

            strArogyaID = Session["strArogyaID"].ToString();
            intTokenNumber = Convert.ToInt32(Session["intTokenNumber"]);
            string sortOrder = "";
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            IList<PatientModel> BookList = new List<PatientModel>();
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
            if (!String.IsNullOrEmpty(searchString))
            {

                BookList = patientBll.Get_PrintCard(sortOrder, searchString);

            }

            else
            {
                searchString = "";
                BookList = patientBll.Get_PrintCard(sortOrder, searchString);

            }

            var query2 = from allergy in context.T_Allergies

                         from at in context.M_AllergyType
                         .Where(x => x.ID == allergy.AllergenID).DefaultIfEmpty()
                         //on allergy.AllergenID equals at.ID

                         from ar in context.M_Reaction
                         .Where(x => x.ID == allergy.ReactionID).DefaultIfEmpty()
                         //on allergy.ReactionID equals ar.ID

                         from asev in context.M_Severity
                         .Where(x => x.ID == allergy.SeverityID).DefaultIfEmpty()
                         //on allergy.SeverityID equals asev.ID

                         from ast in context.M_Status
                         .Where(x => x.ID == allergy.StatusID).DefaultIfEmpty()
                         //on allergy.StatusID equals ast.ID

                         where allergy.Token_Number == tokenNumber
                            && EntityFunctions.TruncateTime(allergy.CreateDate).Value == EntityFunctions.TruncateTime(DateTime.Now).Value
                            && allergy.ArogyaID == arogyaID
                         select new Allergy
                         {
                             AllergyType = at.AllergyType,

                             ReactionName = ar.Reaction,
                             SeverityrName = asev.Severity,
                             Status = ast.M_StatusName,
                             // CreateDate =  EntityFunctions.TruncateTime(allergy.CreateDate).Value.ToString()
                             //CreateDateString=allergy.CreateDate.Value.ToString("dd/MM/yyyy")
                         };
            model.Allergys = query2.ToList();
            return View(model);
        }
        public JsonResult saveExaminationData(SaveDocotor Doctormodel)
        {
            try
            {

                ArogyaParivarEntities context = new ArogyaParivarEntities();

                T_Examination modelScreenings = new T_Examination()
                {
                    ComplaintID = Doctormodel.ChiefComplaintID,
                    PresentingComplaint = Doctormodel.HistoryPresentingComplaint,
                    PastMedicalHistory = Doctormodel.PastMedicalHistory,
                    PastSurgicalHistory = Doctormodel.PastSurgicalHistory,
                    FamilyHistory = Doctormodel.FamilyHistory,
                    CurrentMedication = Doctormodel.CurrentMedication,
                    Diagnosis = Doctormodel.Diagnosis,
                    Tests = Doctormodel.Tests,
                    TreatmentPlan = Doctormodel.TreatMentPlan,
                    ArogyaID = Session["arogyid"].ToString(),
                    Token_Number = Convert.ToInt32(Session["Token"]),
                    CreateDate = DateTime.Now,
                    Active = true,
                    UserID = Convert.ToInt32(Session["UserID"]),
                    ScreeningID = Doctormodel.ScreeningoutcomeID
                };
                context.T_Examination.Add(modelScreenings);
                context.SaveChanges();
                return Json("Data Saved", JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(-1, JsonRequestBehavior.AllowGet);
            }
        }
        private DocotorScreening LoadData(int TokenNumber, string ArogyaID)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();
            var query1 = (from screening in context.T_Screenings

                          from pc in context.M_PComplaints
                          .Where(x => x.ID == screening.ComplaintID).DefaultIfEmpty()
                          //on screening.ComplaintID equals pc.ID

                          from user in context.M_User
                          .Where(x => x.User_ID == screening.UserID).DefaultIfEmpty()
                          //on screening.UserID equals user.User_ID

                          where screening.Token_Number == TokenNumber &&
                          EntityFunctions.TruncateTime(screening.CreateDate).Value == DateTime.Today &&
                          screening.ArogyaID == ArogyaID
                          select new DocotorScreening
            {
                ChiefComplaintName = pc.M_PresentingComplainting,
                ChiefComplaintID = screening.ComplaintID.Value,
                HistoryPresentingComplaint = screening.PresentingComplaint,
                PastMedicalHistory = screening.PastMedicalHistory,
                PastSurgicalHistory = screening.PastSurgicalHistory,
                FamilyHistory = screening.FamilyHistory,
                CurrentMedication = screening.CurrentMedication,
                ECGOutcomeID = screening.ECGOutcomeID.Value,
                ScreenOutcomeID = screening.ScreenOutcomeID.Value
                                  //CreateDate = screening.CreateDate
            }).ToList();

            doctormodel = query1[0];

            var query = context.T_Vitals.Where(o => o.ArogyaID == ArogyaID && o.Token_Number == TokenNumber && EntityFunctions.TruncateTime(o.CreateDate) == DateTime.Today).ToList();

            if (query.Count > 0)
            {
                doctormodel.Weight      = query[0].Weight;
                doctormodel.Height      = query[0].Height;
                doctormodel.BMI         = query[0].BMI;
                doctormodel.DiaBP       = query[0].DiaBP;
                doctormodel.SysBP       = query[0].SysBP;
                doctormodel.Temparature = query[0].Temparature;
                doctormodel.Pulse       = query[0].Pulse;
                doctormodel.Respiratory = query[0].Respiratory;

                var query2 = from allergy in context.T_Allergies

                             from at in context.M_AllergyType
                             .Where(x => x.ID == allergy.AllergenID).DefaultIfEmpty()
                             //on allergy.AllergenID equals at.ID

                             from ar in context.M_Reaction
                             .Where(x => x.ID == allergy.ReactionID).DefaultIfEmpty()
                             //on allergy.ReactionID equals ar.ID

                             from asev in context.M_Severity
                             .Where(x => x.ID == allergy.SeverityID).DefaultIfEmpty()
                             //on allergy.SeverityID equals asev.ID

                             from ast in context.M_Status
                             .Where(x => x.ID == allergy.StatusID).DefaultIfEmpty()
                             //on allergy.StatusID equals ast.ID

                             where allergy.Token_Number == TokenNumber &&
                             EntityFunctions.TruncateTime(allergy.CreateDate).Value == DateTime.Today &&
                             allergy.ArogyaID == ArogyaID
                             select new AllergyModel
                {
                    AllergyTypeName = at.AllergyType,
                    AllergenName    = "",
                    ReactionName    = ar.Reaction,
                    SeverityName    = asev.Severity,
                    StatusName      = ast.M_StatusName,
                    CreateDate      = allergy.CreateDate,
                    //CreateDateString=allergy.CreateDate.Value.ToString("dd/MM/yyyy")
                };
                doctormodel.Allergies = query2.ToList();
            }
            return(doctormodel);
        }
        //public ActionResult FileUpload(HttpPostedFileBase Files)
        //{
        //    //create object of LINQ to SQL class

        //    //loop through request file collection 
        //    foreach (string upload in Request.Files)
        //    {
        //        //create byte array of size equal to file input stream
        //        byte[] fileData = new byte[Request.Files[upload].InputStream.Length];
        //        //add file input stream into byte array
        //        Request.Files[upload].InputStream.Read(fileData, 0, Convert.ToInt32(Request.Files[upload].InputStream.Length));
        //        //create system.data.linq object using byte array
        //        System.Data.Linq.Binary binaryFile = new System.Data.Linq.Binary(fileData);
        //        //initialise object of FileDump LINQ to sql class passing values to be inserted
        //        FileDump record = new FileDump { FileData = binaryFile, FileName = System.IO.Path.GetFileName(Request.Files[upload].FileName) };
        //        //call InsertOnsubmit method to pass new object to entity
        //        dataContext.FileDumps.InsertOnSubmit(record);
        //        //call submitChanges method to execute implement changes into database
        //        dataContext.SubmitChanges();
        //    }
        //    var returnData = dataContext.FileDumps;
        //    ViewData.Model = returnData.ToList();
        //    return View();
        //}


        public IList<Patient> GetListGender()
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();

            var query = (from m in context.M_Gender

                         select new Patient
                         {
                            Gender=m.ID,
                            GenderName=m.Gender

                         }).Distinct();


            query = query.OrderBy(m => m.Gender);

            return query.ToList();


        }
        public ActionResult PatientRegistration(Patient model, string command, HttpPostedFileBase Files)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();
            try
            {
                try
                {



                    ObjectParameter outParm = new ObjectParameter("callid", typeof(string));

                    context.SP_TokenGenration(outParm);

                    int tokennumber = Convert.ToInt32(outParm.Value);

                    ObjectParameter outParm1 = new ObjectParameter("callid", typeof(string));

                    context.SP_GenarateArogyaID(outParm1);

                    int intarogyaID = Convert.ToInt32(outParm1.Value);
                    string arogyaID = "A" + intarogyaID;
                    var webCamePath = ConfigurationSettings.AppSettings["WebCampath"];
                
                    if (command.Equals("Reset"))
                    {
                        return RedirectToAction("PatientRegistration");
                    }
                    else
                    {
                        var fileName = "";
                        if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                        {
                            var file = Request.Files[0];

                            if (file != null && file.ContentLength > 0)
                            {
                                fileName = Path.GetFileName(file.FileName);
                                var path = Path.Combine(Server.MapPath(ConfigurationSettings.AppSettings["DocumentUploadPath"]), fileName);
                                file.SaveAs(path);
                            }

                            T_RegUpload upload = new T_RegUpload()
                            {
                                Active = true,
                                ArogyaID = arogyaID,
                                CreateDate = DateTime.Now,
                                FileName = fileName,
                                UserID = Convert.ToInt32(Session["UserID"])
                            };
                            context.T_RegUpload.Add(upload);
                            context.SaveChanges();
                        }
                      

                        PatientModel book = new PatientModel()
                        {

                            PatientName = model.PatientName,
                            ArogyaID = arogyaID,
                            Surname = model.Surname,
                            Age = model.Age,
                            AgeType = model.Cal,
                            Gender = model.Gender,
                            AadharID = model.AadharID,
                            Address = model.Address,
                            ContactNo = model.ContactNo,
                            Village = Convert.ToInt64(Request.Form["Village"]),
                            Town = Request.Form["Mandal"].ToString(),
                            RefBy = Convert.ToInt32(Request.Form["RefBy"]),
                            RefName = model.RefName,
                            Consent = true,
                            District = Convert.ToInt32(Request.Form["city"].ToString()),
                            Sate = model.Sate,

                        };

                        T_Token tokn = new T_Token()
                        {
                            ArogyaID = arogyaID,
                            Token_Number = tokennumber,
                            Tokem_Date = DateTime.Now
                        };

                        context.T_Token.Add(tokn);
                        context.SaveChanges();
                        patientBll.Save(book);
                        return RedirectToAction("PrintCard", new { ArogyaID = arogyaID });
                 
                    }
                }
                catch
                {
                    return View(model);
                }


            }
            catch
            {
                return View(model);
            }
        }
        public ActionResult UpdateRegistration(Patient model, string command, HttpPostedFileBase Files)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();

            try
            {
                try
                {

                    ObjectParameter outParm = new ObjectParameter("callid", typeof(string));

                    context.SP_TokenGenration(outParm);

                    int tokennumber = Convert.ToInt32(outParm.Value);
                    if (command.Equals("Reset"))
                    {
                        return RedirectToAction("PatientRegistration");
                    }
                    else
                    {
                    
                        
                        T_Token tokn = new T_Token()
                        {
                            ArogyaID = model.ArogyaID,
                            Token_Number = tokennumber,
                            Tokem_Date = DateTime.Now
                        };
                        
                      context.T_Token.Add(tokn);
                       var value= context.T_PatientInfo.Where(x => x.ArogyaID == model.ArogyaID).FirstOrDefault();
                        

                            value.FirstName = model.PatientName;
                            value.ArogyaID = model.ArogyaID;
                            value.SurName = model.Surname;
                            value.Age = model.Age;
                            value.AgeType = Convert.ToInt32(Request.Form["AgeType"]);
                            value.FK_GenderID = model.Gender;
                            value.ID_Number = model.AadharID;
                            value.Address = model.Address;
                            value.ContactNumber = model.ContactNo;
                            value.VillageId = Convert.ToInt64(Request.Form["Village"]);
                            value.TownId = Request.Form["Town"];
                            value.RefBy = Convert.ToInt32(Request.Form["RefBy"]);
                            value.RefName = model.RefName;
                            value.Consen = true;
                            value.DistrictId = Convert.ToInt32(Request.Form["District"].ToString());
                            value.SateId = model.Sate;

                        context.SaveChanges();
                        return RedirectToAction("PatientSearch");
                    }
                }
                catch
                {
                    return View(model);
                }


            }
            catch
            {
                return View(model);
            }
        }
        private DocotorScreening LoadData(int TokenNumber, string ArogyaID)
        {
            ArogyaParivarEntities context = new ArogyaParivarEntities();
            var query1 = (from screening in context.T_Screenings

                          from pc in context.M_PComplaints
                          .Where(x => x.ID == screening.ComplaintID).DefaultIfEmpty()
                          //on screening.ComplaintID equals pc.ID

                          from user in context.M_User
                          .Where(x => x.User_ID == screening.UserID).DefaultIfEmpty()
                          //on screening.UserID equals user.User_ID

                          where screening.Token_Number == TokenNumber
                              && EntityFunctions.TruncateTime(screening.CreateDate).Value == DateTime.Today
                              && screening.ArogyaID == ArogyaID
                          select new DocotorScreening
                          {
                              ChiefComplaintName = pc.M_PresentingComplainting,
                              ChiefComplaintID = screening.ComplaintID.Value,
                              HistoryPresentingComplaint = screening.PresentingComplaint,
                              PastMedicalHistory = screening.PastMedicalHistory,
                              PastSurgicalHistory = screening.PastSurgicalHistory,
                              FamilyHistory = screening.FamilyHistory,
                              CurrentMedication = screening.CurrentMedication,
                              ECGOutcomeID = screening.ECGOutcomeID.Value,
                              ScreenOutcomeID = screening.ScreenOutcomeID.Value
                              //CreateDate = screening.CreateDate
                          }).ToList();
            doctormodel = query1[0];

            var query = context.T_Vitals.Where(o => o.ArogyaID == ArogyaID && o.Token_Number == TokenNumber && EntityFunctions.TruncateTime(o.CreateDate) == DateTime.Today).ToList();
            if (query.Count > 0)
            {
                doctormodel.Weight = query[0].Weight;
                doctormodel.Height = query[0].Height;
                doctormodel.BMI = query[0].BMI;
                doctormodel.DiaBP = query[0].DiaBP;
                doctormodel.SysBP = query[0].SysBP;
                doctormodel.Temparature = query[0].Temparature;
                doctormodel.Pulse = query[0].Pulse;
                doctormodel.Respiratory = query[0].Respiratory;

                var query2 = from allergy in context.T_Allergies

                             from at in context.M_AllergyType
                             .Where(x => x.ID == allergy.AllergenID).DefaultIfEmpty()
                             //on allergy.AllergenID equals at.ID

                             from ar in context.M_Reaction
                             .Where(x => x.ID == allergy.ReactionID).DefaultIfEmpty()
                             //on allergy.ReactionID equals ar.ID

                             from asev in context.M_Severity
                             .Where(x => x.ID == allergy.SeverityID).DefaultIfEmpty()
                             //on allergy.SeverityID equals asev.ID

                             from ast in context.M_Status
                             .Where(x => x.ID == allergy.StatusID).DefaultIfEmpty()
                             //on allergy.StatusID equals ast.ID

                             where allergy.Token_Number == TokenNumber
                                && EntityFunctions.TruncateTime(allergy.CreateDate).Value == DateTime.Today
                                && allergy.ArogyaID == ArogyaID
                             select new AllergyModel
                             {
                                 AllergyTypeName = at.AllergyType,
                                 AllergenName = "",
                                 ReactionName = ar.Reaction,
                                 SeverityName = asev.Severity,
                                 StatusName = ast.M_StatusName,
                                 CreateDate = allergy.CreateDate,
                                 //CreateDateString=allergy.CreateDate.Value.ToString("dd/MM/yyyy")
                             };
                doctormodel.Allergies = query2.ToList();

            }
            return doctormodel;
        }