//
        // GET: /RepeatPrescription/ddd

        public ActionResult Index()
        {
            MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
            Guid userId = (Guid)user.ProviderUserKey;

            var context = new LangleyPharmacyEntities();
            var patientPerscription = context.Patients.Where(i => i.UserId == userId).FirstOrDefault();
            var viewModel = new RepeatPrescriptionViewModel();
            if (patientPerscription != null)
            {
                var model = viewModel.model;
                model.Name = patientPerscription.Name;
                model.DateOfBirth = patientPerscription.DateOfBirth;
                model.Address = patientPerscription.Address;
                model.Email = patientPerscription.EmailAddress;
                model.TelephoneNumber = patientPerscription.TelephoneNumber;
                model.PatientId = patientPerscription.PatientId;
                model.PayForPerscriptions = patientPerscription.PatientPrescriptionDetail.PayForPrescription;
                model.ExcemptionReason = patientPerscription.PatientPrescriptionDetail.ExcemptionReason;
                model.ExcemptionNumber = patientPerscription.PatientPrescriptionDetail.ExcemptionNumber;
                model.FurtherComments = patientPerscription.PatientPrescriptionDetail.FurtherComments;
                model.DeliveryAddress = patientPerscription.PatientPrescriptionDetail.DeliveryAddress;
                model.RepeatItems.Clear();

                foreach (var item in patientPerscription.PatientPerscriptionDetailsRepeatItems)
                {
                    model.RepeatItems.Add(item.Item);
                }

                viewModel.model = model;
            }
            return View(viewModel);
        }
        //
        // GET: /RepeatPrescription/
        public ActionResult SaveRepeatPrescription(FormCollection collection)
        {
            var model = new RepeatPrescriptionViewModel();
            this.TryUpdateModel<RepeatPrescriptionModel>(model.model, "model", collection);

            if (!model.model.AuthoriseFlag)
            {
                ModelState.AddModelError("AuthoriseFlag", "Please indicate whether you agree with the t&c's before continuing");
            }

            var count = 0;
            foreach (var item in model.model.RepeatItems)
            {
                if (!string.IsNullOrEmpty(item))
                    count++;
            }

            if (count == 0)
            {
                ModelState.AddModelError("RepeatItems", "Please add at least one repeat item before continuing");
            }
            MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
            Guid userId = (Guid)user.ProviderUserKey;

            var saveModel = model.model;
            if (ModelState.IsValid)
            {
                try
                {


                    var context = new LangleyPharmacyEntities();

                    if (saveModel.PatientId <= 0)
                    {
                        var patient = new Patient();
                        patient.Name = saveModel.Name;
                        patient.DateOfBirth = saveModel.DateOfBirth.Value;
                        patient.Address = saveModel.Address;
                        patient.EmailAddress = saveModel.Email;
                        patient.TelephoneNumber = saveModel.TelephoneNumber;
                        patient.UserId = userId;

                        var patientDetail = new PatientPrescriptionDetail();
                        patientDetail.PatientId = patient.PatientId;
                        patientDetail.SurgeryId = 1;
                        patientDetail.PayForPrescription = saveModel.PayForPerscriptions.Value;
                        patientDetail.ExcemptionReason = saveModel.ExcemptionReason;
                        patientDetail.ExcemptionNumber = saveModel.ExcemptionNumber;
                        patientDetail.FurtherComments = saveModel.FurtherComments;
                        patientDetail.DeliveryMethodId = 1;
                        patientDetail.DeliveryAddress = saveModel.DeliveryAddress;
                        patientDetail.CreatedDate = DateTime.Now;
                        foreach (var item in saveModel.RepeatItems)
                        {
                            if (!string.IsNullOrEmpty(item))
                                patient.PatientPerscriptionDetailsRepeatItems.Add(new PatientPerscriptionDetailsRepeatItem { Item = item });
                        }

                        patient.PatientPrescriptionDetail = patientDetail;
                        context.Patients.AddObject(patient);
                        context.SaveChanges();
                        model.model.PatientId = patient.PatientId;
                        TempData["Action"] = "Create";


                        var errorEmailAddress = ConfigurationManager.AppSettings["RepeatCCEmailAddresses"];
                        var emailBody = this.RenderPartialViewToString("Email", model);
                        Email.SendEmail("*****@*****.**", errorEmailAddress, emailBody, string.Format("Repeat prescription for patient #{0} created", patient.PatientId));
                        return RedirectToAction("Index");

                    }
                    else
                    {
                        var patient = context.Patients.Where(i => i.PatientId == saveModel.PatientId).First();
                        patient.Name = saveModel.Name;
                        patient.DateOfBirth = saveModel.DateOfBirth.Value;
                        patient.Address = saveModel.Address;
                        patient.EmailAddress = saveModel.Email;
                        patient.TelephoneNumber = saveModel.TelephoneNumber;

                        var patientPerscription = patient.PatientPrescriptionDetail;
                        patientPerscription.SurgeryId = 1;
                        patientPerscription.PayForPrescription = saveModel.PayForPerscriptions.Value;
                        patientPerscription.ExcemptionReason = saveModel.ExcemptionReason;
                        patientPerscription.ExcemptionNumber = saveModel.ExcemptionNumber;
                        patientPerscription.FurtherComments = saveModel.FurtherComments;
                        patientPerscription.DeliveryMethodId = 1;
                        patientPerscription.DeliveryAddress = saveModel.DeliveryAddress;
                        patientPerscription.ModifiedDate = DateTime.Now;
                        patient.PatientPerscriptionDetailsRepeatItems.ToList().ForEach(x => context.PatientPerscriptionDetailsRepeatItems.DeleteObject(x));
                        foreach (var item in saveModel.RepeatItems)
                        {
                            if (!string.IsNullOrEmpty(item))
                                patient.PatientPerscriptionDetailsRepeatItems.Add(new PatientPerscriptionDetailsRepeatItem { Item = item });
                        }
                        context.SaveChanges();
                        TempData["Action"] = "Edit";

                        var errorEmailAddress = ConfigurationManager.AppSettings["RepeatCCEmailAddresses"];
                        var emailBody = this.RenderPartialViewToString("Email", model);
                        Email.SendEmail("*****@*****.**", errorEmailAddress, emailBody, string.Format("Repeat prescription for patient #{0} updated", patient.PatientId));
                    }
                }
                catch (Exception ex)
                {
                    var s = ex.Message;
                    ExceptionHelper.SendExceptionEmail(ex);
                }
            }
            return View("Index", model);
        }