using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using System.IO;
using System.Configuration;
using Fab2ApprovalSystem.ViewModels;
using Fab2ApprovalSystem.Utilities;

namespace Fab2ApprovalSystem.Controllers
{
    [Authorize]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    [SessionExpireFilter]
    public class CorrectiveActionController : Controller
    {
        CorrectiveActionDMO caDMO = new CorrectiveActionDMO();
        WorkflowDMO wfDMO = new WorkflowDMO();
        UserAccountDMO userDMO = new UserAccountDMO();
        AuditDMO auditDMO = new AuditDMO();
        FileUtilities fileUtilities = new FileUtilities();


        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(@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(@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);

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <returns></returns>
        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(@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
            {
                if (model.TriggerApproval)
                {
                    //model.FollowUpDate = DateTime.Now.AddMonths(6);
                }
                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);
                    //NotifyApprovers(model.CANo, 1);
                    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(@User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
                }
                catch { }
                caDMO.ReleaseLockOnDocument(-1, issueID);

            }


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        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);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="attachmentID"></param>
        [HttpPost]
        public void DeleteCAAttachment(int attachmentID)
        {
            caDMO.DeleteCAAttachment(attachmentID);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileGuid"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        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 = Functions.GetAttachmentFolder() + "CorrectiveAction\\" + caNo.ToString();
                var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension);

                var FDir_AppData = Functions.GetAttachmentFolder();
                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;
                    //throw new Exception("File not found");
                }

                return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
            }

            catch
            {
                // TODO - proces the error
                throw;
            }
        }
        public ActionResult DownloadTemplatesFiles()
        {

            //string templatesPath = GlobalVars.CA_BlankFormsLocation;
            //string fullName = Server.MapPath("~" + filePath);
            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);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="D2Files"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int caNo)
        {
            try
            {
                // The Name of the Upload component is "files"
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        // Some browsers send file names with full path.
                        // We are only interested in the file name.


                        var fileName = Path.GetFileName(file.FileName);
                        var fileExtension = Path.GetExtension(file.FileName);
                        //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);       
                        DirectoryInfo di;
                        var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo;
                        di = new DirectoryInfo(ccPhysicalPath);
                        if (!di.Exists)
                            di.Create();


                        var guid = Guid.NewGuid().ToString();
                        var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension);


                        file.SaveAs(physicalPath);
                        CA_Attachment attach = new CA_Attachment()
                        {
                            CANo = caNo,
                            FileGUID = guid,
                            FileName = fileName,
                            UploadedByID = (int)Session[GlobalVars.SESSION_USERID],
                            Section = Functions.CASectionMapper(GlobalVars.CASection.Main)
                        };


                        //ccDMO.InsertCCAttachment(attach);
                        caDMO.InsertCAAttachment(attach);
                    }
                }
            }
            catch
            {
                throw;
            }


            return Content("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        public ActionResult GetD3ContainmentActionsList([DataSourceRequest] DataSourceRequest request, int caNo)
        {

            return Json(caDMO.GetD3ContainmentActions(caNo).ToDataSourceResult(request));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        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("");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        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("");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="d3ContainmentActionID"></param>
        [HttpPost]
        public void DeletetD3ContainmentActionItem(int d3ContainmentActionID)
        {
            caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID);
        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo)
        {

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



        /// <summary>
        /// 
        /// </summary>
        /// <param name="D2Files"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        public ActionResult D4FilesAttachSave(IEnumerable<HttpPostedFileBase> D4Files, int caNo)
        {
            try
            {
                // The Name of the Upload component is "files"
                if (D4Files != null)
                {
                    foreach (var file in D4Files)
                    {
                        // Some browsers send file names with full path.
                        // We are only interested in the file name.


                        var fileName = Path.GetFileName(file.FileName);
                        var fileExtension = Path.GetExtension(file.FileName);
                        //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);       
                        DirectoryInfo di;
                        var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo;
                        di = new DirectoryInfo(ccPhysicalPath);
                        if (!di.Exists)
                            di.Create();


                        var guid = Guid.NewGuid().ToString();
                        var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension);


                        file.SaveAs(physicalPath);
                        CA_Attachment attach = new CA_Attachment()
                        {
                            CANo = caNo,
                            FileGUID = guid,
                            FileName = fileName,
                            UploadedByID = (int)Session[GlobalVars.SESSION_USERID],
                            Section = Functions.CASectionMapper(GlobalVars.CASection.D4)

                        };


                        //ccDMO.InsertCCAttachment(attach);
                        caDMO.InsertCAAttachment(attach);
                    }
                }
            }
            catch
            {
                throw;
            }


            return Content("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        public ActionResult GetD5D6CorrectivetActionList([DataSourceRequest] DataSourceRequest request, int caNo)
        {

            return Json(caDMO.GetD5D6CorrectivetActions(caNo).ToDataSourceResult(request));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data)
        {
            try
            {
                caDMO.InsertD5D6CorrectivetAction(data);
            }
            catch(Exception e)
            {
                return Content(e.Message + " Please try again...");
            }
            if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0)
            {
                //NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
                //NotifyRequestor(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
                

            }
            return Content("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        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("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="holdStepID"></param>
        /// <returns></returns>
        public ActionResult GetD5D6CAItem(int d5d6CAID)
        {
            var model = new D5D6CorrectivetAction();
            model = caDMO.GetD5D5CAItem(d5d6CAID);

            return PartialView("_D5D6CAAttachment", model);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="d5d6CAID"></param>
        /// <returns></returns>
        public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID)
        {

            return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="d5d6CAID"></param>
        [HttpPost]
        public void DeleteD5D6CAItem(int d5d6CAID)
        {
            caDMO.DeleteD5D6CorrectivetAction(d5d6CAID);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="D5D6CA_Attachemnt"></param>
        /// <param name="d5d6CAID"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        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)
                {
                    foreach (var file in D5D6CA_Attachemnt)
                    {
                        // Some browsers send file names with full path.
                        // We are only interested in the file name.


                        var fileName = Path.GetFileName(file.FileName);
                        var fileExtension = Path.GetExtension(file.FileName);
                        //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);       
                        DirectoryInfo di;
                        var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo;
                        di = new DirectoryInfo(ccPhysicalPath);
                        if (!di.Exists)
                            di.Create();


                        var guid = Guid.NewGuid().ToString();
                        var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension);


                        file.SaveAs(physicalPath);
                        CA_Attachment attach = new CA_Attachment()
                        {
                            D5D6CAID = d5d6CAID,
                            CANo = caNo,
                            FileGUID = guid,
                            FileName = fileName,
                            UploadedByID = (int)Session[GlobalVars.SESSION_USERID],
                            Section = Functions.CASectionMapper(GlobalVars.CASection.D5)

                        };

                        
                        caDMO.InsertCAAttachment(attach);
                    }
                }
            }
            catch
            {
                throw;
            }


            return Content("");
        }



        // D7 ====================================================================================
        public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo)
        {

            return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        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("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        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("");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="holdStepID"></param>
        /// <returns></returns>
        public ActionResult GetD7PAItem(int d7paID)
        {
            var model = new D7PreventiveAction();
            model = caDMO.GetD7PAItem(d7paID);

            return PartialView("_D7PAAttachment", model);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="d5d6CAID"></param>
        /// <returns></returns>
        public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID)
        {

            return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request));
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="d7PAID"></param>
        [HttpPost]
        public void DeleteD7PAItem(int d7PAID)
        {
            caDMO.DeleteD7PreventiveActionItem(d7PAID);
        }

        

       

       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="D5D6CA_Attachemnt"></param>
        /// <param name="d5d6CAID"></param>
        /// <param name="caNo"></param>
        /// <returns></returns>
        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)
                {
                    foreach (var file in D7PA_Attachemnt)
                    {
                        // Some browsers send file names with full path.
                        // We are only interested in the file name.


                        var fileName = Path.GetFileName(file.FileName);
                        var fileExtension = Path.GetExtension(file.FileName);
                        //var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);       
                        DirectoryInfo di;
                        var ccPhysicalPath = Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo;
                        di = new DirectoryInfo(ccPhysicalPath);
                        if (!di.Exists)
                            di.Create();


                        var guid = Guid.NewGuid().ToString();
                        var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"CorrectiveAction\" + caNo + @"\", guid + fileExtension);


                        file.SaveAs(physicalPath);
                        CA_Attachment attach = new CA_Attachment()
                        {
                            D7PAID = d7PAID,
                            CANo = caNo,
                            FileGUID = guid,
                            FileName = fileName,
                            UploadedByID = (int)Session[GlobalVars.SESSION_USERID],
                            Section = Functions.CASectionMapper(GlobalVars.CASection.D7)

                        };


                        caDMO.InsertCAAttachment(attach);
                    }
                }
            }
            catch
            {
                throw;
            }


            return Content("");
        }


        

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

            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public JsonResult GetAllUsersList()
        {
            //var userList = ldDMO.GetApprovedApproversList(issueID, currentStep);
            //return Json(userList, JsonRequestBehavior.AllowGet);

            UserAccountDMO userDMO = new UserAccountDMO();
            IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
            return Json(userlist, JsonRequestBehavior.AllowGet);

        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="reAssignApproverFrom"></param>
        /// <param name="reAssignApproverTo"></param>
        /// <param name="step"></param>
        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(@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);

            }


            string emailTemplate = "CorrectiveActionReAssigned.txt";
            string userEmail = string.Empty;
            string subject = "Corrective Action Re-Assignment";
            string senderName = "CorrectiveAction";

            subject = "Corrective Action Re-Assignment" + " - Email would be sent to " + email;
            EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
            string[] emailparams = new string[3];
            emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
            emailparams[1] = issueID.ToString();
            emailparams[2] = GlobalVars.hostURL;
            userEmail = email;
            //#if(DEBUG)
            //            userEmail = "rkotian1@irf.com";
            //#endif

            en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="userIDs"></param>
        /// <param name="step"></param>
        /// <param name="docType"></param>
        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(@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);

            }


            string emailTemplate = "CorrectiveActionReAssigned.txt";
            string userEmail = string.Empty;
            string subject = "Corrective Action Re-Assignment";
            string senderName = "CorrectiveAction";

            subject = "Corrective Action Re-Assignment" + " - Email would be sent to " + email;
            EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
            string[] emailparams = new string[3];
            emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
            emailparams[1] = issueID.ToString();
            emailparams[2] = GlobalVars.hostURL;
            userEmail = email;
            //#if(DEBUG)
            //            userEmail = "rkotian1@irf.com";
            //#endif

            en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="currentStep"></param>
        /// <param name="comments"></param>
        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(@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);

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        public void NotifyRejectionToAssignee(int issueID, string comments)
        {

            List<string> emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList();

            string emailTemplate = "CorrectiveActionReject.txt";
            string userEmail = string.Empty;
            string subject = "Corrective Action Rejection";
            string senderName = "CorrectiveAction";

            foreach (string email in emailIst)
            {
                subject = "Corrective Action Rejection";
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = issueID.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = Session[GlobalVars.SESSION_USERNAME].ToString();
                emailparams[4] = comments;
                userEmail = email;
                //#if(DEBUG)
                //    userEmail = "rkotian1@irf.com";
                //#endif

                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
            }

            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Rejection: " + userEmail });
            }
            catch { }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="currentStep"></param>
        /// <param name="comments"></param>
        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(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber);

                //while (lastApprover && !lastStep)
                //{
                //    currentStep++;
                //    //lastApprover = wfDMO.Approve(issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber);
                //    NotifyApprovers(issueID, currentStep);
                //}
                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(@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.ToString());

                string emailTemplate = "CorrectiveActionSectionAssignee.txt";
                //string userEmail = string.Empty;
                string subject = "Corrective Action Assignment";
                string senderName = "CorrectiveAction";

                    subject = "Corrective Action Assignment - Section Approval";
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[4];
                    emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                    emailparams[1] = issueID.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = section;
                //#if(DEBUG)
                //    userEmail = "rkotian1@irf.com";
                //#endif

                en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);

                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(@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
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList();

                string emailTemplate = "CorrectiveActionAssigned.txt";
                string userEmail = string.Empty;
                string subject = "Corrective Action Assignment";
                string senderName = "CorrectiveAction";

                foreach (string email in emailIst)
                {
                    subject = "Corrective Action Assignment - Final Approval";
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[3];
                    emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                    emailparams[1] = issueID.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    userEmail = email;
                    //#if(DEBUG)
                    //    userEmail = "rkotian1@irf.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    emailSentList += email + ",";
                }

                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(@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


        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="step"></param>
        /// <param name="userIDs"></param>
        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(@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);
            }

            string emailTemplate = "CorrectiveActionAssigned.txt";
            string userEmail = string.Empty;
            string subject = "Corrective Action Assignment - Final Approval";
            string senderName = "CorrectiveAction";

            string[] emailIst = emailArray.Split(new char[] { '~' });
            foreach (string email in emailIst)
            {
                if (email.Length > 0)
                {
                    //subject = "Lot Disposition Assignment" + " - Email would be sent to " + email;
                    subject = "Corrective Action Assignment";
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    string[] emailparams = new string[3];
                    emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                    emailparams[1] = issueID.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    userEmail = email;
                    //#if(DEBUG)
                    //    userEmail = "rkotian1@irf.com";
                    //#endif

                    en.SendNotificationEmail(emailTemplate,  GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
                    emailSentList += email + ",";

                }

            }
            try
            {

                EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList });
            }
            catch { }
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="issueID"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step)
        {
            //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request));
            return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.CorrectiveAction).ToDataSourceResult(request));
        }
        public ActionResult GetSectionApprovalLog([DataSourceRequest] DataSourceRequest request, int caNo)
        {
            //return Json(ldDMO.GetApproversList(issueID, step).ToDataSourceResult(request));
            return Json(caDMO.GetCASectionApprovalLog(caNo).ToDataSourceResult(request));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="dueDate"></param>
        /// <param name="responsibleOwnerID"></param>
        public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template)
        {
            try
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                string email = MiscDMO.GetEmail(responsibleOwnerID);

                string emailTemplate = template;
                string userEmail = string.Empty;
                string subject = "Corrective Action Assignment - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = dueDate.ToString();
                emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction);
                emailparams[3] = GlobalVars.hostURL;
                emailparams[4] = issueID.ToString();
                //userEmail = email;

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams);
                emailSentList += 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(@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 });
                //throw e;


            }

        }
        public void NotifyAssignee(int issueID, int? responsibleOwnerID, string template, DateTime? D3DueDate, DateTime? D5D7DueDate)
        {
            try
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                string email = MiscDMO.GetEmail(responsibleOwnerID);

                string emailTemplate = template;
                string userEmail = string.Empty;
                string subject = "CAR Assigned - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                string D3DueDateString = D3DueDate != null ? D3DueDate.ToString() : "N/A";
                string D5D7DueDateString = D5D7DueDate != null ? D5D7DueDate.ToString() : "N/A";

                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[6];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction);
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = issueID.ToString();
                emailparams[4] = D3DueDateString;
                emailparams[5] = D5D7DueDateString;
                //userEmail = email;

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams);
                emailSentList += 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(@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 });
                //throw e;


            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        /// <param name="dueDate"></param>
        /// <param name="responsibleOwnerID"></param>
        public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template)
        {
            try
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                string email = MiscDMO.GetEmail(responsibleOwnerID);

                string emailTemplate = template;
                string userEmail = string.Empty;
                string subject = "Action Item in " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = dueDate.ToString();
                emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction);
                emailparams[3] = GlobalVars.hostURL;
                emailparams[4] = issueID.ToString();
                //userEmail = email;

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams);
                emailSentList += 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(@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 });
                //throw e;


            }

        }
        public void NotifyActionItemCompletion(int issueID, DateTime? dueDate, int? recipientId, string template)
        {
            try
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                string email = MiscDMO.GetEmail(recipientId);

                string emailTemplate = template;
                string userEmail = string.Empty;
                string subject = "8D Action Item Completion - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[5];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = dueDate.ToString();
                emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.CorrectiveAction);
                emailparams[3] = GlobalVars.hostURL;
                emailparams[4] = issueID.ToString();
                //userEmail = email;

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams);
                emailSentList += 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(@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 });
                //throw e;


            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="issueID"></param>
        public void NotifyClosureOf8D(int issueID)
        {
            try
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                List<string> emailIst = MiscDMO.Get8DEmailListForClosureNotification(issueID);


                string emailTemplate = "CorrectiveActionClosed.txt";
                //string userEmail = string.Empty;
                string subject = "Corrective Action Follow Up Closure - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[3];
                foreach (string email in emailIst)
                {
                    emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                    emailparams[1] = GlobalVars.hostURL;
                    emailparams[2] = issueID.ToString();
                    //userEmail = email;

                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams);
                    emailSentList += email + ",";
                }

                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(@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 });
                //throw e;


            }
        }
        public void NotifyCompletionOf8D(int issueID, DateTime? followUpDate)
        {
            try
            {
                string emailSentList = "";

                //List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
                List<string> emailIst = MiscDMO.Get8DEmailListForClosureNotification(issueID);


                string emailTemplate = "CorrectiveActionCompleted.txt";
                //string userEmail = string.Empty;
                string subject = "Corrective Action Completion - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[4];
                foreach (string email in emailIst)
                {
                    emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                    emailparams[1] = GlobalVars.hostURL;
                    emailparams[2] = issueID.ToString();
                    emailparams[3] = followUpDate.ToString();
                    //userEmail = email;

                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, email, null, subject, emailparams);
                    emailSentList += email + ",";
                }

                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(@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 });
                //throw e;


            }
        }
        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;
                //int userID = (int)Session[GlobalVars.SESSION_USERID];
                
                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(@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(@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);
                //return Content(ex.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, dSection);
                NotifySectionRejection(issueID, requestorId, dSection);
                NotifySectionRejection(issueID, qaId, dSection);

                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(@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 userId, string section)
        {
            try
            {
                string userEmail = userDMO.GetUserEmailByID(userId.ToString());

                string emailTemplate = "CorrectiveActionSectionRejection.txt";
                //string userEmail = string.Empty;
                string subject = "Corrective Action Rejection - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                //subject = "Corrective Action Assignment";
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[4];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = issueID.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = section;
                //#if(DEBUG)
                //    userEmail = "rkotian1@irf.com";
                //#endif

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);

                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(@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.ToString());

                string emailTemplate = "CorrectiveActionSectionApproved.txt";
                //string userEmail = string.Empty;
                string subject = "Corrective Action Section Approval - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                //subject = "Corrective Action Assignment";
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[4];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = issueID.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = dSection;
                //#if(DEBUG)
                //    userEmail = "rkotian1@irf.com";
                //#endif

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);

                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(@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.ToString());

                string emailTemplate = "CorrectiveActionSectionApproved.txt";
                //string userEmail = string.Empty;
                string subject = "Corrective Action Section Approval - " + Functions.ReturnCANoStringFormat(issueID);
                string senderName = "CorrectiveAction";

                //subject = "Corrective Action Assignment";
                EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                string[] emailparams = new string[4];
                emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
                emailparams[1] = issueID.ToString();
                emailparams[2] = GlobalVars.hostURL;
                emailparams[3] = dSection;
                //#if(DEBUG)
                //    userEmail = "rkotian1@irf.com";
                //#endif

                en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);

                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(@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
                {
                    string emailTemplate = "D3D5D7Due.txt";
                    //string userEmail = string.Empty;
                    string subject = "Corrective Action " + dueCA.ItemDue + " " + dueCA.ExpiryType + " - " + Functions.ReturnCANoStringFormat(dueCA.CANo);
                    string senderName = "CorrectiveAction";
                    string[] emailparams = new string[7];
                    emailparams[0] = Functions.ReturnCANoStringFormat(dueCA.CANo);
                    emailparams[1] = dueCA.CANo.ToString();
                    emailparams[2] = GlobalVars.hostURL;
                    emailparams[3] = dueCA.ExpiryType;
                    emailparams[4] = dueCA.ItemDue;
                    if (ca.D3DueDate != null)
                    {
                        emailparams[5] = ca.D3DueDate.ToString();
                    }
                    else
                    {
                        emailparams[5] = "N/A";
                    }
                    if(ca.D5D7DueDate != null)
                    {
                        emailparams[6] = ca.D5D7DueDate.ToString();
                    }
                    else
                    {
                        emailparams[6] = "N/A";
                    }
                    
                    //subject = "Corrective Action Assignment";
                    EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
                    en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, user.Email, "jonathan.ouellette@infineon.com", subject, emailparams);
                    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(@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()
        {

        }

    }
}