// Check session in page initia stage
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                if ((Session["AuthenticatedUser"] != null))// || (Session["loanStep"] != null)
                 {    
                    userData = ((User)Session["AuthenticatedUser"]);
                    if (Session["loanStep"] != null)
                    {
                        
                        loanData = ((LoanSetupStep)Session["loanStep"]);
                        Session["companyStep"] = 5;

                        if(loanData.loanId > 0)
                        {
                            loanstep = loanData.stepId;
                            CurtailmentAccess curtailmentAccess = new CurtailmentAccess();

                           
                            _loan = curtailmentAccess.GetLoanDetailsByLoanId(loanData.loanId);
                            
                            Session["isInterest"] = _loan.isInterestCalculate;
                        }
                        else if (loanData.loanId == 0)
                        {
                            loanstep = 1;
                            //CurtailmentAccess curtailmentAccess = new CurtailmentAccess();


                            // _loan = curtailmentAccess.GetLoanDetailsByLoanId(loanData.loanId);

                            // Session["isInterest"] = _loan.isInterestCalculate;
                        }
                    }
                }
                else
                {
                    if (HttpContext.Request.IsAjaxRequest())
                    {
                        filterContext.Result = new HttpStatusCodeResult(404, "Due to inactivity your session has timed out, please log in again.");
                    }
                    else
                    {

                        filterContext.Result = new RedirectResult("/Login/UserLogin?lbl=Due to inactivity your session has timed out, please log in again.");
                    }
                }
            }
            catch
            {
                filterContext.Result = new RedirectResult("~/Exceptions/Index");
            }
        }
        public void RenderReport(int loanId)
        {
            //check authentication session is null, if null return
            if (Session["AuthenticatedUser"] == null) return;
            User userData = (User)Session["AuthenticatedUser"];

            //set reportviewr properties
            rptViewerLoanTerms.ProcessingMode = ProcessingMode.Local;
            rptViewerLoanTerms.Reset();
            rptViewerLoanTerms.LocalReport.EnableExternalImages = true;
            rptViewerLoanTerms.LocalReport.ReportPath = Server.MapPath("~/Reports/RptLoanTerms.rdlc");
            rptViewerLoanTerms.ZoomMode = ZoomMode.PageWidth;

            ReportAccess ra = new ReportAccess();

            //Get loan details and set to reportviwer
            List<RptLoanTerms> loanTermsDetails = ra.RptLoanTermsDetails(loanId);
            rptViewerLoanTerms.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", loanTermsDetails));

            List<LoanDetailsRpt> details = ra.GetLoanDetailsRptforCompanySummary(userData.Company_Id, userData.UserId);
            rptViewerLoanTerms.LocalReport.DataSources.Add(new ReportDataSource("DataSet6", details));

            //get curtailment schedule details and set to reportviwer
            CurtailmentAccess ca = new CurtailmentAccess();
            List<Curtailment> curtailments = ca.retreiveCurtailmentByLoanId(loanId);

            if (curtailments != null && curtailments.Count > 0)
            {
                for (int i = 0; i < curtailments.Count; i++)
                {
                    curtailments[i].CurtailmentId = i + 1;
                }
            }
            rptViewerLoanTerms.LocalReport.DataSources.Add(new ReportDataSource("DataSet2", curtailments));

            //get fees details and set to reportviwer
            List<RptFeeLoanTerm> loanTermsFeeDetails = ra.RptLoanTermsFeeDetails(loanId);
            rptViewerLoanTerms.LocalReport.DataSources.Add(new ReportDataSource("DataSet3", loanTermsFeeDetails));

            //get reminders details and set to reportviwer
            List<RptEmailReminder> loanTermsEmailReminders = ra.RptLoanTermsEmailReminders(loanId);
            rptViewerLoanTerms.LocalReport.DataSources.Add(new ReportDataSource("DataSet4", loanTermsEmailReminders));

            //get unit types and set  to reportviwer
            IList<UnitType> unitTypes = ra.RptGetUnitTypes(loanId);
            rptViewerLoanTerms.LocalReport.DataSources.Add(new ReportDataSource("DataSet5", unitTypes));
        }
        /// <summary>
        /// CreatedBy : Nadeeka
        /// CreatedDate: 2016/03/15
        /// 
        /// Get loan curtailment schedule by calling StepAccess class method, and creating curtailment date using that values
        /// 
        /// </summary>
        /// <param name="loanId"></param>
        public bool GetLoanCurtailmentDetails(int loanId, string unitId, DateTime advaceDate, decimal advanceAmount, decimal cost)
        {
            try
            {
                StepAccess stepAccess = new StepAccess();
            LoanSetupStep1 loan = stepAccess.GetLoanCurtailmentBreakdown(loanId);
            Int32 curtailmentNo = 1;
            //bool isEditAdvanceAmount = false;
            //isEditAdvanceAmount = ((cost * loan.advancePercentage) / 100) == advanceAmount ? false : true;
            foreach (Curtailment curtailment in loan.curtailmetList)
            {
                curtailment.CurtailmentId = curtailmentNo;
                //check pay off period as days or month               
                curtailment.CurtailmentDate = loan.payOffPeriodType == 0 ? (advaceDate.AddDays(Convert.ToDouble(curtailment.TimePeriod))) : advaceDate.AddMonths(curtailment.TimePeriod ?? 0);
                if (loan.CurtailmentCalculationBase == "f")
                { 
                    if (loan.curtailmetList.Count==curtailmentNo)
                    {
                        curtailment.Amount = Math.Round(advanceAmount - GetCurtailmentCurrentTotal(loan.curtailmetList),2);
                    }
                    else
                    {
                        curtailment.Amount = Math.Round(this.CalculateAdditionalPercentage(advanceAmount, curtailment.Percentage, loan.advancePercentage), 2);
                    }
                }
                else if (loan.CurtailmentCalculationBase == "a")
                {
                    if (loan.curtailmetList.Count == curtailmentNo)
                    {
                        curtailment.Amount = Math.Round(advanceAmount - GetCurtailmentCurrentTotal(loan.curtailmetList), 2);
                    }
                    else
                    {
                        curtailment.Amount = Math.Round((advanceAmount * curtailment.Percentage ?? 0) / 100, 2);
                    }                   
                }
                curtailmentNo++;
            }

           
                XElement xEle = new XElement("Curtailments",
                    from curtailment in loan.curtailmetList
                    select new XElement("Curtailment",
                        new XElement("LoanId", loanId),
                        new XElement("UnitId", unitId),
                        new XElement("CurtNo", curtailment.CurtailmentId),
                        new XElement("CurtAmount", curtailment.Amount),
                        new XElement("CurtDueDate", curtailment.CurtailmentDate),
                        new XElement("CurtStatus", 0)
                        ));
                string xmlDoc = xEle.ToString();
                CurtailmentAccess curtailmentAccess = new CurtailmentAccess();
                return curtailmentAccess.InsertCurtailmentScheduleInfo(xmlDoc, unitId, loanId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ActionResult loadGrid()
        {
            string loanCode;

            try
            {
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                //filterContext.Controller.TempData.Add("UserLogin", "Login");
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }          

            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);



            BranchAccess ba = new BranchAccess();
            ViewBag.ComType = userData.CompanyType;
            ViewBag.loanId = loanDetails.loanId;
            ViewBag.loanDetails = loanDetails;

            UnitPayOffViewModel unitPayOffViewModel = new UnitPayOffViewModel();
            CurtailmentAccess payoff = new CurtailmentAccess();
            unitPayOffViewModel.UnitPayOffList = new List<UnitPayOffModel>();
            unitPayOffViewModel.PayDate = DateTime.Now;

            unitPayOffViewModel.UnitPayOffList = payoff.GetUnitPayOffList(loanDetails.loanId);

            decimal advanceFee = 0;
            advanceFee = payoff.AdvanceForPayOffUnits(loanDetails.loanId);

            //int advanceFeeAtPayoff = payoff.CheckAdvanceFeeAtPayOff(loanDetails.loanId);

            //if (advanceFeeAtPayoff == 1) {
            //    foreach (var unit in unitPayOffViewModel.UnitPayOffList) {
            //        unit.IsAdvancePaid = false;
            //    }
            //}
            ViewBag.AdvanceFee = advanceFee;

            var unitPayOffList = unitPayOffViewModel.UnitPayOffList;

            Session["payoffList"] = unitPayOffList;
            ViewBag.payOffList = unitPayOffList;

            TitleAccess ta = new TitleAccess();
            Title title = ta.getTitleDetails(loanDetails.loanId);

            Session["PayOffUnitloanId"] = loanDetails.loanId;

            if (title != null)
            {
                bool isTitleTrack = title.IsTitleTrack;
                if (isTitleTrack)
                    ViewBag.IsTitleTrack = "Yes";

            }

            return PartialView(unitPayOffViewModel);
        }
        public string PayCurtailments(SelectedCurtailmentList selectedCurtailmentList, string needSend, string dealerEmail, string dueDate)
        {
            // if session expired -- return null 
            if (Session["loanCode"] == null || Session["loanCode"].ToString() == "")
                return null;

            var loanCode = Session["loanCode"].ToString(); // take loan code from session 
            string paidDate = "";

            var loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode); // take loan details of the loan code

            CurtailmentAccess curtailmentAccess = new CurtailmentAccess();
            string returnValue = curtailmentAccess.updateCurtailmets(selectedCurtailmentList, loanDetails.loanId, dealerEmail); // update curtailment details as paid


            // if curtailment successfully updated
            if (returnValue != null)
            {
                // saving for reporting purpose
                decimal totalpaid = 0.00M;
                List<CurtailmentShedule> selectedCurtailmentSchedules = selectedCurtailmentList.SelectedCurtailmentSchedules;
                foreach (var items in selectedCurtailmentSchedules)
                {
                    items.PaidDate = items.PayDate.ToString("MM/dd/yyyy");
                    totalpaid += items.CurtAmount;
                    paidDate = items.PaidDate;
                }

                foreach (var items in selectedCurtailmentSchedules)
                {
                    items.TotalAmountPaid = totalpaid;
                }

                Session["CurtUnitDuringSession"] = selectedCurtailmentSchedules;
                if (needSend == "Yes")
                {
                    ReportViewer rptViewerCurtailmentReceiptDuringSession = new ReportViewer();
                    rptViewerCurtailmentReceiptDuringSession.ProcessingMode = ProcessingMode.Local;
                    rptViewerCurtailmentReceiptDuringSession.Reset();
                    rptViewerCurtailmentReceiptDuringSession.LocalReport.EnableExternalImages = true;
                    rptViewerCurtailmentReceiptDuringSession.LocalReport.ReportPath = Server.MapPath("~/Reports/RptCurtailmentDuringSession.rdlc");

                    ReportAccess ra = new ReportAccess();
                    List<LoanDetailsRpt> details = ra.TopHeaderDetails(loanDetails.loanId, userData.UserId);

                    foreach (var dates in details)
                    {
                        dates.ReportDate = DateTime.Now.ToString("MM/dd/yyyy");
                    }

                    rptViewerCurtailmentReceiptDuringSession.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", details));

                    if (selectedCurtailmentSchedules != null && selectedCurtailmentSchedules.Count > 0)
                    {
                        try
                        {
                            rptViewerCurtailmentReceiptDuringSession.LocalReport.DataSources.Add(new ReportDataSource("DataSet2", selectedCurtailmentSchedules));

                            Warning[] warnings;
                            string[] streamids;
                            string mimeType;
                            string encoding;
                            string filenameExtension;

                            //create pdf file
                            byte[] bytes = rptViewerCurtailmentReceiptDuringSession.LocalReport.Render(
                                "PDF", null, out mimeType, out encoding, out filenameExtension,
                                out streamids, out warnings);

                            if (dealerEmail != "")
                            {
                                string mailSubject = "Curtailment Paid Receipt - Loan " + loanDetails.loanNumber;
                                string mailBody =
                                    "Curtailments for Loan " + loanDetails.loanNumber + " which were due on or before " + dueDate  + " have been paid on " + paidDate + ". " +
                                    "Please view the attached PDF file for full curtailment payment details. " +
                                    Environment.NewLine + Environment.NewLine +
                                    "Thank you," +
                                    Environment.NewLine +
                                    "Dealer Floor Plan Software Team";

                                Thread thread = new Thread(delegate ()
                                {
                                    Email email = new Email(dealerEmail);
                                    email.SendMailWithAttachment(mailSubject, mailBody, bytes);
                                });

                                thread.IsBackground = true;
                                thread.Start();

                            }

                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
                    }
                }

                //insert to log
                string[] arrList = new string[selectedCurtailmentList.SelectedCurtailmentSchedules.Count];
                int i = 0;
                // add all paid curtailment details to array
                foreach (var x in selectedCurtailmentList.SelectedCurtailmentSchedules)
                {
                    if (!string.IsNullOrEmpty(x.UnitId))
                    {
                        arrList[i] = "Pay Curtailment(s) for unit(s): " + x.IDNumber + " ,Curtailment No: " + x.CurtNumber + " ,Curtailment Amount:" + x.CurtAmount + " ,Paid Date:" + x.PayDate;
                        i++;
                    }
                }

                // join the array with comma seperated
                string units = string.Join(",", arrList);
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanDetails.loanId, "Pay Curtailments", units, DateTime.Now);
                // insert into log
                int islog = (new LogAccess()).InsertLog(log);
            }
            // return the value
            return returnValue;
        }
        /*

 Frontend page: Curtailment Page
 Title: Curtailments by selected due date
 Designed: Nadeeka
 User story: 
 Developed: Nadeeka
 Date created: 3/21/2016

*/
        public ActionResult PayCurtailmentForSelectedDueDate(DateTime dueDate)
        {
            CurtailmentScheduleModel curtailmentScheduleModel = new CurtailmentScheduleModel();
            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(Session["loanCode"].ToString()); // take loan details of selected loan
            ViewBag.loanDetails = loanDetails;

            string f = dueDate.ToShortDateString();
            DateTime dd = Convert.ToDateTime(f);


            CurtailmentAccess curtailmentAccess = new CurtailmentAccess();
            List<CurtailmentShedule> curtailmentSchedule = curtailmentAccess.GetCurtailmentScheduleByDueDate(loanDetails.loanId, dd);  // get curtailment list by due date
            ViewBag.DealerEmail = (string)Session["DealerEmail"]; // pass dealer email to the view
            ViewBag.LoanId = loanDetails.loanId;  // pass loan id to the view

            curtailmentScheduleModel.CurtailmentScheduleInfoModel = new List<CurtailmentShedule>();
            curtailmentScheduleModel.CurtailmentScheduleInfoModel.AddRange(curtailmentSchedule); // bind the list of curtailment to model
            curtailmentScheduleModel.DueDate = dueDate; // bind the due date to model

            // return the partial view page
            return PartialView(curtailmentScheduleModel);
        }
        public ActionResult AddCurtailment(List<Curtailment> curtailmentList, CurtailmentModel curtaiulmentModel)
        {
            //calculate payment percentage
            if (userData.RoleId >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }

            CurtailmentAccess curtailmentAccess = new CurtailmentAccess();
            StepAccess sa = new StepAccess();
            if (curtailmentAccess.InsertCurtailment(curtailmentList, loanData.loanId) > 0)
            {
                ViewBag.SuccessMsg = "Curtailment Details added successfully";
                sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 6);
               
                    Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, loanData.loanId, "Curtailment", "Inserted curtailment details of loan : " + loanData.loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);

                ViewBag.Redirect = 1;
            }
            else
            {
                sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 6);
                
                    Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, loanData.loanId, "Curtailment", "Edited curtailment details of loan : " + loanData.loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
               
                ViewBag.SuccessMsg = "Curtailment Details updated successfully";
            }

            //bool loanActive = curtaiulmentModel.LoanStatus == "Yes";

            LoanSetupAccess loanAccess = new LoanSetupAccess();
            loanAccess.UpdateLoanCurtailment(curtaiulmentModel, loanData.loanId);
            TempData["LoanId"] = loanData.loanId;
            return RedirectToAction("Step10", new { lbl = "Details added successfully" });
        }
        public ActionResult Step10(string lbl)
        {
            CurtailmentModel curtailment = new CurtailmentModel();

            int userId = userData.UserId;
            if (userData.RoleId >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }

            //check user step is valid for this step
            StepAccess sa = new StepAccess();
            if (loanData.stepId == 5)
            {
                ViewBag.LoanId = 0;
                if (lbl == "Details added successfully")
                {
                    ViewBag.SuccessMsg = "Loan setup is completed";
                    Session["loanStep"] = null;
                    if (TempData["LoanId"] != null && (int)TempData["LoanId"] > 0) {
                        ViewBag.LoanId = (int)TempData["LoanId"];
                    }
                   
                    if (HttpContext.Request.IsAjaxRequest())
                    {
                        ViewBag.AjaxRequest = 1;
                        return PartialView(curtailment);
                    }
                    return View(curtailment);
                }

                int branchId = loanData.BranchId;

                LoanSetupAccess la = new LoanSetupAccess();
                int loanId = loanData.loanId;
                CurtailmentAccess curAccess = new CurtailmentAccess();
                _loan = curAccess.GetLoanDetailsByLoanId(loanId);
                _loan.loanId = loanId;
                
                curtailment.AdvancePt = _loan.advancePercentage;
                curtailment.RemainingPercentage = curtailment.AdvancePt;

                curtailment.InfoModel = new List<Curtailment>();

                var curtailments = curAccess.retreiveCurtailmentByLoanId(loanId);

                int payPercentage = _loan.advancePercentage;
                int? totalPercentage = 0;

                int curId = 0;
                if (curtailments != null && curtailments.Count > 0)
                {
                    for (int i = 0; i < curtailments.Count; i++)
                    {
                        curId++;
                        totalPercentage += curtailments[i].Percentage;
                        curtailment.InfoModel.Add(new Curtailment { CurtailmentId = curId, TimePeriod = curtailments[i].TimePeriod, Percentage = curtailments[i].Percentage });
                    }
                    curtailment.LoanStatus = _loan.LoanStatus ? "Yes" : "No";

                    curtailment.CalculationBase = _loan.CurtailmentCalculationBase == "a" ? "Advance" : "Full payment";
                    curtailment.DueDate = _loan.CurtailmentDueDate;
                    curtailment.AutoRemindEmail = _loan.CurtailmentAutoRemindEmail;
                    curtailment.EmailRemindPeriod = _loan.CurtailmentEmailRemindPeriod;
                }

                ViewBag.CalMode = "Full Payment";
                curtailment.RemainingPercentage = payPercentage - totalPercentage;

                if (curtailment.RemainingPercentage > 0)
                    curtailment.InfoModel.Add(new Curtailment { CurtailmentId = curId + 1 });
                ViewData["objmodel"] = curtailment;

                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(curtailment);
                }
                else
                {

                    return View(curtailment);
                }
            }
            return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
        }