using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Utilities;
using Fab2ApprovalSystem.ViewModels;

using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

namespace Fab2ApprovalSystem.Controllers;

[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter]
public class CorrectiveActionController : Controller {

    AuditDMO auditDMO = new AuditDMO(GlobalVars.AppSettings);
    CorrectiveActionDMO caDMO = new CorrectiveActionDMO();
    WorkflowDMO wfDMO = new WorkflowDMO();
    private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
    UserAccountDMO userDMO = new UserAccountDMO();
    FileUtilities<System.Web.Mvc.FileContentResult> fileUtilities = new FileUtilities<System.Web.Mvc.FileContentResult>();

    public ActionResult Index() {
        return View();
    }

    public ActionResult Create() {
        CorrectiveAction ca = new CorrectiveAction();
        try {
            // TODO: Add insert logic here

            ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID];
            caDMO.InsertCA(ca);
            return RedirectToAction("Edit", new { issueID = ca.CANo });
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
            throw new Exception(e.Message);
        }
    }

    public ActionResult CreateFromAudit(string title) {
        CorrectiveAction ca = new CorrectiveAction();
        try {
            // TODO: Add insert logic here

            ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID];
            ca.CASource = "Audit";
            caDMO.InsertCA(ca);
            string test = ca.CANoDisp;
            return Content((ca.CANo).ToString());
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
            throw new Exception(e.Message);
        }
    }

    public ActionResult Edit(int issueID) {
        CorrectiveAction ca = new CorrectiveAction();
        string s = Functions.ReturnCANoStringFormat(issueID);
        try {
            List<int> _8DQAList = caDMO.Get8DQA();

            int QAs = _8DQAList.Find(delegate (int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; });

            ViewBag.Is8DQA = "false";
            if (QAs != 0) {
                ViewBag.Is8DQA = "true";
            }

            ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]);

            ViewBag.CanCompleteCA = "false";
            if (ca.D1AssigneeID == (int)Session[GlobalVars.SESSION_USERID])
                ViewBag.CanCompleteCA = "true";

            List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, ca.CurrentStep, (int)GlobalVars.DocumentType.CorrectiveAction);
            ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; });
            if (approver == null)
                ViewBag.IsApprover = "false";
            else
                ViewBag.IsApprover = "true";

            ViewBag.IsAIAssignee = caDMO.IsAIAssignee((int)Session[GlobalVars.SESSION_USERID], issueID);
            ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, (int)Session[GlobalVars.SESSION_USERID]);
            ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList();
            if (ca.RelatedAudit != null && ca.RelatedAudit > 0) {
                Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]);
                IEnumerable<AuditFindings> auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo);

                AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First();

                string relatedAuditFinding = relatedFinding.Findings;
                IEnumerable<int> relatedAuditFindingCatIds = auditDMO.GetAuditFindingCategoryIdsByFindingId(relatedFinding.ID);
                string relatedViolatedClause = relatedFinding.ViolatedClause;

                ViewBag.AuditFinding = relatedAuditFinding;
                ViewBag.AuditFindingCategories = relatedAuditFindingCatIds;
                ViewBag.ViolatedClause = relatedViolatedClause;
            } else {
                ViewBag.AuditFinding = "";
                ViewBag.AuditFindingCategories = "";
                ViewBag.ViolatedClause = "";
            }

            if ((ca.ClosedDate != null) ||
                 // TODO Aproverslist================================================================
                 (ca.ClosedDate != null && ViewBag.IsApprover == "false" && ViewBag.IsAIAssignee == "false") ||
                (ca.RecordLockIndicator && ca.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ca.Status == 11 && ViewBag.IsApprover == "false")) {
                return RedirectToAction("ReadOnlyCA", new { caNo = ca.CANo });
            } else {
                ViewBag.ECNList = caDMO.GetECNList();
                if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11) {
                    // Pulling in the user list which includes inactive users.
                    ViewBag.UserList = caDMO.GetAllUserList();
                } else {
                    // Pulling in the user list which only includes active users.
                    ViewBag.UserList = caDMO.GetUserList();
                }
                ViewBag.CASourceList = caDMO.GetCASourceList();
                ViewBag.ModuleList = caDMO.GetModuleList();
                ViewBag.D3RiskAssessmentAreas = caDMO.GetD3RiskAssessmentAreas();
                ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement();
            }

        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit - CA\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString });
            throw new Exception(e.Message);
        }

        return View(ca);
    }

    [HttpPost]
    public ActionResult Edit(CorrectiveAction model) {
        int currentUserId = (int)Session[GlobalVars.SESSION_USERID];
        CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId);
        if ((currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID)) {
            return Content("User is not authorized to save the CA.");
        }
        try {
            caDMO.UpdateCorrectiveAction(model);

            if ((model.D1AssigneeID != model.CurrentD1AssigneeID && model.CASubmitted) || (model.CASubmitted && !caPrevious.CASubmitted)) {
                // Set Due Dates here:
                DateTime? D3DueDate = null;
                DateTime? D5D7DueDate = null;

                if (model.CAType != "D0") {
                    D3DueDate = SetD3DueDate(model.CANo);
                    if (model.CAType != "D3") {
                        D5D7DueDate = SetD5D7DueDate(model.CANo);
                    }
                }

                NotifyAssignee(model.CANo, model.D1AssigneeID, "CorrectiveActionAssignee.txt", D3DueDate, D5D7DueDate);
            }

            if (model.TriggerSectionApproval) {
                if (model.SectionApproval == "D5D6D7Validation") {
                    caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval);
                    return Content("Successfully Saved...Validation initiated!");
                }
                caDMO.StartSectionApproval(model.CANo, model.QAID, model.SectionApproval);
                caDMO.StartSectionApproval(model.CANo, model.RequestorID, model.SectionApproval);

                NotifySectionApprover(model.CANo, model.QAID, model.SectionApproval);

                NotifySectionApprover(model.CANo, model.RequestorID, model.SectionApproval);
                return Content("Successfully Saved...Approval initiated!");
            }
            if (model.TriggerApproval) {
                caDMO.StartApproval(model.CANo, (int)Session[GlobalVars.SESSION_USERID], model.WorkFlowNumber);
                NotifyApprovers(model.CANo, 1);
                return Content("Successfully Saved...Approval initiated!");
            }
        } catch (Exception ex) {
            return Content(ex.Message);
        }

        return Content("Successfully Saved");
    }

    public ActionResult ReadOnlyCA(int caNo) {
        CorrectiveAction ca = new CorrectiveAction();

        ca = caDMO.GetCAItemReadOnly(caNo, (int)Session[GlobalVars.SESSION_USERID]);
        if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11 || ca.ClosedDate != null) {
            ViewBag.UserList = caDMO.GetAllUserList();
        } else {
            ViewBag.UserList = caDMO.GetUserList();
        }
        ViewBag.CASourceList = caDMO.GetCASourceList();
        ViewBag.ModuleList = caDMO.GetModuleList();
        ViewBag.D3RiskAssessmentAreas = caDMO.GetD3RiskAssessmentAreas();
        ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement();

        ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList();
        if (ca.RelatedAudit != null && ca.RelatedAudit > 0) {
            Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]);
            IEnumerable<AuditFindings> auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo);

            AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First();

            string relatedAuditFinding = relatedFinding.Findings;
            IEnumerable<int> relatedAuditFindingCatIds = auditDMO.GetAuditFindingCategoryIdsByFindingId(relatedFinding.ID);
            string relatedViolatedClause = relatedFinding.ViolatedClause;

            ViewBag.AuditFinding = relatedAuditFinding;
            ViewBag.AuditFindingCategories = relatedAuditFindingCatIds;
            ViewBag.ViolatedClause = relatedViolatedClause;
        } else {
            ViewBag.AuditFinding = "";
            ViewBag.AuditFindingCategories = "";
            ViewBag.ViolatedClause = "";
        }

        return View(ca);
    }

    public void ReleaseLockOnDocumentAdmin(int issueID) {
        try {
            caDMO.ReleaseLockOnDocument(-1, issueID);
        } catch (Exception e) {
            try {
                Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
            } catch { }
            caDMO.ReleaseLockOnDocument(-1, issueID);
        }
    }

    public ActionResult GetD2AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) {

        return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D2)).ToDataSourceResult(request));
    }

    public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int caNO) {
        return Json(caDMO.GetCAAttachmentsList(caNO, "Main").ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public void DeleteCAAttachment(int attachmentID) {
        caDMO.DeleteCAAttachment(attachmentID);
    }

    public ActionResult DownloadCAAttachment(string fileGuid, int caNo) {
        try {
            string fileName = caDMO.GetCAAttachmentFileName(fileGuid);

            string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));

            string ecnFolderPath = _AppSettings.AttachmentFolder + "CorrectiveAction\\" + caNo.ToString();
            var sDocument = System.IO.Path.Combine(ecnFolderPath, fileGuid + fileExtension);

            var FDir_AppData = _AppSettings.AttachmentFolder;
            if (!sDocument.StartsWith(FDir_AppData)) {
                // Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
                // and block requests outside like "../web.config"
                throw new HttpException(403, "Forbidden");
            }

            if (!System.IO.File.Exists(sDocument)) {
                return null;
            }

            return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        } catch {
            // TODO - proces the error
            throw;
        }
    }

    public ActionResult DownloadTemplatesFiles() {
        string fileName = "5Why_Is_Is_Not_Fishbone.pptx";
        string pathToFile = GlobalVars.MesaTemplateFiles + "\\5Why_Is_Is_Not_Fishbone.pptx";
        byte[] fileBytes = fileUtilities.GetFile(pathToFile);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }

    public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int caNo) {
        try {
            // The Name of the Upload component is "files"
            if (files != null) {
                int userId = (int)Session[GlobalVars.SESSION_USERID];
                foreach (var file in files) {
                    CorrectiveActionHelper.AttachSave(_AppSettings, caDMO, caNo, userId, file.FileName, file.InputStream);
                }
            }
        } catch {
            throw;
        }

        return Content("");
    }

    public ActionResult GetD3ContainmentActionsList([DataSourceRequest] DataSourceRequest request, int caNo) {
        return Json(caDMO.GetD3ContainmentActions(caNo).ToDataSourceResult(request));
    }

    public ActionResult UpdateD3ContainmentAction(D3ContainmentAction data) {
        caDMO.UpdateD3ContainmentAction(data);
        if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) {
            NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
        }

        return Content("");
    }

    public ActionResult InsertD3ContainmentAction(D3ContainmentAction data) {
        caDMO.InsertD3ContainmentAction(data);
        if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) {
            NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
        }
        return Content("");
    }

    [HttpPost]
    public void DeletetD3ContainmentActionItem(int d3ContainmentActionID) {
        caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID);
    }

    public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) {
        return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D4)).ToDataSourceResult(request));
    }

    public ActionResult D4FilesAttachSave(IEnumerable<HttpPostedFileBase> D4Files, int caNo) {
        try {
            // The Name of the Upload component is "files"
            if (D4Files != null) {
                int userId = (int)Session[GlobalVars.SESSION_USERID];
                foreach (var file in D4Files) {
                    CorrectiveActionHelper.D4FilesAttachSave(_AppSettings, caDMO, caNo, userId, file.FileName, file.InputStream);
                }
            }
        } catch {
            throw;
        }

        return Content("");
    }

    public ActionResult GetD5D6CorrectivetActionList([DataSourceRequest] DataSourceRequest request, int caNo) {
        return Json(caDMO.GetD5D6CorrectivetActions(caNo).ToDataSourceResult(request));
    }

    public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data) {
        try {
            caDMO.InsertD5D6CorrectivetAction(data);
        } catch (Exception e) {
            return Content(e.Message + " Please try again...");
        }
        return Content("");
    }

    public ActionResult UpdateD5D6CAItem(D5D6CorrectivetAction data) {
        D5D6CorrectivetAction previousData = caDMO.GetD5D5CAItem(data.ID);
        CorrectiveAction caData = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]);
        try {
            caDMO.UpdateD5D6CorrectivetAction(data);
        } catch (Exception e) {
            return Content(e.Message + " Please try again...");
        }
        if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) {
            NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
        }
        if (data.IsImplemented && previousData.ImplementedDate == null) {
            // Notify completion to Assignee and Requestor
            NotifyActionItemCompletion(data.CANo, data.ECD, caData.D1AssigneeID, "CorrectiveActionAICompleted.txt");
            NotifyActionItemCompletion(data.CANo, data.ECD, caData.RequestorID, "CorrectiveActionAICompleted.txt");
            NotifyActionItemCompletion(data.CANo, data.ECD, caData.QAID, "CorrectiveActionAICompleted.txt");
        }
        return Content("");
    }

    public ActionResult GetD5D6CAItem(int d5d6CAID) {
        var model = new D5D6CorrectivetAction();
        model = caDMO.GetD5D5CAItem(d5d6CAID);

        return PartialView("_D5D6CAAttachment", model);
    }

    public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID) {
        return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request));
    }

    [HttpPost]
    public void DeleteD5D6CAItem(int d5d6CAID) {
        caDMO.DeleteD5D6CorrectivetAction(d5d6CAID);
    }

    public ActionResult SaveD5D6CA_Attachemnt(IEnumerable<HttpPostedFileBase> D5D6CA_Attachemnt, int d5d6CAID, int caNo) {
        try {
            // The Name of the Upload component is "files"
            if (D5D6CA_Attachemnt != null) {
                int userId = (int)Session[GlobalVars.SESSION_USERID];
                foreach (var file in D5D6CA_Attachemnt) {
                    CorrectiveActionHelper.SaveD5D6CA_Attachemnt(_AppSettings, caDMO, d5d6CAID, caNo, userId, file.FileName, file.InputStream);
                }
            }
        } catch {
            throw;
        }

        return Content("");
    }

    // D7 ====================================================================================
    public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo) {
        return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request));
    }

    public ActionResult InsertD7PAItem(D7PreventiveAction data) {
        caDMO.InsertD7PreventiveAction(data);
        if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) {
            NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
        }

        return Content("");
    }

    public ActionResult UpdateD7PAItem(D7PreventiveAction data) {
        caDMO.UpdateD7PreventiveAction(data);
        if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) {
            NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
        }

        return Content("");
    }

    public ActionResult GetD7PAItem(int d7paID) {
        var model = new D7PreventiveAction();
        model = caDMO.GetD7PAItem(d7paID);

        return PartialView("_D7PAAttachment", model);
    }

    public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID) {
        return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request));
    }

    [HttpPost]
    public void DeleteD7PAItem(int d7PAID) {
        caDMO.DeleteD7PreventiveActionItem(d7PAID);
    }

    public ActionResult SaveD7PA_Attachemnt(IEnumerable<HttpPostedFileBase> D7PA_Attachemnt, int d7PAID, int caNo) {
        try {
            // The Name of the Upload component is "files"
            if (D7PA_Attachemnt != null) {
                int userId = (int)Session[GlobalVars.SESSION_USERID];
                foreach (var file in D7PA_Attachemnt) {
                    CorrectiveActionHelper.SaveD7PA_Attachemnt(_AppSettings, caDMO, d7PAID, caNo, userId, file.FileName, file.InputStream);
                }
            }
        } catch {
            throw;
        }

        return Content("");
    }

    public void ReleaseLockOnDocument(int issueID) {
        try {
            caDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID);
        } catch (Exception e) {
            try {
                Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
            } catch { }
            caDMO.ReleaseLockOnDocument(-1, issueID);
        }
    }

    public JsonResult GetAllUsersList() {
        UserAccountDMO userDMO = new UserAccountDMO();
        IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
        return Json(userlist, JsonRequestBehavior.AllowGet);
    }

    public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) {
        var email = "";
        try {
            email = wfDMO.ReAssignApproval(issueID, reAssignApproverFrom, reAssignApproverTo, step, docType);
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
            throw new Exception(e.Message);
        }
        CorrectiveActionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email);
        try {
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email });
        } catch { }
    }

    public void ReAssignApproval(int issueID, int userIDs, byte step) {
        var email = "";
        try {
            email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction);
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
            throw new Exception(e.Message);
        }
        CorrectiveActionHelper.ReAssignApproval(_AppSettings, issueID, email);
        try {
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email });
        } catch { }
    }

    public void Reject(int issueID, byte currentStep, string comments) {
        try {
            if (Session[GlobalVars.SESSION_USERID] != null) {
                wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction);
                NotifyRejectionToAssignee(issueID, comments);
            } else {
                Response.Redirect("~/Account/Login");
            }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString });
            throw new Exception(e.Message);
        }
    }

    public void NotifyRejectionToAssignee(int issueID, string comments) {
        string username = Session[GlobalVars.SESSION_USERNAME].ToString();
        List<string> emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList();
        string userEmail = CorrectiveActionHelper.NotifyRejectionToAssignee(_AppSettings, issueID, comments, username, emailIst);
        try {
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Rejection: " + userEmail });
        } catch { }
    }

    public void Approve(int issueID, byte currentStep, string comments) {
        int isITARCompliant = 1;
        try {
            bool lastStep = false;
            CorrectiveAction ca = caDMO.GetCAItemReadOnly(issueID, (int)Session[GlobalVars.SESSION_USERID]);

            bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber);

            if (lastApprover && !lastStep) {
                // Set to complete
                DateTime followUpDate = caDMO.SetCAComplete(issueID);
                // Notify completion and send follow up date
                NotifyCompletionOf8D(issueID, followUpDate);

            }
            if (lastApprover && lastStep) {
                // Notify re the closure of the 8D
                NotifyClosureOf8D(issueID);

            }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString });
            throw new Exception(e.Message);
        }
    }

    public void NotifySectionApprover(int issueID, int userId, string section) {
        try {
            string userEmail = userDMO.GetUserEmailByID(userId);
            CorrectiveActionHelper.NotifySectionApprover(_AppSettings, issueID, section, userEmail);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
            throw e;
        }
    }

    public void NotifyApprovers(int issueID, byte currentStep) {
        try {
            List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList();
            string emailSentList = CorrectiveActionHelper.NotifyApprovers(_AppSettings, issueID, emailIst);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
            throw e;
        }
    }

    #region Additional Approvers

    public void AddAdditionalApproval(int issueID, byte step, string userIDs) {
        string emailSentList = "";
        var emailArray = "";
        try {
            emailArray = wfDMO.AddAdditionalApproval(issueID, userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction);
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
            throw new Exception(e.Message);
        }
        emailSentList = CorrectiveActionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray);
        try {
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList });
        } catch { }
    }

    #endregion

    public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) {
        return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.CorrectiveAction).ToDataSourceResult(request));
    }

    public ActionResult GetSectionApprovalLog([DataSourceRequest] DataSourceRequest request, int caNo) {
        return Json(caDMO.GetCASectionApprovalLog(caNo).ToDataSourceResult(request));
    }

    public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) {
        try {
            string email = MiscDMO.GetEmail(responsibleOwnerID);
            CorrectiveActionHelper.NotifyRequestor(_AppSettings, issueID, dueDate, template, email);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }

            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString });
        }
    }

    public void NotifyAssignee(int issueID, int? responsibleOwnerID, string template, DateTime? D3DueDate, DateTime? D5D7DueDate) {
        try {
            string email = MiscDMO.GetEmail(responsibleOwnerID);
            CorrectiveActionHelper.NotifyAssignee(_AppSettings, issueID, template, D3DueDate, D5D7DueDate, email);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }

            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString });
        }
    }

    public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) {
        try {
            string email = CorrectiveActionHelper.NotifyActionItemOwner(_AppSettings, issueID, dueDate, responsibleOwnerID, template);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }

            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString });
        }
    }

    public void NotifyActionItemCompletion(int issueID, DateTime? dueDate, int? recipientId, string template) {
        try {
            string email = CorrectiveActionHelper.NotifyActionItemCompletion(_AppSettings, issueID, dueDate, recipientId, template);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }

            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemCompletion\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString });
        }
    }

    public void NotifyClosureOf8D(int issueID) {
        try {
            string emailSentList = CorrectiveActionHelper.NotifyClosureOf8D(_AppSettings, issueID);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }

            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Closure of 8D  - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString });
        }
    }

    public void NotifyCompletionOf8D(int issueID, DateTime? followUpDate) {
        try {
            string emailSentList = CorrectiveActionHelper.NotifyCompletionOf8D(_AppSettings, issueID, followUpDate);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }

            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Closure of 8D  - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString });
        }
    }

    public void StartSectionApproval(int issueID, string dSection) {
        try {
            CorrectiveAction ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]);

            int requestorId = ca.RequestorID;
            int qaId = ca.QAID;

            caDMO.StartSectionApproval(issueID, requestorId, dSection);
            NotifySectionApprover(issueID, requestorId, dSection);
            caDMO.StartSectionApproval(issueID, qaId, dSection);
            NotifySectionApprover(issueID, qaId, dSection);
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString });
            throw new Exception(e.Message);
        }
    }
    [HttpPost]
    public ActionResult ApproveSection(int issueID, string dSection) {
        try {
            int userID = (int)Session[GlobalVars.SESSION_USERID];
            CorrectiveAction caItem = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]);
            caDMO.ApproveSection(issueID, userID, dSection);
            bool isLastApprover = caDMO.IsLastSectionApprover(issueID, dSection);
            if (isLastApprover) {
                if (dSection == "D5D6D7") {
                    NotifyForD5D6D7Validation(issueID, caItem.D1AssigneeID, dSection);
                    NotifyForD5D6D7Validation(issueID, caItem.RequestorID, dSection);
                    NotifyForD5D6D7Validation(issueID, caItem.QAID, dSection);

                    // Notify AI owners of pending action items
                    List<D5D6CorrectivetAction> actionItems = caDMO.GetD5D6CorrectivetActions(issueID).ToList();
                    foreach (var item in actionItems) {
                        NotifyActionItemOwner(issueID, item.ECD, item.CurrentResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
                    }
                } else {
                    NotifyUsersDSectionApproved(issueID, caItem.D1AssigneeID, dSection);
                    NotifyUsersDSectionApproved(issueID, caItem.RequestorID, dSection);
                    NotifyUsersDSectionApproved(issueID, caItem.QAID, dSection);
                }
                // TODO Notify Requestor for approval
                return Content("Successfully Saved, Last Approver");
            } else {
                return Content("Successfully Saved, More Approvers");
            }

        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString });
            return Content(e.Message);
        }
    }
    [HttpPost]
    public ActionResult RejectSection(int issueID, string dSection, string comments) {
        try {

            int userID = (int)Session[GlobalVars.SESSION_USERID];
            CorrectiveAction ca = caDMO.GetCAItem(issueID, userID);
            caDMO.RejectSection(issueID, userID, dSection, comments);
            // Notify Rejection to assignee and requestor
            int assigneeId = ca.D1AssigneeID;
            int requestorId = ca.RequestorID;
            int qaId = ca.QAID;
            NotifySectionRejection(issueID, assigneeId, userID, dSection, comments);
            NotifySectionRejection(issueID, requestorId, userID, dSection, comments);
            NotifySectionRejection(issueID, qaId, userID, dSection, comments);

            return Content("Successfully Saved");
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Reject\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString });
            return Content(e.Message);
        }
    }
    public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment) {
        try {
            LoginModel recipient = userDMO.GetUserByID(recipientUserId);
            LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId);
            CorrectiveActionHelper.NotifySectionRejection(_AppSettings, issueID, section, comment, recipient, loggedInUser);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
            throw e;
        }
    }

    public void NotifyForD5D6D7Validation(int issueID, int userId, string dSection) {
        try {
            string userEmail = userDMO.GetUserEmailByID(userId);
            CorrectiveActionHelper.NotifyForD5D6D7Validation(_AppSettings, issueID, dSection, userEmail);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
            throw e;
        }
    }

    public void NotifyUsersDSectionApproved(int issueID, int userId, string dSection) {
        try {
            string userEmail = userDMO.GetUserEmailByID(userId);
            CorrectiveActionHelper.NotifyUsersDSectionApproved(_AppSettings, issueID, dSection, userEmail);
            try {
                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " });
            } catch { }
        } catch (Exception e) {
            string detailedException = "";
            try {
                detailedException = e.InnerException.ToString();
            } catch {
                detailedException = e.Message;
            }
            string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
            Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
            EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
            throw e;
        }
    }

    public DateTime SetD3DueDate(int caNo) {
        DateTime d3DueDate = caDMO.SetCAD3DueDate(caNo);

        return d3DueDate;
    }
    public DateTime SetD5D7DueDate(int caNo) {
        DateTime d5d7DueDate = caDMO.SetCAD5D7DueDate(caNo);
        return d5d7DueDate;
    }
    public bool ProcessCARDueDates() {
        bool isSuccess = false;
        List<CAD3D5D7Due> dueCAs = caDMO.GetCAD3D5D7Due().ToList();

        foreach (var dueCA in dueCAs) {
            CorrectiveAction ca = caDMO.GetCAItemReadOnly(dueCA.CANo, 999);
            int assigneeID = ca.D1AssigneeID;
            LoginModel user = userDMO.GetUserByID(assigneeID);

            try {
                CorrectiveActionHelper.ProcessCARDueDates(_AppSettings, dueCA, ca, user);
                caDMO.SetD3D5D7NotificationDate(dueCA.CANo, dueCA.ItemDue);
                isSuccess = true;

            } catch (Exception e) {
                isSuccess = false;
                string detailedException = "";
                try {
                    detailedException = e.InnerException.ToString();
                } catch {
                    detailedException = e.Message;
                }
                string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + dueCA.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
                Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - ProcessCARDueDates\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
                EventLogDMO.Add(new WinEventLog() { IssueID = dueCA.CANo, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ProcessCARDueDates - Called via API - " + exceptionString });

            }

        }
        return true;
    }

    public void ProcessCAForFollowUp() {
    }

}