// GET: Invoice/Create
        public ActionResult Create(string id)
        {
            if (id == null)
            {
                id = globalID;
            }
            Invoice objInvoice = new Invoice();

            objInvoice.PatientChild = db.Children.FirstOrDefault(x => x.IdNumber == id);
            objInvoice.VaccinationList = db.Vaccinations.Where(x => x.IdNumber == id).ToList();
            string branch = db.UserStatus.FirstOrDefault(x => x.Username == User.Identity.Name).Branch_Practice_No;
            var  temp = new List<ExtendedFeesCustom>();
            List<ExtendedFee> listFromDB = null;
            if (branch == "ADMIN2010")
            {
                listFromDB = db.ExtendedFees.ToList();
            }
            else
            {
                listFromDB = db.ExtendedFees.Where(x => x.Branch == branch).ToList();
            }

            foreach (ExtendedFee item in listFromDB)
            {
                temp.Add(FeesToCustomObj(item));
            }

            objInvoice.ExtendedFeeList = temp;

            objInvoice.InvoiceFromDate = DateTime.Now.Date;
            objInvoice.BranchInformation = db.Branches1.FirstOrDefault(x => x.Practice_No == branch);
                

            return View(objInvoice);
        }
        public Document CreateDocument(Invoice inputInvoice, string loggedInUser)
        {
            globalCurrentUser = loggedInUser;
            this.document = new Document();
            document.DefaultPageSetup.Orientation = Orientation.Portrait;
            this.document.Info.Title = "Vaccination Invoice";
            this.document.Info.Subject = "Contains Child's Vaccinations Invoice";
            this.document.Info.Author = loggedInUser;

            if (inputInvoice.VaccinationList.Count < 1)
            {
                Section s = this.document.AddSection();
                Paragraph p = s.AddParagraph("No vaccinations for the selected date");
                p.Format.Font.Size = 20;
                p.Format.Font.Color = Colors.Red;
                p.AddLineBreak(); p.AddLineBreak(); p.AddLineBreak(); p.AddLineBreak(); p.AddLineBreak(); p.AddLineBreak();
                p.Format.Alignment = ParagraphAlignment.Center;
                return this.document;

            }


            DefineStyles();
            CreatePage();
            FillContents(inputInvoice);

            return this.document;
        }
        private FileContentResult CreateDummyReport()
        {
            //-------------------------------------------
            //outputDate = ViewBag.GlobalDate;
            string id = Url.RequestContext.RouteData.Values["id"].ToString();
            if (string.IsNullOrEmpty(id))
            {
                id = invoiceID;
            }
            Invoice objInvoice = new Invoice();

            objInvoice.PatientChild = db.Children.FirstOrDefault(x => x.IdNumber == id);
            objInvoice.VaccinationList = db.Vaccinations.Where(x => x.IdNumber == id && x.Date.Day == outputDate.Day && x.Date.Month == outputDate.Month && x.Date.Year == outputDate.Year).ToList();
            string branch = db.UserStatus.FirstOrDefault(x => x.Username == User.Identity.Name).Branch_Practice_No;
            var temp = new List<ExtendedFeesCustom>();
            List<ExtendedFee> listFromDB = null;
            if (branch == "ADMIN2010")
            {
                listFromDB = db.ExtendedFees.ToList();
            }
            else
            {
                listFromDB = db.ExtendedFees.Where(x => x.Branch == branch).ToList();
            }

            foreach (ExtendedFee item in listFromDB)
            {
                temp.Add(FeesToCustomObj(item));
            }

            objInvoice.ExtendedFeeList = temp;
            objInvoice.InvoiceFromDate = outputDate;
            objInvoice.InvoiceToDate = outputDate;


            objInvoice.BranchInformation = db.Branches1.FirstOrDefault(x => x.Practice_No == branch);

            //-------------------------------------------


            InvoiceReport report = new InvoiceReport();


            Document document = report.CreateDocument(objInvoice, User.Identity.Name);
            //string ddl = MigraDoc.DocumentObjectModel.IO.DdlWriter.WriteToString(document);
            PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
            renderer.Document = document;

            renderer.RenderDocument();

            using (MemoryStream stream = new MemoryStream())
            {
                renderer.PdfDocument.Save(stream, false);
                return File(stream.ToArray(), "application/pdf");
            }
        }
        public ActionResult Create(Invoice model)
        {
            Session["DateError"] = "";
            string tempId = Url.RequestContext.RouteData.Values["id"].ToString();
            if (string.IsNullOrEmpty(tempId))
            {
                
            }
            else
            {
                Session["GlobalID"] = tempId;
            }
            try
            {
                //var obj = (List<ExtendedFeesCustom>)Request["Model.ExtendedFeeList"];
                //string test = obj[0].FeeName;
                var obj2 = model.InvoiceFromDate.ToString().Substring(0, model.InvoiceFromDate.ToString().LastIndexOf(" "));
                string obj3 = obj2.Substring(0, obj2.LastIndexOf(" "));
                obj2 = obj3;
                if (!isValidDate(obj2))
                {
                    Session["DateError"] = "Invalid";

                    return View(model);
                    //return RedirectToAction("Create", "Invoice", new { id = Session["GlobalID"] });
                }
                Session["DateError"] = "";
                ViewBag.GlobalDate = outputDate;
                resultPDF = CreateDummyReport();
                return RedirectToAction("Edit", new {id = tempId});
            }
            catch(Exception ex)
            {
                return View(model);
            }
        }
        public void FillContents(Invoice contents)
        {
            #region Top paragraph data
            
            Details.Format.Font.Size = 18;
            Details.AddTab(); Details.AddTab(); Details.AddTab(); Details.AddTab(); Details.AddTab();
            Details.AddFormattedText("Invoice", TextFormat.Bold);
            Details.AddLineBreak();

            Details.AddLineBreak(); Details.AddLineBreak();
            //---------------CENTRE DETAILS-----------------------------------------------------------------------------
            Details.Format.Font.Size = 12;
            Details.AddTab(); Details.AddTab(); Details.AddTab(); Details.AddTab(); 
            Details.AddFormattedText("Medical Centre Details", TextFormat.Bold);
            Details.AddLineBreak(); Details.AddLineBreak();

            Details.Format.Font.Size = 11;
            Details.AddFormattedText("Branch Centre Name:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            if (contents != null && (contents.BranchInformation != null && contents.BranchInformation.Name != null)) Details.AddText(contents.BranchInformation.Name);
            Details.AddLineBreak();

            Details.AddFormattedText("Manager:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (contents != null && (contents.BranchInformation != null && contents.BranchInformation.Overseer_Name != null))
                Details.AddText(contents.BranchInformation.Overseer_Name + " " + contents.BranchInformation.Overseer_Surname);
            Details.AddLineBreak();

            Details.AddFormattedText("Practice Number:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            if (contents != null && contents.BranchInformation != null && contents.BranchInformation.Practice_No != null)
            {
                Details.AddText(contents.BranchInformation.Practice_No);
            }

            Details.AddLineBreak();

            Details.AddFormattedText("Address:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab(); Details.AddTab();
            if (contents != null && contents.BranchInformation != null && contents.BranchInformation.Address != null)
                Details.AddText(contents.BranchInformation.Address);
            Details.AddLineBreak(); Details.AddLineBreak();

            Details.AddFormattedText("Telephone:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (contents != null && contents.BranchInformation != null && contents.BranchInformation.Tel_Number != null)
                Details.AddText(contents.BranchInformation.Tel_Number);
            Details.AddLineBreak();

            Details.AddFormattedText("Fax:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (contents != null && contents.BranchInformation != null && contents.BranchInformation.Fax_Number != null)
                Details.AddText(contents.BranchInformation.Fax_Number);
            Details.AddLineBreak(); Details.AddLineBreak();

            //------------------------Parent Details---------------------------------------------------
            var parent = db.Parents.FirstOrDefault(x => x.IdNumber == contents.PatientChild.MotherId);

            if (parent == null)
            {
                parent = db.Parents.FirstOrDefault(x => x.IdNumber == contents.PatientChild.FatherId);
            }

            Details.Format.Font.Size = 11;
            Details.AddTab(); Details.AddTab(); Details.AddTab(); Details.AddTab(); 
            Details.AddFormattedText("Medical Aid Principal Member Details", TextFormat.Bold);
            Details.AddLineBreak(); Details.AddLineBreak();

            Details.AddFormattedText("Name:", TextFormat.Bold);
            Details.AddTab(); Details.AddTab();
            Details.AddTab(); Details.AddTab();
            if (parent != null && parent.Name != null) { Details.AddText(parent.Name); }
            Details.AddLineBreak();
            


            Details.AddFormattedText("Surname:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.Surname != null) Details.AddText(parent.Surname);
            Details.AddLineBreak();
            


            Details.AddFormattedText("ID Number:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.IdNumber != null) Details.AddText(parent.IdNumber);
            Details.AddLineBreak();
            

            Details.AddFormattedText("Address:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.Address != null)
            {

                Address addressResult = parent.Address;
                Details.AddText(addressResult.AddressLine1 + ", " + addressResult.AddressLine2 + ", " + addressResult.Suburb + ", " + addressResult.Town + ", " + addressResult.PostalCode); //Fetch Address from ID and display
            }
                
            Details.AddLineBreak(); Details.AddLineBreak();
            

            Details.AddFormattedText("Telephone:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.HomeTel != null) Details.AddText(parent.HomeTel);
            Details.AddLineBreak();
            

            Details.AddFormattedText("Cell:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.Cellphone != null) Details.AddText(parent.Cellphone);
            Details.AddLineBreak(); Details.AddLineBreak();

            //----------------------END Parent Details-------------------------------------------------

            //----------------------Medical Aid Info---------------------------------------------------
            
            Details.AddFormattedText("Employer:", TextFormat.Bold);
            Details.AddTab(); Details.AddTab();
            Details.AddTab();
            if(parent != null && parent.Employer != null)
                Details.AddText(parent.Employer);
            Details.AddLineBreak();
            
            Details.AddFormattedText("Office Phone:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.Telephone != null)
                if (parent != null) Details.AddText(parent.Telephone);
            Details.AddLineBreak();
            
            Details.AddFormattedText("Medical Aid:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.MedicalAidName != null) Details.AddText(parent.MedicalAidName);
            Details.AddLineBreak();
            
            Details.AddFormattedText("Medical Aid No:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.MedicalAidNumber != null)
                Details.AddText(parent.MedicalAidNumber);
            Details.AddLineBreak();
            
            Details.AddFormattedText("Medical Aid Plan:", TextFormat.Bold);
            Details.AddTab();
            Details.AddTab();
            if (parent != null && parent.MedicalAidPlan != null) Details.AddText(parent.MedicalAidPlan);
            Details.AddLineBreak();

            //----------------------END Medical Aid Info-----------------------------------------------

            //------------------------END CENTRE DETAILS----------------------------------------------------------------


            #endregion

            //-----------------------VACCINATIONS-----------------------------------------------------------------------

            var vaccinations = contents.VaccinationList;
            var temp = db.UserStatus.FirstOrDefault(x => x.Username == globalCurrentUser);
            string currentBranch = "";
            if (temp != null)
            {
                currentBranch = temp.Branch_Practice_No;
            }

            decimal sum = Convert.ToDecimal(0.0);
            var extendedFees = db.ExtendedFees.Where(x => x.IncludeInReport == "Include" && x.Branch == currentBranch).ToList();
            foreach (var vacc in vaccinations)
            {
                //if (vacc.Existing)
                //{
                // Each item fills two rows
                Row row1 = this.VaccincationsTable.AddRow();
                //Row row2 = this.table.AddRow();
                //row1.TopPadding = 1.5;
                //row1.Cells[0].Shading.Color = Colors.Gray;
                //row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
                //row1.Cells[0].MergeDown = 1;
                //row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
                //row1.Cells[1].MergeRight = 3;
                //row1.Cells[5].Shading.Color = Colors.Gray;
                //row1.Cells[5].MergeDown = 1;
                
                VaccinationDefinition vaccDef = db.VaccinationDefinitions.FirstOrDefault(x=>x.Id == vacc.VaccinationDefinitionId);
                VaccinationPrice vaccPrice = db.VaccinationPrices.FirstOrDefault(x=>x.VaccinationDefId == vacc.VaccinationDefinitionId.ToString());
                int quantity = 1;
                row1.Cells[0].AddParagraph(contents.InvoiceFromDate.ToString("yyyy-MM-dd"));
                if (vaccDef != null && vaccDef.Description != null) row1.Cells[1].AddParagraph(vaccDef.Description);
                if (vaccDef != null && vaccDef.Code != null) row1.Cells[2].AddParagraph(vaccDef.Code);
                if (vaccDef != null && vaccDef.ICDCode != null) row1.Cells[3].AddParagraph(vaccDef.ICDCode);
                row1.Cells[4].AddParagraph(quantity.ToString()); // Dummy value for QTY
                if (vaccDef.Price == null)
                {
                    row1.Cells[5].AddParagraph("0.00");
                }
                else
                {
                    row1.Cells[5].AddParagraph(vaccDef.Price.ToString());
                }


                this.VaccincationsTable.SetEdge(0, this.VaccincationsTable.Rows.Count - 2, 6, 2, Edge.Box, BorderStyle.Single, 0.75);
                decimal price;
                if (vaccDef.Price == null)
                {
                    price = Convert.ToDecimal(0.0);
                }
                else
                {
                    price = Convert.ToDecimal(vaccDef.Price);
                }
                sum += (price * quantity);
                //}
            }
            foreach (var item in extendedFees)
            {
                Row row1 = this.VaccincationsTable.AddRow();
                int quantity = 1;

                row1.Cells[0].AddParagraph(contents.InvoiceFromDate.ToString());
                row1.Cells[1].AddParagraph(item.FeeName);
                row1.Cells[2].AddParagraph(item.NappiCode);
                row1.Cells[3].AddParagraph(item.FeeCode);
                row1.Cells[4].AddParagraph(quantity.ToString()); // Dummy value for QTY
                row1.Cells[5].AddParagraph(item.Amount.ToString());
                this.VaccincationsTable.SetEdge(0, this.VaccincationsTable.Rows.Count - 2, 6, 2, Edge.Box, BorderStyle.Single, 0.75);

                sum += (item.Amount*quantity);
            }
            //-----------------------END VACCINATIONS-------------------------------------------------------------------

            //------------------------BANKING DETAILS-------------------------------------------------------------------
            Totals.Format.Alignment = ParagraphAlignment.Right;
            Totals.AddLineBreak();
            Totals.Format.Font.Size = 13;
            Totals.AddFormattedText("Total:", TextFormat.Bold);
            Totals.AddTab();
            Totals.AddTab();
            Totals.AddText("R " + sum);
            Totals.AddTab(); Details.AddTab();
            Totals.AddLineBreak(); Totals.AddLineBreak();

            BankingDetails.Format.Alignment = ParagraphAlignment.Left;
            BankingDetails.AddFormattedText("Banking Details", TextFormat.Underline);
            BankingDetails.AddLineBreak(); Details.AddLineBreak();

            BankingDetails.AddFormattedText("Bank Name:", TextFormat.Bold);
            if (!string.IsNullOrEmpty(contents.BranchInformation.Bank_Name))
            {
                BankingDetails.AddText(contents.BranchInformation.Bank_Name);
            }
            BankingDetails.AddTab();
            BankingDetails.AddLineBreak();

            BankingDetails.AddFormattedText("Account No:", TextFormat.Bold);
            if (!string.IsNullOrEmpty(contents.BranchInformation.Account_Number))
            {
                BankingDetails.AddText(contents.BranchInformation.Account_Number);
            }
            BankingDetails.AddTab();
            BankingDetails.AddLineBreak();
            
            BankingDetails.AddFormattedText("Branch No:", TextFormat.Bold);
            if (!string.IsNullOrEmpty(contents.BranchInformation.Branch_Number))
            {
                BankingDetails.AddText(contents.BranchInformation.Branch_Number);
            }
            BankingDetails.AddTab();
            BankingDetails.AddLineBreak(); Details.AddLineBreak();

            //Details.AddTab(); Details.AddTab(); Details.AddTab(); Details.AddTab();
            //Details.AddFormattedText("Invoice Date: " + contents.InvoiceFromDate.Date.ToString(), TextFormat.Underline);
            //Details.AddLineBreak(); Details.AddLineBreak();


            //------------------------END BANKING DETAILS---------------------------------------------------------------
        }