public void Approve([FromBody] Models.Presentation.ReportSignatureModel signatureInfo)
        {
            string userName = System.Web.HttpContext.Current.User.Identity.Name.Substring(5).ToLower();

            if (userName.ToLower() != signatureInfo.userName.ToLower())
            {
                throw new Exception("Current user information is not synchronized.  Cannot approve report.");
            }

            SessionController session = new SessionController();

            bool userVerified = session.VerifyPassword(userName, signatureInfo.signature);

            session.Dispose();

            if (userVerified)
            {
                Models.Medical medicalAssessment = this._db.Medicals.Where(m => m.incidentMedicalId == signatureInfo.incidentMedicalId).SingleOrDefault();

                if (medicalAssessment != null)
                {
                    // SET STATUS OF ASSESSMENT TO CLOSED
                    medicalAssessment.statusId = 6;
                    this._db.Medicals.Attach(medicalAssessment);
                    this._db.Entry(medicalAssessment).State = System.Data.Entity.EntityState.Modified;



                    // CREATE SIGNATURE RECORD
                    Models.ReportSign medicalSignature = new Models.ReportSign();

                    medicalSignature.incidentId        = signatureInfo.incidentId;
                    medicalSignature.incidentMedicalId = signatureInfo.incidentMedicalId;
                    medicalSignature.reportSigType     = "M";
                    medicalSignature.reportSigUserId   = signatureInfo.currentUser;
                    medicalSignature.staffName         = signatureInfo.staffName;
                    medicalSignature.staffTitle        = signatureInfo.staffTitle;
                    medicalSignature.approvalStatusId  = 3;
                    medicalSignature.reportSigStamp    = DateTime.Now;
                    medicalSignature.reportSigStation  = signatureInfo.stationName;

                    this._db.ReportSigns.Add(medicalSignature);
                    this._db.SaveChanges();
                }
                else
                {
                    throw new Exception("Medical Assessment could not be found.");
                } // if (medicalAssessment != null)
            }
            else
            {
                throw new Exception("Unable to validate signature.  Please use your current CFS account password to sign.");
            } // if (userVerified)
        }
        public void VoidReport(long id)
        {
            var report = this._db.IncidentReports.Where(r => r.incidentId == id).SingleOrDefault();

            if (report != null)
            {
                SessionController session = new SessionController();
                var user = session.Get();


                report.statusId       = 7;
                report.lastModified   = DateTime.Now;
                report.lastModifiedBy = user.userId;


                session.Dispose();

                this._db.IncidentReports.Attach(report);
                this._db.Entry(report).State = System.Data.Entity.EntityState.Modified;

                this._db.SaveChanges();
            }
        }
        public void AdminFinalApprove([FromBody] Models.Presentation.ReportSignatureModel signatureInfo)
        {
            Models.IncidentReport report = this._db.IncidentReports.Where(r => r.incidentId == signatureInfo.incidentId).SingleOrDefault();

            if (report != null)
            {
                string userName = System.Web.HttpContext.Current.User.Identity.Name.Substring(5).ToLower();
                if (userName.ToLower() != signatureInfo.userName.ToLower())
                {
                    throw new Exception("Current user information is not synchronized.  Cannot approve report.");
                }

                SessionController session = new SessionController();

                bool userVerified = session.VerifyPassword(userName, signatureInfo.signature);
                session.Dispose();

                if (userVerified)
                {
                    report.statusId       = signatureInfo.statusId;
                    report.lastModified   = DateTime.Now;
                    report.lastModifiedBy = signatureInfo.currentUser;

                    this._db.SaveChanges();


                    PrintController printer = new PrintController();
                    printer.SaveToEbook(report, signatureInfo.ebookFolder);

                    printer.Dispose();
                }
                else
                {
                    throw new Exception("Unable to validate signature.  Please use your current CFS account password to sign.");
                }
            }
        }
        public string Post([FromBody] Models.Presentation.AgendaPostModel agenda)
        {
            string filePath = @"\\844dc2\Residential Incidents\";
            string fileName = string.Format("{0}{1}.docx", filePath, agenda.agendaTitle);

            //MemoryStream documentStream = new MemoryStream();


            using (WordprocessingDocument agendaDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            //using (WordprocessingDocument agendaDocument = WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document))
            {
                var reports = from r in this._db.IncidentReports
                              join u in this._db.Users
                              on r.userId equals u.userId
                              join p in this._db.IncidentPrograms
                              on r.programId equals p.incidentProgramId
                              join s in this._db.ReportStatuses
                              on r.statusId equals s.reportStatusId
                              from d in this._db.IncidentDetails.Where(d => d.incidentId == r.incidentId).DefaultIfEmpty()
                              where r.incidentReportTypeId == 1 &&
                              r.incidentDate >= agenda.fromDate &&
                              r.incidentDate <= agenda.toDate
                              select new
                {
                    incidentId      = r.incidentId,
                    clientName      = r.clientName,
                    clientDob       = r.clientDob,
                    programTitle    = p.programTitle,
                    reportingAgency = r.reportingAgency,
                    incidentDate    = r.incidentDate,
                    createdStamp    = r.createdStamp,
                    lastModified    = r.lastModified,
                    createdByName   = u.firstName + " " + u.lastName,
                    statusId        = r.statusId,
                    currentStatus   = s.reportStatusText,
                    incidentDetails = d.incidentDetails,
                    staffs          = (
                        from st in this._db.IncidentStaffs
                        join e in this._db.Users
                        on st.userId equals e.userId
                        where st.incidentId == r.incidentId
                        select new
                    {
                        staffName = e.firstName + " " + e.lastName
                    }
                        )
                };



                MainDocumentPart root = agendaDocument.AddMainDocumentPart();

                root.Document = new Document();
                Body body = root.Document.AppendChild(new Body());


                // PAGE MARGINS
                SectionProperties sectionProperties = new SectionProperties();
                PageMargin        pageMargin        = new PageMargin()
                {
                    Top = 720, Right = (UInt32Value)720U, Bottom = 720, Left = (UInt32Value)720U, Header = (UInt32Value)720U, Footer = (UInt32Value)720U, Gutter = (UInt32Value)0U
                };
                sectionProperties.Append(pageMargin);
                root.Document.Body.Append(sectionProperties);

                // DOCUMENT STYLES
                StyleDefinitionsPart styleDefinitionsPart = root.AddNewPart <StyleDefinitionsPart>();
                Styles styles = new Styles();
                styles.Save(styleDefinitionsPart);

                Style style = new Style()
                {
                    Type        = StyleValues.Paragraph,
                    StyleId     = "AgendaStyle",
                    CustomStyle = true
                };
                StyleName styleHeading1 = new StyleName()
                {
                    Val = "Heading1"
                };
                style.Append(styleHeading1);
                StyleRunProperties styleRunPropertiesHeading1 = new StyleRunProperties();
                styleRunPropertiesHeading1.Append(new Bold());
                styleRunPropertiesHeading1.Append(new RunFonts()
                {
                    Ascii = "Calibri"
                });
                styleRunPropertiesHeading1.Append(new FontSize()
                {
                    Val = "24"
                });                                                                // Sizes are in half-points. Oy!
                style.Append(styleRunPropertiesHeading1);
                styles.Append(style);


                foreach (var report in reports)
                {
                    //Paragraph para = body.AppendChild(new Paragraph());
                    //Run run = para.AppendChild(new Run());

                    // CLIENT NAME HEADER
                    Paragraph clientNamePara = body.AppendChild(new Paragraph());
                    clientNamePara.AppendChild(new Run(new Text(report.clientName)));
                    clientNamePara.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId()
                    {
                        Val = "Heading1"
                    });


                    // REPORT DETAILS
                    Paragraph infoPara = body.AppendChild(new Paragraph());
                    Run       infoRun  = infoPara.AppendChild(new Run());

                    infoRun.AppendChild(new Text(string.Format("Program: {0}", report.programTitle)));
                    infoRun.AppendChild(new Break());
                    infoRun.AppendChild(new Text(string.Format("Reporting Agency: {0}", report.reportingAgency)));
                    infoRun.AppendChild(new Break());
                    infoRun.AppendChild(new Text(string.Format("Date of Incident: {0}", report.incidentDate.ToShortDateString())));
                    infoRun.AppendChild(new Break());
                    infoRun.AppendChild(new Text(string.Format("Staff: {0}", report.createdByName)));


                    // INCIDENT DETAILS
                    Paragraph detailsPara = body.AppendChild(new Paragraph());
                    Run       detailsRun  = detailsPara.AppendChild(new Run());

                    detailsRun.AppendChild(new Text("Details of Incident: "));
                    detailsRun.AppendChild(new Break());

                    if (report.incidentDetails == string.Empty)
                    {
                        detailsRun.AppendChild(new Text("<No details given.  Report incomplete.>"));
                    }
                    else
                    {
                        detailsRun.AppendChild(new Text(report.incidentDetails));
                    }



                    // ADDITIONAL STAFF INVOLVED
                    Paragraph staffPara = body.AppendChild(new Paragraph());
                    Run       staffRun  = staffPara.AppendChild(new Run());

                    staffRun.AppendChild(new Text("Additional Staff Involved:"));
                    staffRun.AppendChild(new Break());


                    if (report.staffs.ToList().Any())
                    {
                        foreach (var staff in report.staffs)
                        {
                            staffRun.AppendChild(new Text(staff.staffName));
                            staffRun.AppendChild(new Break());
                        }
                    }
                    else
                    {
                        staffRun.AppendChild(new Text("No additional staff identified."));
                        staffRun.AppendChild(new Break());
                    }



                    // ACTIONS TAKEN
                    Paragraph actionsPara = body.AppendChild(new Paragraph());
                    Run       actionsRun  = actionsPara.AppendChild(new Run(new Text("Actions Taken")));


                    // PATTERNS
                    Paragraph patternsPara = body.AppendChild(new Paragraph());
                    Run       patternsRun  = patternsPara.AppendChild(new Run(new Text("Pattern Behavior/Recommendation")));



                    // PAGE BREAK
                    body.AppendChild(new Paragraph(
                                         new Run(
                                             new Break()
                    {
                        Type = BreakValues.Page
                    })));
                }

                //run.AppendChild(new Text("From Date: " + agenda.fromDate.ToShortDateString() + " to "  + agenda.toDate.ToShortDateString()));
            }


            SessionController session = new SessionController();

            var user = session.Get();

            session.Dispose();

            FileStream documentStream = new FileStream(fileName, FileMode.Open);


            MailMessage msg = new MailMessage();

            msg.To.Add(new MailAddress(user.userEmail));
            //msg.Bcc.Add(new MailAddress("*****@*****.**"));
            msg.From       = new MailAddress("*****@*****.**");
            msg.Subject    = "CFS Incident Reports: Agenda Document";
            msg.IsBodyHtml = true;


            msg.Attachments.Add(new System.Net.Mail.Attachment(documentStream, agenda.agendaTitle + ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));

            StringBuilder messageBody = new StringBuilder();

            messageBody.Append("<h1>Incident Reports Agenda</h1>");
            messageBody.Append("<p>An agenda document has been created and is attached.</p>");
            messageBody.Append("<p>A copy has been saved <a href=\"\\\\844dc2\\Residential Incidents\\\">here</a>.</p>");

            msg.Body = messageBody.ToString();

            SmtpClient smtp = new SmtpClient("cfs-mailserv");

            smtp.Send(msg);


            smtp.Dispose();
            msg.Dispose();

            documentStream.Close();
            documentStream.Dispose();

            return(fileName);
        }
        public long Post([FromBody] Models.IncidentReport report)
        {
            if (report.userId == 0)
            {
                SessionController session = new SessionController();
                var user = session.Get();

                report.userId         = user.userId;
                report.createdStation = user.stationInfo;
                report.currentUser    = user.userId;

                session.Dispose();
            }

            if (report.incidentId == 0)
            {
                // CREATE REPORT
                this._db.IncidentReports.Add(report);
            }
            else
            {
                this._db.IncidentReports.Attach(report);
                this._db.Entry(report).State = System.Data.Entity.EntityState.Modified;
            }

            try
            {
                this._db.SaveChanges();


                // WRITE TO REPORT LOG
                Models.ReportLog log = new Models.ReportLog();
                log.incidentId  = report.incidentId;
                log.userId      = report.userId;
                log.userStation = report.createdStation;
                log.logDateTime = DateTime.Now;
                log.logDetails  = "Report created.";

                LogController logController = new LogController();
                logController.Post(log);
                logController.Dispose();


                // NOTIFY
                MailController mailer = new MailController();



                StringBuilder messageBody = new StringBuilder();

                messageBody.Append("<p>A new incident report for <b>" + report.clientName + "</b> has been created by " + report.staffName + ".</p>");
                messageBody.Append("<p><a href=\"http://cfs-incidents/report/residential/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>");

                if (report.incidentReportTypeId == 1)
                {
                    mailer.SendMail(
                        new List <string>()
                    {
                        "*****@*****.**"
                    },
                        "*****@*****.**",
                        "New Incident Report",
                        System.Net.Mail.MailPriority.High,
                        messageBody
                        );
                }
                else
                {
                    mailer.SendMail(
                        new List <string>()
                    {
                        "*****@*****.**"
                    },
                        "*****@*****.**",
                        "New Incident Report",
                        System.Net.Mail.MailPriority.High,
                        messageBody
                        );
                }

                mailer.Dispose();

                return(report.incidentId);
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);


                MailController mailer = new MailController();
                mailer.SendMail(
                    new List <string>()
                {
                    "*****@*****.**"
                },
                    "*****@*****.**",
                    "ERROR CREATING INCIDENT: VALIDATION",
                    System.Net.Mail.MailPriority.High,
                    exceptionMessage
                    );

                string currentUser = RequestContext.Principal.Identity.Name;

                mailer.SendExceptionDetail("post:/api/reports", exceptionMessage, ex.StackTrace, currentUser, report);


                // Throw a new DbEntityValidationException with the improved exception message.
                throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                if (ex.InnerException != null)
                {
                    errorMessage += " Inner Exception: " + ex.InnerException;
                }

                MailController mailer = new MailController();
                mailer.SendMail(
                    new List <string>()
                {
                    "*****@*****.**"
                },
                    "*****@*****.**",
                    "ERROR CREATING INCIDENT",
                    System.Net.Mail.MailPriority.High,
                    errorMessage
                    );

                string currentUser = RequestContext.Principal.Identity.Name;

                mailer.SendExceptionDetail("post:/api/reports", errorMessage, ex.StackTrace, currentUser, report);

                throw new Exception(errorMessage);
            }
        }
        public void SupervisorFinalApprove([FromBody] Models.Presentation.ReportSignatureModel signatureInfo)
        {
            Models.IncidentReport report = this._db.IncidentReports.Where(r => r.incidentId == signatureInfo.incidentId).SingleOrDefault();
            string logDetails            = string.Empty;


            if (report != null)
            {
                string userName = System.Web.HttpContext.Current.User.Identity.Name.Substring(5).ToLower();
                if (userName.ToLower() != signatureInfo.userName.ToLower())
                {
                    throw new Exception("Current user information is not synchronized.  Cannot approve report.");
                }

                SessionController session = new SessionController();

                bool userVerified = session.VerifyPassword(userName, signatureInfo.signature);
                session.Dispose();

                if (userVerified)
                {
                    // GET SUPERVISOR SIGNATURE RECORD
                    Models.ReportSign supervisorSignature = this._db.ReportSigns.Where(
                        s => s.incidentId == signatureInfo.incidentId &&
                        s.reportSigType == "S" &&
                        s.reportSigUserId == signatureInfo.currentUser).SingleOrDefault();

                    if (supervisorSignature == null)
                    {
                        throw new Exception("Could not find signature record.  Cannot approve report.");
                    }
                    else
                    {
                        supervisorSignature.approvalStatusId = signatureInfo.approvalStatusId;
                        supervisorSignature.reportSigStamp   = DateTime.Now;
                        supervisorSignature.reportSigStation = signatureInfo.stationName;
                        supervisorSignature.approvalComments = signatureInfo.approvalComments;

                        this._db.ReportSigns.Attach(supervisorSignature);
                        this._db.Entry(supervisorSignature).State = System.Data.Entity.EntityState.Modified;



                        if (signatureInfo.approvalStatusId == 3) // SUPERVISOR APPROVED
                        {
                            // SUPERVISOR APPROVES, REPORT SENT TO ADMINS FOR REVIEW
                            Models.ReportSign adminSignature = new Models.ReportSign();

                            adminSignature.incidentId        = signatureInfo.incidentId;
                            adminSignature.incidentMedicalId = 0;
                            adminSignature.reportSigType     = "A";
                            adminSignature.reportSigUserId   = 0;
                            adminSignature.staffName         = "Administrator";
                            adminSignature.staffTitle        = "Administrator";
                            adminSignature.approvalStatusId  = 1;

                            this._db.ReportSigns.Add(adminSignature);

                            // EMAIL ADMINS!!!! (INCLUDE ADMINS?)

                            logDetails = "Supervisor approved report.";
                        }
                        else
                        {
                            // NOTIFY EMPLOYEE REPORT REJECTED


                            logDetails = "Supervisor rejected report. Comments: " + signatureInfo.approvalComments;
                        } // if (signatureInfo.approvalStatusId == 3)


                        // UPDATE REPORT STATUS

                        report.statusId       = signatureInfo.statusId;
                        report.currentUser    = signatureInfo.currentUser;
                        report.lastModified   = DateTime.Now;
                        report.lastModifiedBy = signatureInfo.currentUser;

                        this._db.IncidentReports.Attach(report);
                        this._db.Entry(report).State = System.Data.Entity.EntityState.Modified;


                        // WRITE CHANGES TO LOG

                        Models.ReportLog log = new Models.ReportLog();

                        log.incidentId  = signatureInfo.incidentId;
                        log.userId      = signatureInfo.currentUser;
                        log.userStation = signatureInfo.stationName;
                        log.logDateTime = DateTime.Now;
                        log.logDetails  = logDetails;

                        this._db.ReportLogs.Add(log);



                        // IF JUSTICE CENTER CALLED, NOTIFY CORPORATE COMPLIANCE


                        // notifyPartyId = 8 (Justice Center)
                        bool jcCalled = this._db.Notifications.Where(n => n.incidentId == signatureInfo.incidentId && n.notifyPartyId == 8).Any();

                        if (jcCalled)
                        {
                            Models.Notification ccNotification = new Models.Notification();

                            ccNotification.incidentId        = signatureInfo.incidentId;
                            ccNotification.notifyPartyId     = 37; // Corporate Compliance
                            ccNotification.notifyDateTime    = DateTime.Now;
                            ccNotification.notifyContact     = "CFS Corporate Compliance";
                            ccNotification.notifyMethod      = "E-Mail";
                            ccNotification.notifyStaffId     = 0;
                            ccNotification.isAcknowledged    = 1;
                            ccNotification.acknowledgeUserId = 0;

                            this._db.Notifications.Add(ccNotification);

                            MailController mailer = new MailController();

                            List <string> sendTos = new List <string>();
                            sendTos.Add("*****@*****.**");

                            StringBuilder msg = new StringBuilder();
                            msg.Append("<h1>Incident Report Notification</h1>");
                            msg.Append("<p>An incident report has been created for client " + report.clientName + " by " + report.staffName);
                            msg.Append(", and the Justice Center was called.</p>");

                            mailer.SendMail(sendTos, "*****@*****.**", "Incident Reports: Justice Center Called", System.Net.Mail.MailPriority.Normal, msg);
                        }



                        this._db.SaveChanges();
                    }  // if (supervisorSignature == null)
                }
                else
                {
                    throw new Exception("Unable to validate signature.  Please use your current CFS account password to sign.");
                }  // if (userVerified)
            }
        }
        public void FinalApprove([FromBody] Models.Presentation.ReportSignatureModel signatureInfo)
        {
            Models.IncidentReport report = this._db.IncidentReports.Where(r => r.incidentId == signatureInfo.incidentId).SingleOrDefault();

            if (report != null)
            {
                string userName = System.Web.HttpContext.Current.User.Identity.Name.Substring(5).ToLower();
                if (userName.ToLower() != signatureInfo.userName.ToLower())
                {
                    throw new Exception("Current user information is not synchronized.  Cannot approve report.");
                }

                SessionController session = new SessionController();

                bool userVerified = session.VerifyPassword(userName, signatureInfo.signature);
                session.Dispose();

                if (userVerified)
                {
                    Models.ReportSign staffSignature = new Models.ReportSign();

                    staffSignature.incidentId        = signatureInfo.incidentId;
                    staffSignature.incidentMedicalId = 0;
                    staffSignature.reportSigType     = "E";
                    staffSignature.reportSigUserId   = signatureInfo.currentUser;
                    staffSignature.staffName         = signatureInfo.staffName;
                    staffSignature.staffTitle        = signatureInfo.staffTitle;
                    staffSignature.approvalStatusId  = 3;
                    staffSignature.reportSigStamp    = DateTime.Now;
                    staffSignature.reportSigStation  = signatureInfo.stationName;

                    this._db.ReportSigns.Add(staffSignature);



                    StaffController staffs     = new StaffController();
                    Models.User     supervisor = staffs.GetStaffSupervisor(signatureInfo.currentUser);
                    staffs.Dispose();


                    Models.ReportSign supervisorSignature = new Models.ReportSign();

                    supervisorSignature.incidentId        = signatureInfo.incidentId;
                    supervisorSignature.incidentMedicalId = 0;
                    supervisorSignature.reportSigType     = "S";
                    supervisorSignature.reportSigUserId   = supervisor.userId;
                    supervisorSignature.staffName         = supervisor.firstName + " " + supervisor.lastName;
                    supervisorSignature.staffTitle        = supervisor.jobTitle;
                    supervisorSignature.approvalStatusId  = 1;

                    this._db.ReportSigns.Add(supervisorSignature);



                    // WRITE CHANGES TO LOG

                    Models.ReportLog log = new Models.ReportLog();

                    log.incidentId  = signatureInfo.incidentId;
                    log.userId      = signatureInfo.currentUser;
                    log.userStation = signatureInfo.stationName;
                    log.logDateTime = DateTime.Now;
                    log.logDetails  = "Report signed by staff.";

                    this._db.ReportLogs.Add(log);



                    // EMAIL SUPERVISOR!!!! (INCLUDE ADMINS?)


                    MailController mailer      = new MailController();
                    StringBuilder  messageBody = new StringBuilder();
                    messageBody.Append("<p>A new incident report for <b>" + report.clientName + "</b> has been posted by " + report.staffName + ".</p>");
                    messageBody.Append("<p><a href=\"http://cfs-incidents/report/residential/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>");

                    mailer.SendMail(
                        new List <string>()
                    {
                        supervisor.eMail, "*****@*****.**"
                    },
                        "*****@*****.**",
                        "Incident Report Posted",
                        System.Net.Mail.MailPriority.High,
                        messageBody
                        );

                    mailer.Dispose();



                    report.statusId       = signatureInfo.statusId;
                    report.currentUser    = signatureInfo.currentUser;
                    report.lastModified   = DateTime.Now;
                    report.lastModifiedBy = signatureInfo.currentUser;

                    this._db.IncidentReports.Attach(report);
                    this._db.Entry(report).State = System.Data.Entity.EntityState.Modified;



                    this._db.SaveChanges();
                }
                else
                {
                    throw new Exception("Unable to validate signature.  Please use your current CFS account password to sign.");
                }
            }
        }