using LHDN.CRM.BC;
using LHDN.CRM.BC.Common;
using LHDN.CRM.BC.Services;
using LHDN.CRM.Models.ViewModels;
using LHDN.CRM.WebAPI.Filters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Http;
using System.Net.Http;
using System.Net;
using LHDN.CRM.Models.Models;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Net.Http.Headers;
using System.Web.Http.Results;
using Newtonsoft.Json;
using System.Configuration;

namespace LHDN.CRM.WebAPI.Controllers.Api
{
    [ApiErrorHandler]
    public class OutboundApiController : BaseApiController
    {
        private OutboundService svc = new OutboundService();
        private UserProfileService userSvc = new UserProfileService();

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetDropdown(dynamic blnIsHCLEmailBlast)
        {
            return Json(svc.GetDropdown(blnIsHCLEmailBlast));
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetOutboundViewColumns(SearchOutboundPagedListViewModel model)
        {
            return Json(svc.GetOutboundSavedViewColumns(model));
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedSearchOutbound(SearchOutboundPagedListViewModel paging)
        {
            int intCount = 0;
            int intCountNew = 0;
            int intCountVerified = 0;
            int intCountScheduled = 0;

            var lst = svc.SearchOutboundSavedView(paging, out intCount, out intCountNew, out intCountVerified, out intCountScheduled);
            var objRecord = new
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                recordsNew = intCountNew,
                recordsVerified = intCountVerified,
                recordsScheduled = intCountScheduled,

                data = lst,
            };

            return Json(objRecord);

        }

        [HttpGet]
        public IHttpActionResult GetOutboundSegmentise(long id)
        {
            var data = svc.GetOutboundSegmentise(id);

            if (data == null)
                throw new NotFoundException("Segmentise is deleted or not found!");

            DateTime dtNow = DateTime.Now;

            //AuditLogTxn(AuditService.AuditEventID.ViewCaseProfile,
            //    AuditService.ResultType.Success,
            //    AuditService.ActionType.View,
            //    userSvc.LoginID,
            //    dtNow,
            //    "View Segmentise");

            return Json(data);
        }

        [HttpGet]
        public IHttpActionResult GetEmailBlastSegmentise(long id)
        {
            var data = svc.GetEmailBlastSegmentise(id);

            if (data == null)
                throw new NotFoundException("Segmentise is deleted or not found!");

            DateTime dtNow = DateTime.Now;

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdateOutboundSegmentise(OutboundSegmentiseUpdateViewModel model)
        {
            DataTable dTblResult = new DataTable();
            string strLastUpdatedBy = userSvc.LoginID;
            //string strLastUpdatedName = userSvc.DisplayName;
            //string strLastUpdatedEmail = userSvc.Email;
            DateTime dtNow = DateTime.Now;
            string strSegDescription = "";
            string strRefTableName;
            long lngViewID = 0;
            int intCampaignID = 0;
            AuditService.ActionType actionType = new AuditService.ActionType();
            string strText = "";
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.UpdateOutboundSegmentise(model, strLastUpdatedBy, dtNow, out lngViewID, out intCampaignID);

            if (model.OutboundSegmentise.ViewID > 0)
            {
                actionType = AuditService.ActionType.Update;

                if (model.IsHCLEmailBlast == true)
                {
                    strText = "Update Email Blast Segmentise";
                    strSegDescription = string.Format("Email Blast Segmentise " + model.OutboundSegmentise.ViewID + " is updated");
                    strRefTableName = "HCL_EmailView";
                }
                else
                {
                    strText = "Update Outbound Segmentise";
                    strSegDescription = string.Format("Outbound Segmentise " + model.OutboundSegmentise.ViewID + " is updated");
                    strRefTableName = "Outbound_View";
                }

                AuditLogTxn(AuditService.AuditEventID.ManageSegmentisation,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            dtNow,
                            strText,
                            lstAuditDetail,
                            strRefTableName, lngViewID);
            }
            else
            {
                actionType = AuditService.ActionType.Add;

                if (model.IsHCLEmailBlast == true)
                {
                    strText = "Create Email Blast Segmentise";
                    strSegDescription = string.Format("New Email Blast Segmentise is created");
                    strRefTableName = "HCL_EmailView";
                }
                else
                {
                    strText = "Create Outbound Segmentise";
                    strSegDescription = string.Format("New Outbound Segmentise is created");
                    strRefTableName = "Outbound_View";
                }

                AuditLogTxn(AuditService.AuditEventID.ManageSegmentisation,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            dtNow,
                            strText,
                            lstAuditDetail,
                            strRefTableName, lngViewID);
            }

            //Create Campaign 
            if (model.OutboundSegmentise.ViewID > 0 && model.OutboundCampaign != null)
            {
                if (model.OutboundCampaign.CampaignID > 0)
                {
                    actionType = AuditService.ActionType.Update;

                    if (model.IsHCLEmailBlast == true)
                    {
                        strText = "Update Email Blast Campaign";
                        strSegDescription = string.Format("Email Blast Campaign " + model.OutboundCampaign.CampaignID + " is updated");
                        strRefTableName = "HCL_EmailCampaign";
                    }
                    else
                    {
                        strText = "Update Outbound Campaign";
                        strSegDescription = string.Format("Outbound Campaign " + model.OutboundCampaign.CampaignID + " is updated");
                        strRefTableName = "Outbound_Campaign";
                    }

                    AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                                AuditService.ResultType.Success,
                                actionType,
                                userSvc.LoginID,
                                dtNow,
                                strText,
                                lstAuditDetail,
                                strRefTableName, intCampaignID);
                }
                else
                {
                    actionType = AuditService.ActionType.Add;
                    if (model.IsHCLEmailBlast == true)
                    {
                        strText = "Create Email Blast Campaign";
                        strSegDescription = string.Format("New Email Blast Campaign is created");
                        strRefTableName = "HCL_EmailCampaign";
                    }
                    else
                    {
                        strText = "Create Outbound Campaign";
                        strSegDescription = string.Format("New Outbound Campaign is created");
                        strRefTableName = "Outbound_Campaign";
                    }

                    AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                                AuditService.ResultType.Success,
                                actionType,
                                userSvc.LoginID,
                                dtNow,
                                strText,
                                lstAuditDetail,
                                strRefTableName, intCampaignID);
                }
            };

            var result = new
            {
                ViewID = lngViewID,
                CampaignID = intCampaignID
            };

            return Json(result);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetOutboundDetails(OutboundParamViewModel model)
        {
            if (model.JenisKempenID == null || model.DataID == null)
            {
                throw new NotFoundException("Invalid Jenis Kempen ID or Data ID!");
            }

            dynamic data;
            JenisKempenDetailViewModel jenisKempenDetails = new JenisKempenDetailViewModel();
            data = svc.GetOutboundDetails(model);


            AuditLogTxn(AuditService.AuditEventID.ViewOutboundProfile,
                AuditService.ResultType.Success,
                AuditService.ActionType.View,
                userSvc.LoginID,
                DateTime.Now,
                string.Format("Jenis Kempen ID : {0} Data ID : {1}", model.JenisKempenID.ToString(), model.DataID.ToString()));

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdateOutboundDetailsAnsuran(OutboundDetailsAnsuranUpdateViewModel model)
        {
            List<ChangeHistoryUpdateViewModel> data = new List<ChangeHistoryUpdateViewModel>();
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            AuditService.AuditEventID auditEvent = new AuditService.AuditEventID();
            AuditService.ActionType actionType = new AuditService.ActionType();
            List<AuditDetailViewModel> lstAuditDetail = null;
            int intResult = 0;

            model.OutboundDetails.LastUpdatedBy = strLastUpdatedBy;
            model.OutboundDetails.LastUpdatedByName = strLastUpdatedName;
            model.OutboundDetails.LastUpdatedDateTime = DateTime.Now;

            string strOldStatus;
            data = svc.UpdateOutboundDetailsAnsuran(model, out strOldStatus);

            auditEvent = AuditService.AuditEventID.EditOutboundProfile;
            actionType = AuditService.ActionType.Update;
            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditLogTxn(auditEvent,
                        AuditService.ResultType.Success,
                        actionType,
                        userSvc.LoginID,
                        DateTime.Now,
                        string.Format("{0} Data ID: {1} Jenis Kempen ID: {2}", "Update Outbound Profile.", model.OutboundDetails.DataID.ToString(), model.OutboundDetails.JenisKempenID.ToString()),
                        lstAuditDetail,
                        model.OutboundDetails.ReMSTableName,
                        model.OutboundDetails.DataID);

            //if save and verify, to insert verify audit
            if (model.blnIsVerify == true)
            {
                List<ChangeHistoryUpdateViewModel> lst = new List<ChangeHistoryUpdateViewModel>();
                lst.Add(svc.BindChangeHistVM(model.OutboundDetails.DataID, "StatusID", "Status", strOldStatus, Constant.OutboundStatus.Disahkan.ToString(), model.OutboundDetails.JenisKempenID.Value));
                svc.InsertChangeHistory(lst, model.OutboundDetails.LastUpdatedByName, model.OutboundDetails.LastUpdatedBy, model.OutboundDetails.LastUpdatedDateTime);

                lstAuditDetail = lst.Select(a => new AuditDetailViewModel
                {
                    FieldName = a.DisplayName,
                    OldValue = a.OldValue,
                    NewValue = a.NewValue
                }).ToArray().ToList();

                AuditLogTxn(AuditService.AuditEventID.VerifyOutboundList,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            DateTime.Now,
                            string.Format("{0} Data ID: {1} Jenis Kempen ID: {2}", "Verify Outbound Profile.", model.OutboundDetails.DataID.ToString(), model.OutboundDetails.JenisKempenID.ToString()),
                            lstAuditDetail,
                            model.OutboundDetails.ReMSTableName,
                            model.OutboundDetails.DataID);
            }

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdateOutboundDetailsTunggakan(OutboundDetailsTunggakanUpdateViewModel model)
        {
            List<ChangeHistoryUpdateViewModel> data = new List<ChangeHistoryUpdateViewModel>();
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            AuditService.AuditEventID auditEvent = new AuditService.AuditEventID();
            AuditService.ActionType actionType = new AuditService.ActionType();
            List<AuditDetailViewModel> lstAuditDetail = null;
            int intResult = 0;

            model.OutboundDetails.LastUpdatedBy = strLastUpdatedBy;
            model.OutboundDetails.LastUpdatedByName = strLastUpdatedName;
            model.OutboundDetails.LastUpdatedDateTime = DateTime.Now;

            string strOldStatus;
            data = svc.UpdateOutboundDetailsTunggakan(model, out strOldStatus);

            auditEvent = AuditService.AuditEventID.EditOutboundProfile;
            actionType = AuditService.ActionType.Update;
            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditLogTxn(auditEvent,
                        AuditService.ResultType.Success,
                        actionType,
                        userSvc.LoginID,
                        DateTime.Now,
                        string.Format("{0} Data ID: {1} Jenis Kempen ID: {2}", "Update Outbound Profile.", model.OutboundDetails.DataID.ToString(), model.OutboundDetails.JenisKempenID.ToString()),
                        lstAuditDetail,
                        model.OutboundDetails.ReMSTableName,
                        model.OutboundDetails.DataID);

            //if save and verify, to insert verify audit
            if (model.blnIsVerify == true)
            {
                List<ChangeHistoryUpdateViewModel> lst = new List<ChangeHistoryUpdateViewModel>();
                lst.Add(svc.BindChangeHistVM(model.OutboundDetails.DataID, "StatusID", "Status", strOldStatus, Constant.OutboundStatus.Disahkan.ToString(), model.OutboundDetails.JenisKempenID.Value));
                svc.InsertChangeHistory(lst, model.OutboundDetails.LastUpdatedByName, model.OutboundDetails.LastUpdatedBy, model.OutboundDetails.LastUpdatedDateTime);

                lstAuditDetail = lst.Select(a => new AuditDetailViewModel
                {
                    FieldName = a.DisplayName,
                    OldValue = a.OldValue,
                    NewValue = a.NewValue
                }).ToArray().ToList();

                AuditLogTxn(AuditService.AuditEventID.VerifyOutboundList,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            DateTime.Now,
                            string.Format("{0} Data ID: {1} Jenis Kempen ID: {2}", "Verify Outbound Profile.", model.OutboundDetails.DataID.ToString(), model.OutboundDetails.JenisKempenID.ToString()),
                            lstAuditDetail,
                            model.OutboundDetails.ReMSTableName,
                            model.OutboundDetails.DataID);
            }

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdateOutboundDetailsCTL(OutboundDetailsCTLUpdateViewModel model)
        {
            List<ChangeHistoryUpdateViewModel> data = new List<ChangeHistoryUpdateViewModel>();
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            AuditService.AuditEventID auditEvent = new AuditService.AuditEventID();
            AuditService.ActionType actionType = new AuditService.ActionType();
            List<AuditDetailViewModel> lstAuditDetail = null;
            int intResult = 0;

            model.OutboundDetails.LastUpdatedBy = strLastUpdatedBy;
            model.OutboundDetails.LastUpdatedByName = strLastUpdatedName;
            model.OutboundDetails.LastUpdatedDateTime = DateTime.Now;

            string strOldStatus;
            data = svc.UpdateOutboundDetailsCTL(model, out strOldStatus);

            auditEvent = AuditService.AuditEventID.EditOutboundProfile;
            actionType = AuditService.ActionType.Update;
            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditLogTxn(auditEvent,
                        AuditService.ResultType.Success,
                        actionType,
                        userSvc.LoginID,
                        DateTime.Now,
                        string.Format("{0} Data ID: {1} Jenis Kempen ID: {2}", "Update Outbound Profile.", model.OutboundDetails.DataID.ToString(), model.OutboundDetails.JenisKempenID.ToString()),
                        lstAuditDetail,
                        model.OutboundDetails.ReMSTableName,
                        model.OutboundDetails.DataID);

            //if save and verify, to insert verify audit
            if (model.blnIsVerify == true)
            {
                List<ChangeHistoryUpdateViewModel> lst = new List<ChangeHistoryUpdateViewModel>();
                lst.Add(svc.BindChangeHistVM(model.OutboundDetails.DataID, "StatusID", "Status", strOldStatus, Constant.OutboundStatus.Disahkan.ToString(), model.OutboundDetails.JenisKempenID.Value));
                svc.InsertChangeHistory(lst, model.OutboundDetails.LastUpdatedByName, model.OutboundDetails.LastUpdatedBy, model.OutboundDetails.LastUpdatedDateTime);

                lstAuditDetail = lst.Select(a => new AuditDetailViewModel
                {
                    FieldName = a.DisplayName,
                    OldValue = a.OldValue,
                    NewValue = a.NewValue
                }).ToArray().ToList();

                AuditLogTxn(AuditService.AuditEventID.VerifyOutboundList,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            DateTime.Now,
                            string.Format("{0} Data ID: {1} Jenis Kempen ID: {2}", "Verify Outbound Profile.", model.OutboundDetails.DataID.ToString(), model.OutboundDetails.JenisKempenID.ToString()),
                            lstAuditDetail,
                            model.OutboundDetails.ReMSTableName,
                            model.OutboundDetails.DataID);
            }

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetOutboundManualAssigned(OutboundManualAssignedPagedListViewModel paging)
        {
            int intCount = 0;

            var lst = svc.GetOutboundManualAssigned(paging, out intCount);
            DTResultViewModel<OutboundManualAssignedPagedListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<OutboundManualAssignedPagedListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };


            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdatedOCLAgentAssign(OutboundManualAssignedPagedListViewModel paging)
        {
            OutboundUser user = new OutboundUser();
            user.ID = userSvc.LoginID;
            user.Email = userSvc.Email;
            user.DisplayName = userSvc.DisplayName;
            paging.AssignTo = user;
            DateTime dtNow = DateTime.Now;

            var data = svc.UpdatedOCLAgentAssign(user, paging, dtNow);

            return Json(data);
        }

        [HttpPost]
        public IHttpActionResult GetSearchUser(OutboundUser data)
        {
            return Json(svc.GetAllUser(data));
        }

        [HttpPost]
        public IHttpActionResult UpdatedOCLMangerAssign(OutboundManualAssignUpdatedModel data)
        {
            OutboundUser user = new OutboundUser();   //Assign To User
            user.ID = data.OutboundUser.ID;
            user.Email = data.OutboundUser.Email;
            user.DisplayName = data.OutboundUser.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool blnIsRead = false;

            OutboundUser CurrentLoginUser = new OutboundUser();  //Assign By User
            CurrentLoginUser.ID = userSvc.LoginID;
            CurrentLoginUser.DisplayName = userSvc.DisplayName;

            var result = svc.UpdatedOCLMangerAssign(data, user, CurrentLoginUser, dtNow);

            for (int i = 0; i < result.Outbound.Count; i++)
            {
                RecentTaskAlertNotify(user.ID, (short)(Constant.TableType.Outbound), result.Outbound[i].OutboundID, (int)(Constant.MessageType.New), string.Format(Constant.RecentActivity.TaskAlertForOutbound, result.Outbound[i].OutboundID), string.Format(Constant.RecentActivity.OutboundURL, result.Outbound[i].JenisKempenId, result.Outbound[i].ReMSDataID), blnIsRead, CurrentLoginUser.ID, CurrentLoginUser.DisplayName, dtNow);

            }

            return Json(data);
        }

        [HttpPost]
        public IHttpActionResult GetMyPendingOutboundInDashboard(OutboundManualAssignedPagedListViewModel paging)
        {
            int intCount = 0;
            string strUserLogin = userSvc.LoginID;
            var lst = svc.GetMyPendingOutboundInDashboard(strUserLogin, paging, out intCount);
            DTResultViewModel<OutboundManualAssignedPagedListViewModel> objRecord = null;

            objRecord = new DTResultViewModel<OutboundManualAssignedPagedListViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };


            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetAllSegmentiseList(SegmentisePagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetAllSegmentiseList(paging, out intCount);
            DTResultViewModel<SegmentiseListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<SegmentiseListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetAllEmailBlastSegmentiseList(SegmentisePagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetAllEmailBlastSegmentiseList(paging, out intCount);
            DTResultViewModel<SegmentiseListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<SegmentiseListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetAllReMSBatchList(ReMSBatchPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetAllReMSBatchList(paging, out intCount);
            DTResultViewModel<ReMSBatchListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<ReMSBatchListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetAllEmailBlastBatchList(HCLEmailBlastBatchPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetAllEmailBlastBatchList(paging, out intCount);
            DTResultViewModel<HCLEmailBlastBatchListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<HCLEmailBlastBatchListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetReMSDataByBatchID(ReMSDataPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetReMSDataByBatchID(paging, out intCount);
            DTResultViewModel<ReMSDataListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<ReMSDataListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };
            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetEmailBlastDataByBatchID(HCLEmailBlastDataPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetHCLEmailBlastDataByBatchID(paging, out intCount);
            DTResultViewModel<HCLEmailBlastDataListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<HCLEmailBlastDataListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };
            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetInvalidReMSDataByBatchID(ReMSDataPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetInvalidReMSDataByBatchID(paging, out intCount);
            DTResultViewModel<ReMSDataListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<ReMSDataListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };
            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetInvalidEmailBlastDataByBatchID(HCLEmailBlastDataPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetInvalidEmailBlastDataByBatchID(paging, out intCount);
            DTResultViewModel<HCLEmailBlastDataListingViewModel> objRecord = null;

            objRecord = new DTResultViewModel<HCLEmailBlastDataListingViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount,
                recordsFiltered = intCount,
                data = lst
            };
            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetReMSBatchDetailsByBatchID(ReMSDataPagedListViewModel model)
        {
            return Json(svc.GetReMSBatchDetailsByBatchID(model.BatchID, model.JenisKempenID));
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetEmailBlastBatchDetailsByBatchID(HCLEmailBlastDataPagedListViewModel model)
        {
            return Json(svc.GetEmailBlastBatchDetailsByBatchID(model.BatchID, model.JenisKempenID));
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult ReturnReMSBatch(ReMSBatchReturnViewModel model)
        {
            model.ReturnedBy = userSvc.LoginID;
            model.ReturnedByName = userSvc.DisplayName;
            model.ReturnedDateTime = DateTime.Now;
            int intNoOfRecord = 0;

            bool blnIsSuccess = svc.ReturnReMSBatch(model, out intNoOfRecord);

            if (blnIsSuccess)
            {
                AuditLogTxn(AuditService.AuditEventID.ReturnOutboundList,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        "Return Outbound List. Batch ID: " + model.BatchID.ToString(),
                        null,
                        model.JenisKempenName + " Batch",
                        (long)model.BatchID);
            }

            return Json(new { IsSuccess = blnIsSuccess, data = model, noOfRecord = intNoOfRecord });
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult RejectEmailBlastBatch(HCLEmailBlastDataPagedListViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;

            var data = svc.RejectEmailBlastBatch(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now);

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult DeleteSegmentise(OutboundSegmentiseViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteSegmentise(model);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.ManageSegmentisation,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                "Delete Outbound Segmentise. View ID: " + model.ViewID.ToString());

                // Insert Recent Activity
                //RecentActivityTxn("Task", model.TaskID, string.Format(Constant.RecentActivity.TaskDeletedMsg, model.TaskRefNo), strLastUpdatedBy, strLastUpdatedByName, dtNow, string.Format(Constant.RecentActivity.TaskURL, model.TaskID));
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult DeleteEmailBlastSegmentise(OutboundSegmentiseViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteEmailBlastSegmentise(model);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.ManageSegmentisation,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                "Delete Email Blast Segmentise. View ID: " + model.ViewID.ToString());
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult DeleteCampaign(OutboundCampaignViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteCampaign(model);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                "Delete Outbound Campaign. Campaign ID: " + model.CampaignID.ToString());

                // Insert Recent Activity
                //RecentActivityTxn("Task", model.TaskID, string.Format(Constant.RecentActivity.TaskDeletedMsg, model.TaskRefNo), strLastUpdatedBy, strLastUpdatedByName, dtNow, string.Format(Constant.RecentActivity.TaskURL, model.TaskID));
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult DeleteEmailBlastCampaign(OutboundCampaignViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteEmailBlastCampaign(model);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                "Delete Email Blast Campaign. Campaign ID: " + model.CampaignID.ToString());
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedAllOutboundSchedule(OutboundSchedulePagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetAllOutboundSchedule(paging, out intCount);
            DTResultViewModel<OutboundScheduleViewModel> objRecord = null;

            objRecord = new DTResultViewModel<OutboundScheduleViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedAllEmailBlastSchedule(OutboundSchedulePagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetAllEmailBlastSchedule(paging, out intCount);
            DTResultViewModel<OutboundScheduleViewModel> objRecord = null;

            objRecord = new DTResultViewModel<OutboundScheduleViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpGet]
        public IHttpActionResult GetOutboundScheduleByID(int id)
        {
            var data = svc.GetOutboundScheduleByID(id);

            if (data == null)
                throw new NotFoundException("Schedule is deleted or not found!");

            DateTime dtNow = DateTime.Now;

            //AuditLogTxn(AuditService.AuditEventID.ViewCaseProfile,
            //    AuditService.ResultType.Success,
            //    AuditService.ActionType.View,
            //    userSvc.LoginID,
            //    dtNow,
            //    "View Segmentise");

            return Json(data);
        }

        [HttpGet]
        public IHttpActionResult GetEmailBlastScheduleByID(int id)
        {
            var data = svc.GetEmailBlastScheduleByID(id);

            if (data == null)
                throw new NotFoundException("Schedule is deleted or not found!");

            DateTime dtNow = DateTime.Now;

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdateOutboundSchedule(OutboundScheduleUpdateViewModel model)
        {
            DataTable dTblResult = new DataTable();
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            //string strLastUpdatedEmail = userSvc.Email;
            DateTime dtNow = DateTime.Now;
            string strSegDescription = "";
            int intScheduleID = 0;
            DateTime dtScheduleStartDate, dtScheduleEndDate;
            AuditService.ActionType actionType = new AuditService.ActionType();
            string strText = "";
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.UpdateOutboundSchedule(model, strLastUpdatedBy, strLastUpdatedName, dtNow, out intScheduleID, out dtScheduleStartDate, out dtScheduleEndDate);

            if (model.OutboundSchedule.ScheduleID > 0)
            {
                actionType = AuditService.ActionType.Update;
                strText = "Update Outbound Schedule";
                strSegDescription = string.Format("Outbound Schedule " + model.OutboundSchedule.ScheduleID + " is updated");

                svc.AddOutboundSSISTask(model.OutboundSchedule.ScheduleID, model.OutboundCampaign.ViewID, userSvc.LoginID, model.OutboundSchedule.ScheduleStartDate.Value, model.OutboundSchedule.ScheduleExpiryDate.Value, model.IsHCLEmailBlast.Value);

                AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            dtNow,
                            strText,
                            lstAuditDetail,
                            "Update Outbound Schedule. Schedule ID: " + intScheduleID.ToString(), intScheduleID);
            }
            else
            {
                actionType = AuditService.ActionType.Add;
                strText = "Create Outbound Schedule";
                strSegDescription = string.Format("New Outbound Schedule is created");

                //Insert SSIS Process Request
                svc.AddOutboundSSISTask(intScheduleID, model.OutboundCampaign.ViewID, userSvc.LoginID, dtScheduleStartDate, dtScheduleEndDate, model.IsHCLEmailBlast.Value);

                AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                            AuditService.ResultType.Success,
                            actionType,
                            userSvc.LoginID,
                            dtNow,
                            strText,
                            lstAuditDetail,
                            "Create Outbound Schedule. Schedule ID: " + intScheduleID.ToString(), intScheduleID);
            }
            return Json(intScheduleID);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult DeleteSchedule(OutboundScheduleViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteSchedule(model, strLastUpdatedBy, strLastUpdatedByName, dtNow);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                "Delete Outbound Schedule. Schedule ID: " + model.ScheduleID.ToString());

                // Insert Recent Activity
                //RecentActivityTxn("Task", model.TaskID, string.Format(Constant.RecentActivity.TaskDeletedMsg, model.TaskRefNo), strLastUpdatedBy, strLastUpdatedByName, dtNow, string.Format(Constant.RecentActivity.TaskURL, model.TaskID));
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult DeleteEmailBlastSchedule(OutboundScheduleViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            DateTime dtNow = DateTime.Now;
            bool data = svc.DeleteEmailBlastSchedule(model, strLastUpdatedBy, strLastUpdatedByName, dtNow);

            if (data)
            {
                AuditLogTxn(AuditService.AuditEventID.ManageCampaign,
                AuditService.ResultType.Success,
                AuditService.ActionType.Delete,
                userSvc.LoginID,
                dtNow,
                "Delete Email Blast Schedule. Schedule ID: " + model.ScheduleID.ToString());
            }

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedOutboundHistoryListByID(OutboundHistoryPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetOutboundHistoryListByID(paging, out intCount);
            DTResultViewModel<OutboundHistoryViewModel> objRecord = null;

            objRecord = new DTResultViewModel<OutboundHistoryViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedEmailBlastHistoryListByID(OutboundHistoryPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetEmailBlastHistoryListByID(paging, out intCount);
            DTResultViewModel<HCLEmailBlastHistoryViewModel> objRecord = null;

            objRecord = new DTResultViewModel<HCLEmailBlastHistoryViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpGet]
        public IHttpActionResult GetOutboundHistoryByID(long id)
        {
            var data = svc.GetOutboundHistoryByID(id);

            if (data == null)
                throw new NotFoundException("Outbound History not found!");

            return Json(data);
        }

        [HttpGet]
        [CRMAuthorize(Roles = Constant.Authentication.HCL.SearchEmailHistory)]
        public IHttpActionResult GetEmailBlastHistoryByID(long id)
        {
            var data = svc.GetEmailBlastHistoryByID(id);

            if (data == null)
                throw new NotFoundException("Email Blast History not found!");

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedOutboundHistoryDetailListByID(OutboundHistoryDetailPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetOutboundHistoryDetailListByID(paging, out intCount);
            DTResultViewModel<OutboundHistoryDetailViewModel> objRecord = null;

            objRecord = new DTResultViewModel<OutboundHistoryDetailViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult GetPagedEmailBlastHistoryDetailListByID(OutboundHistoryDetailPagedListViewModel paging)
        {
            int intCount = 0;
            var lst = svc.GetEmailBlastHistoryDetailListByID(paging, out intCount);
            DTResultViewModel<HCLEmailBlastHistoryDetailViewModel> objRecord = null;

            objRecord = new DTResultViewModel<HCLEmailBlastHistoryDetailViewModel>()
            {
                draw = paging.Draw,
                recordsTotal = intCount, //data.Count,
                recordsFiltered = intCount, //data.Count,
                data = lst
            };

            return Json(objRecord);
        }

        [HttpPost()]
        [ValidateAjaxRequest]
        public async Task<IHttpActionResult> UploadAttachment()
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                //throw new UnsupportedMediaTypeException( );
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            TempAttachment a = new TempAttachment();
            DateTime dtNow = DateTime.Now;

            if (HttpContext.Current.Request.Files.Count > 0)
            {
                var streamProvider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(streamProvider);
                foreach (HttpContent item in streamProvider.Contents)
                {
                    string strFileName = item.Headers.ContentDisposition.FileName.Replace("\"", String.Empty);
                    byte[] yArrFileContent = item.ReadAsByteArrayAsync().Result;
                    a.FileName = strFileName;
                    a.FileContent = yArrFileContent;
                    a.FileContentType = MimeMapping.GetMimeMapping(strFileName); //Path.GetExtension(strFileName); 
                    a.CreatedDateTime = dtNow;
                }
            }

            if (a.FileContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                && a.FileContentType != "application/vnd.ms-excel"
                )
            {
                return Json(false);
                //throw new UnsupportedMediaTypeException( );
                //throw new UnsupportedFileTypeException();
            }

            return Json(a);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult WriteAttachmentToFolder(HCLEmailBlastUploadParamViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;

            string strDest = AdminService.ParameterSettings.Where(x => x.ParameterID == 9).Select(x => x.ParameterValue).FirstOrDefault();

            if (!Directory.Exists(strDest))
                Directory.CreateDirectory(strDest);

            //string strFileExtension = ".xls";
            int idx = model.AttachmentList[0].FileName.LastIndexOf(".");

            //if (idx > 0)
            //{
            //    strFileExtension = model.AttachmentList[0].FileName.Substring(idx);
            //}

            //model.AttachmentList[0].FileName = "HCLEmailBlast_" + DateTime.Now.ToString("yyyyMMddHHmmss") + strFileExtension;
            File.WriteAllBytes(strDest + "\\" + model.AttachmentList[0].FileName, model.AttachmentList[0].FileContent);

            string strBatchRefNo = svc.InsertEmailBlastBatch(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now);

            return Json(strBatchRefNo);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult LockSegmentiseData(OutboundScheduleUpdateViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            var data = svc.LockSegmentiseData(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now);

            AuditService.AuditEventID auditEventID = model.IsHCLEmailBlast == true ? AuditService.AuditEventID.LockHCLEmailBlastList : AuditService.AuditEventID.LockOutboundList;
            string strDesc = model.IsHCLEmailBlast == true ? string.Format("{0} View ID: {1} Campaign ID: {2}"
                                                                         , "Lock HCL Email Blast List to Schedule."
                                                                         , model.OutboundCampaign.ViewID.ToString()
                                                                         , model.OutboundCampaign.CampaignID.ToString())
                                                           : string.Format("{0} View ID: {1} Campaign ID: {2}"
                                                                         , "Lock Outbound List to Schedule."
                                                                         , model.OutboundCampaign.ViewID.ToString()
                                                                         , model.OutboundCampaign.CampaignID.ToString());

            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc);

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult ReleaseSegmentiseData(OutboundScheduleUpdateViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            var data = svc.ReleaseSegmentiseData(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now);

            AuditService.AuditEventID auditEventID = model.IsHCLEmailBlast == true ? AuditService.AuditEventID.ReleaseHCLEmailBlastList : AuditService.AuditEventID.ReleaseOutboundList;
            string strDesc = model.IsHCLEmailBlast == true ? string.Format("{0} View ID: {1} Campaign ID: {2}"
                                                                         , "Release HCL Email Blast List from Schedule."
                                                                         , model.OutboundCampaign.ViewID.ToString()
                                                                         , model.OutboundCampaign.CampaignID.ToString())
                                                           : string.Format("{0} View ID: {1} Campaign ID: {2}"
                                                                         , "Release Outbound List from Schedule."
                                                                         , model.OutboundCampaign.ViewID.ToString()
                                                                         , model.OutboundCampaign.CampaignID.ToString());

            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc);

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        [CRMAuthorize(Roles = Constant.Authentication.HCL.ViewHCLEmail)]
        public IHttpActionResult GetEmailBlastDetails(OutboundParamViewModel model)
        {
            if (model.JenisKempenID == null || model.DataID == null)
            {
                throw new NotFoundException("Invalid Jenis Kempen ID or Data ID!");
            }

            dynamic data;
            JenisKempenDetailViewModel jenisKempenDetails = new JenisKempenDetailViewModel();
            data = svc.GetEmailBlastDetails(model);


            AuditLogTxn(AuditService.AuditEventID.ViewHCLEmailBlastProfile,
                AuditService.ResultType.Success,
                AuditService.ActionType.View,
                userSvc.LoginID,
                DateTime.Now,
                "View HCL Email Blast Profile");

            return Json(data);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult UpdateEmailBlastDetailsHCL(HCLEmailBlastDetailsUpdateViewModel model)
        {
            List<ChangeHistoryUpdateViewModel> data = new List<ChangeHistoryUpdateViewModel>();
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            AuditService.AuditEventID auditEvent = new AuditService.AuditEventID();
            AuditService.ActionType actionType = new AuditService.ActionType();
            List<AuditDetailViewModel> lstAuditDetail = null;
            int intResult = 0;

            model.EmailBlastDetails.LastUpdatedBy = strLastUpdatedBy;
            model.EmailBlastDetails.LastUpdatedByName = strLastUpdatedName;
            model.EmailBlastDetails.LastUpdatedDateTime = DateTime.Now;

            data = svc.UpdateHCLEmailBlastDetails(model);

            auditEvent = AuditService.AuditEventID.EditHCLEmailBlastProfile;
            actionType = AuditService.ActionType.Update;
            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditLogTxn(auditEvent,
                        AuditService.ResultType.Success,
                        actionType,
                        userSvc.LoginID,
                        DateTime.Now,
                        "Update Email Blast Profile. Data ID:" + data[0].ID.ToString(),
                        lstAuditDetail,
                        "HCL Email Data ",
                        model.EmailBlastDetails.EmailDataID);

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult VerifyEmailBlastData(OutboundParamViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            int intResult = 0;
            DateTime dtNow = DateTime.Now;
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.VerifyEmailBlastData(model, strLastUpdatedBy, strLastUpdatedName, dtNow);

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditLogTxn(AuditService.AuditEventID.VerifyHCLEmailBlastList,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        dtNow,
                        "Verify Email Blast Details. Data ID: " + data[0].ID.ToString(),
                        lstAuditDetail,
                        "HCL_EmailData",
                        model.DataID);

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult RejectEmailBlastData(OutboundParamViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            int intResult = 0;
            DateTime dtNow = DateTime.Now;
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.RejectEmailBlastData(model, strLastUpdatedBy, strLastUpdatedName, dtNow);

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();


            AuditLogTxn(AuditService.AuditEventID.RejectHCLEmailBlastList,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        dtNow,
                        "Reject Email Blast Details. Data ID:" + data[0].ID.ToString(),
                        lstAuditDetail,
                        "HCL_EmailData",
                        model.DataID);

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult VerifyDataByList(OutboundVerifyParamViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            long lngCount;
            var data = svc.VerifyDataByList(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now, out lngCount);
            List<AuditDetailViewModel> lstAuditDetail = null;

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                ID = a.ID,
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditService.AuditEventID auditEventID = model.IsHCLEmailBlast == true ? AuditService.AuditEventID.VerifyHCLEmailBlastList : AuditService.AuditEventID.VerifyOutboundList;
            string strTableName = model.IsHCLEmailBlast == true ? "HCL_EmailData"
                                                                : "ReMS_" + ((Constant.JenisKempen)model.JenisKempenID).ToString();

            //for (int i = 0; i < lstAuditDetail.Count; i++)
            //{
            //    string strDesc = model.IsHCLEmailBlast == true ? string.Format("{0} Data ID: {1} Select All: {2}", "Verify HCL Email Blast.", lstAuditDetail[i].ID.ToString(), model.IsSelectAll.ToString())
            //                                                   : string.Format("{0} Data ID: {1} Select All: {2}", "Verify Outbound.", lstAuditDetail[i].ID.ToString(), model.IsSelectAll.ToString());
            //    AuditLogTxn(auditEventID,
            //                AuditService.ResultType.Success,
            //                AuditService.ActionType.Update,
            //                userSvc.LoginID,
            //                DateTime.Now,
            //                strDesc,
            //                lstAuditDetail.Where(x => x.ID == lstAuditDetail[i].ID).ToList(),
            //                strTableName,
            //                lstAuditDetail[i].ID);
            //}

            string strDesc = model.IsHCLEmailBlast == true ? string.Format("{0} Select All: {1} Jenis Kempen ID: {2}", "Verify HCL Email Blast.", model.IsSelectAll.ToString(), model.JenisKempenID.ToString())
                                                           : string.Format("{0} Select All: {1} Jenis Kempen ID: {2}", "Verify Outbound.", model.IsSelectAll.ToString(), model.JenisKempenID.ToString());
            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc, null, strTableName, 0);

            return Json(lngCount);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult VerifyOutboundDataByBatch(ReMSDataPagedListViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            long lngCount;
            var data = svc.VerifyOutboundDataByBatch(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now, out lngCount);
            List<AuditDetailViewModel> lstAuditDetail = null;

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                ID = a.ID,
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditService.AuditEventID auditEventID = AuditService.AuditEventID.VerifyOutboundList;
            string strTableName = "ReMS_" + ((Constant.JenisKempen)model.JenisKempenID).ToString() + "Batch";

            //for (int i = 0; i < lstAuditDetail.Count; i++)
            //{
            //    string strDesc = string.Format("{0} Batch ID: {1} Data ID: {2}", "Verify Outbound by Batch.", model.BatchID.ToString(), lstAuditDetail[i].ID.ToString());
            //    AuditLogTxn(auditEventID,
            //                AuditService.ResultType.Success,
            //                AuditService.ActionType.Update,
            //                userSvc.LoginID,
            //                DateTime.Now,
            //                strDesc,
            //                lstAuditDetail.Where(x => x.ID == lstAuditDetail[i].ID).ToList(),
            //                strTableName,
            //                lstAuditDetail[i].ID);
            //}

            string strDesc = string.Format("{0} Batch ID: {1}", "Verify Outbound by Batch.", model.BatchID.ToString());

            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc, null, strTableName, model.BatchID);

            return Json(lngCount);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult VerifyEmailBlastDataByBatch(HCLEmailBlastDataPagedListViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            long lngCount;
            var data = svc.VerifyEmailBlastDataByBatch(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now, out lngCount);
            List<AuditDetailViewModel> lstAuditDetail = null;

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                ID = a.ID,
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            AuditService.AuditEventID auditEventID = AuditService.AuditEventID.VerifyHCLEmailBlastList;
            string strTableName = "HCL_EmailBatch";

            //for (int i = 0; i < lstAuditDetail.Count; i++)
            //{
            //    string strDesc = string.Format("{0} Batch ID: {1} Data ID: {2}", "Verify HCL Email Blast by Batch.", model.BatchID.ToString(), lstAuditDetail[i].ID.ToString());
            //    AuditLogTxn(auditEventID,
            //                AuditService.ResultType.Success,
            //                AuditService.ActionType.Update,
            //                userSvc.LoginID,
            //                DateTime.Now,
            //                strDesc,
            //                lstAuditDetail.Where(x => x.ID == lstAuditDetail[i].ID).ToList(),
            //                strTableName,
            //                lstAuditDetail[i].ID);
            //}

            string strDesc = string.Format("{0} Batch ID: {1}", "Verify HCL Email Blast by Batch.", model.BatchID.ToString());

            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc, null, strTableName, model.BatchID);

            return Json(lngCount);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult RejectOutboundData(OutboundParamViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            int intResult = 0;
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.RejectOutboundData(model, strLastUpdatedBy, strLastUpdatedName, DateTime.Now);

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            string strTableName = "ReMS_" + ((Constant.JenisKempen)model.JenisKempenID).ToString();

            AuditLogTxn(AuditService.AuditEventID.ReturnOutboundList,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        "Return Data to ReMS. Data ID:" + data[0].ID.ToString(),
                        lstAuditDetail,
                        strTableName,
                        model.DataID);

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult VerifyOutboundData(OutboundParamViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedName = userSvc.DisplayName;
            int intResult = 0;
            List<AuditDetailViewModel> lstAuditDetail = null;

            var data = svc.VerifyOutboundData(model, strLastUpdatedBy, strLastUpdatedName, DateTime.Now);

            lstAuditDetail = data.Select(a => new AuditDetailViewModel
            {
                FieldName = a.DisplayName,
                OldValue = a.OldValue,
                NewValue = a.NewValue
            }).ToArray().ToList();

            string strTableName = "ReMS_" + ((Constant.JenisKempen)model.JenisKempenID).ToString();

            AuditLogTxn(AuditService.AuditEventID.VerifyOutboundList,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                         DateTime.Now,
                        "Verify Outbound Details. Data ID: " + data[0].ID.ToString(),
                        lstAuditDetail,
                        strTableName,
                        model.DataID);

            return Json(intResult);
        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult SendTestingEmail(EmailTestingViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            int intScheduleID = 0;
            DateTime dtScheduleStartDate, dtScheduleEndDate;
            string strEmail;
            var data = svc.SendTestingEmail(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now, out intScheduleID, out dtScheduleStartDate, out dtScheduleEndDate, out strEmail);

            svc.AddOutboundSSISTask(intScheduleID, model.ViewID, userSvc.LoginID, dtScheduleStartDate, dtScheduleEndDate, model.IsHCLEmailBlast);

            AuditService.AuditEventID auditEventID = model.IsHCLEmailBlast == true ? AuditService.AuditEventID.ManageHCLEmailBlastCampaign : AuditService.AuditEventID.ManageCampaign;
            string strDesc = model.IsHCLEmailBlast == true ? string.Format("{0} Campaign ID: {1}"
                                                                         , "Send HCL Testing Email."
                                                                         , model.CampaignID.ToString())
                                                           : string.Format("{0} Campaign ID: {1}"
                                                                         , "Send HRCC Testing Email."
                                                                         , model.CampaignID.ToString());

            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc);

            return Json(data);


        }

        [HttpPost]
        [ValidateAjaxRequest]
        public IHttpActionResult CancelCampaignByID(OutboundCancelCampaignViewModel model)
        {
            string strLastUpdatedBy = userSvc.LoginID;
            string strLastUpdatedByName = userSvc.DisplayName;
            var data = svc.CancelCampaignByID(model, strLastUpdatedBy, strLastUpdatedByName, DateTime.Now);

            AuditService.AuditEventID auditEventID = model.IsHCLEmailBlast == true ? AuditService.AuditEventID.ManageHCLEmailBlastCampaign : AuditService.AuditEventID.ManageCampaign;
            string strDesc = model.IsHCLEmailBlast == true ? string.Format("{0} Campaign ID: {1} His ID: {2}"
                                                                         , "Cancel HCL Email Blast Campaign."
                                                                         , model.CampaignID.ToString()
                                                                         , model.HisID.ToString())
                                                           : string.Format("{0} Campaign ID: {1} His ID: {2}"
                                                                         , "Cancel Outbound Campaign."
                                                                         , model.CampaignID.ToString()
                                                                         , model.HisID.ToString());

            AuditLogTxn(auditEventID,
                        AuditService.ResultType.Success,
                        AuditService.ActionType.Update,
                        userSvc.LoginID,
                        DateTime.Now,
                        strDesc);

            return Json(data);
        }

        [HttpPost]
        public IHttpActionResult ExportExcelOutboundListing(ExportToExcelViewModel vm)
        {
            SearchOutboundPagedListViewModel paging = new SearchOutboundPagedListViewModel();
            paging = JsonConvert.DeserializeObject<SearchOutboundPagedListViewModel>(vm.strJSON);
            paging.Length = Convert.ToInt32(AdminService.ParameterSettings.Where(x => x.ParameterID == 22).FirstOrDefault().ParameterValue);

            byte[] bytFileContent = null;
            bytFileContent = svc.ExportExcelOutboundListing(paging);

            ResponseMessageResult responseMessageResult = null;
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(bytFileContent)
            };

            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = paging.IsHCLEmailBlast == true ?
                            "CarianHCLEmail_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"
                            : "CarianOutbound_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"
            };

            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            responseMessageResult = ResponseMessage(httpResponseMessage);

            return responseMessageResult;
        }

        [HttpPost]
        public IHttpActionResult ExportExcelOutboundSegmentise(ExportToExcelViewModel vm)
        {
            SearchOutboundPagedListViewModel paging = new SearchOutboundPagedListViewModel();
            paging = JsonConvert.DeserializeObject<SearchOutboundPagedListViewModel>(vm.strJSON);
            paging.Length = Convert.ToInt32(AdminService.ParameterSettings.Where(x => x.ParameterID == 22).FirstOrDefault().ParameterValue);

            byte[] bytFileContent = null;
            bytFileContent = svc.ExportExcelOutboundListing(paging);

            ResponseMessageResult responseMessageResult = null;
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(bytFileContent)
            };

            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = paging.IsHCLEmailBlast == true ?
                            "SegmenHCLEmail_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"
                            : "SegmenOutbound_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"
            };

            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            responseMessageResult = ResponseMessage(httpResponseMessage);

            return responseMessageResult;
        }
    }
}