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 ActionResult Step9(Title title)
        {
            int userId = userData.UserId;
            int branchId = loanData.BranchId;
            //check user is user or dealer user
            if (userData.RoleId >= 3)
            {
                //return to login page
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
         
            TitleAccess ta = new TitleAccess();
            LoanSetupAccess la = new LoanSetupAccess();
            StepAccess sa = new StepAccess();
          
            int loanId = loanData.loanId;
            title.LoanId = loanId;

            if (title.ReceivedTimeLimit == "1")
            {
                title.ReceivedTimeLimit = "Title required to advance";
            }
            else if (title.ReceivedTimeLimit == "2")
            {
                title.ReceivedTimeLimit = "Title can arrive at any time";
            }
            else if (title.ReceivedTimeLimit == "3")
            {
                title.ReceivedTimeLimit = "Title must arrive within a specified time";
            }

            if (title.ReceiptRequiredMethod == "1")
            {
                title.ReceiptRequiredMethod = "Must be physically present";
            }
            else if (title.ReceiptRequiredMethod == "2")
            {
                title.ReceiptRequiredMethod = "Scanned copy only";
            }
            else if (title.ReceiptRequiredMethod == "3")
            {
                title.ReceiptRequiredMethod = "Physically present or scanned copy";
            }
            //insert or update title details and get result
            int reslt = ta.insertTitleDetails(title);
            //check result is not 0
            if (reslt >= 0)
            {
                //update loan setup step table
                if (sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanData.BranchId, loanData.nonRegisteredBranchId, loanData.loanId, 5))
                {
                    //check current step value of loanData object is less than 5
                    if (loanData.stepId < 5)
                    {
                        //update step
                        loanData.stepId = 5;
                    }
                    //if title update or insert result is 0
                    if (reslt == 0)
                    {
                        //insert record in to log table as insert
                        Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, title.LoanId, "Title", "Edited title details of loan : " + title.LoanId, DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                    }
                    if (reslt > 0)
                    {
                        //insert record in to log table as update
                        Log log = new Log(userData.UserId, userData.Company_Id, loanData.BranchId, title.LoanId, "Title", "Inserted title details of loan : " + title.LoanId, DateTime.Now);

                        int islog = (new LogAccess()).InsertLog(log);
                    }
                    //convert loan data object to session variable
                    Session["loanStep"] = loanData;
                    //return to curtailment page
                    return RedirectToAction("Step10");
                }
                //if update loan setup step result is false return to login page
                else
                {
                    return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
                }
            }
           
            else
            {
                return new HttpStatusCodeResult(404);
            }
            
        }
        public ActionResult Step9(int? edit)
        {
            int uId = userData.UserId;
            int branchId = loanData.BranchId;
            //check user is user or dealer user
            if (userData.RoleId >= 3)
            {
                //return to login
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
            //yes no list
            List<SelectListItem> isTitleTrackList = new List<SelectListItem>();

            isTitleTrackList.Add(new SelectListItem
            {
                Text = "Yes",
                Value = "true"
            });
            isTitleTrackList.Add(new SelectListItem
            {
                Text = "No",
                Value = "false"
            });
            ViewBag.isTitleTrack = new SelectList(isTitleTrackList, "Value", "Text");

            List<SelectListItem> isReceiptList = new List<SelectListItem>();

            isReceiptList.Add(new SelectListItem
            {
                Text = "Yes",
                Value = "true"
            });
            isReceiptList.Add(new SelectListItem
            {
                Text = "No",
                Value = "false"
            });
            ViewBag.IsReceipRequired = new SelectList(isReceiptList, "Value", "Text");
        
            //Time Limit Options
            List<SelectListItem> timeLimitList = new List<SelectListItem>();

            timeLimitList.Add(new SelectListItem
            {
                Text = "Title required to advance",
                Value = "1"
            });


            timeLimitList.Add(new SelectListItem
            {
                Text = "Title can arrive at any time",
                Value = "2"
            });

            timeLimitList.Add(new SelectListItem
            {
                Text = "Title must arrive within a specified time",
                Value = "3"
            });
            ViewBag.ReceivedTimeLimit = new SelectList(timeLimitList, "Value", "Text");
            //Receipt required methods
            List<SelectListItem> receiptRequiredMethodList = new List<SelectListItem>();

            receiptRequiredMethodList.Add(new SelectListItem
            {
                Text = "Must be physically present",
                Value = "1"
            });


            receiptRequiredMethodList.Add(new SelectListItem
            {
                Text = "Scanned copy only",
                Value = "2"
            });

            receiptRequiredMethodList.Add(new SelectListItem
            {
                Text = "Physically present or scanned copy",
                Value = "3"
            });
            ViewBag.ReceiptRequiredMethod = new SelectList(receiptRequiredMethodList, "Value", "Text");
            if (uId > 0)
            {
                LoanSetupAccess la = new LoanSetupAccess();
                TitleAccess ta = new TitleAccess();
                Title title = new Title();
                
                int loanId = loanData.loanId;
                //check loan id is greater than 0
                if (loanId > 0)
                {
                    //check is update
                    if (loanData.stepId>4)
                    {
                        //get title details
                        var titleObj = ta.getTitleDetails(loanId);
                        ViewBag.Edit = 1;
                        //check object is not null
                        if (titleObj != null)
                        {
                            if (titleObj.ReceivedTimeLimit == "Title required to advance")
                            {
                                titleObj.ReceivedTimeLimit = "1";
                            }
                            else if (titleObj.ReceivedTimeLimit == "Title can arrive at any time")
                            {
                                titleObj.ReceivedTimeLimit = "2";
                            }
                            else if (titleObj.ReceivedTimeLimit == "Title must arrive within a specified time")
                            {
                                titleObj.ReceivedTimeLimit = "3";
                            }

                            if (titleObj.ReceiptRequiredMethod == "Must be physically present")
                            {
                                titleObj.ReceiptRequiredMethod = "1";
                            }
                            else if (titleObj.ReceiptRequiredMethod == "Scanned copy only")
                            {
                                titleObj.ReceiptRequiredMethod = "2";
                            }
                            else if (titleObj.ReceiptRequiredMethod == "Physically present or scanned copy")
                            {
                                titleObj.ReceiptRequiredMethod = "3";
                            }
                           
                            ViewBag.DefaultEmail = titleObj.RemindEmail;
                        }
                        //check object is null
                        else if(titleObj == null)
                        {
                            //return to login
                            return RedirectToAction("UserLogin", "Login");
                        }
                        //check ajax request
                        if (HttpContext.Request.IsAjaxRequest())
                        {
                            ViewBag.AjaxRequest = 1;
                            return PartialView(titleObj);
                        }
                        else
                        {

                            return View(titleObj);
                        }

                    }

                    else
                    {
                        ViewBag.Edit = 0;
                        //get auto remind email given in loan setup step 1
                        string defaultEmail = la.getAutoRemindEmailByLoanId(loanId);

                        ViewBag.Email = defaultEmail;
                       //check ajax request
                        if (HttpContext.Request.IsAjaxRequest())
                        {
                            ViewBag.AjaxRequest = 1;
                            return PartialView();
                        }
                        else
                        {

                            return View();
                        }

                    }
                   
                }
                //if loan id is 0 or less than 0
                else
                {
                    //return to login page
                    return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
                }
            }
            //if logged user id is 0 or less than 0
            else
            {
                //return to login page
                return RedirectToAction("UserLogin", "Login", new { lbl = "Due to inactivity your session has timed out, please log in again." });
            }

        }
            /*
        Frontend page: Update Titles
        Title: Update title status
        Designed: Piyumi
        User story:
        Developed: Piyumi
        Date created: 03/17/2016
        */
        public int UpdateTitleStatus(Models.Unit unitTitle)
        {
            string loanCode = null;
            //Check Session["loanCode"] is null or empty
            if (!string.IsNullOrEmpty(Session["loanCode"].ToString()))
            {
            //if not null or empty convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            TitleAccess titleObj = new TitleAccess();
            //update title status
            bool reslt = titleObj.UpdateTitle(unitTitle, loanCode,userData.UserId);
            //Check result of update title
            if (reslt)
            {
            //if result is true get loan details by loan code
                LoanSetupStep1 loanDetails = new LoanSetupStep1();
                loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);
                string status = "";
                //Check title status
                //TitleStatus 0 - Not received
                if (unitTitle.TitleStatus == 0)
                {
                    status = "Not Received";
                }
                //TitleStatus 1 - Received
                else if (unitTitle.TitleStatus == 1)
                {
                    status = "Received";
                }
                //TitleStatus 2 - Returned to Dealer
                else if (unitTitle.TitleStatus == 2)
                {
                    status = "Returned to Dealer";
                }
                //TitleStatus 3 - Sent to Bank
                else if (unitTitle.TitleStatus == 3)
                {
                    status = "Sent to Bank";
                }
                //insert log entry 
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId,loanDetails.loanId, "Title Status Update", "Update title status of unit:" + unitTitle.IdentificationNumber +" ,Updated status:"+status+",Updated date:"+ DateTime.Now, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);
                TempData["reslt"] = 1;
                return 1;
            }
            else
            {
                TempData["reslt"] =0;
                return 0;
            }
        }
        /*
      Frontend page: Update Titles
      Title: Search titles by identification number
      Designed: Piyumi
      User story:
      Developed: Piyumi
      Date created: 03/17/2016
      */
        public ActionResult SearchTitleStatus(string identificationNumber)
        {
            //check Session["AuthenticatedUser"] is null or Session["loanCode"] is null
            if (Session["AuthenticatedUser"]==null || Session["loanCode"] == null)
            {
                //return to login page if sessions are null
                return RedirectToAction("UserLogin", "Login",new { lbl = " Due to inactivity your session has timed out, please log in again." });
            }
            //Conver session to string variable
            string loanCode = Session["loanCode"].ToString();

            TitleAccess obj1 = new TitleAccess();
            TitleStatus obj2 = new TitleStatus();
            List<Models.Unit> resultList = new List<Models.Unit>();

            //Check input parameter:identificationNumber is null or empty and loancode is null or empty 
            if ((!string.IsNullOrEmpty(identificationNumber))&&(!string.IsNullOrEmpty(loanCode)))
            {
                //search from units where matching the loan code and last 6 digits of identification number
                resultList = obj1.SearchTitle(loanCode,identificationNumber);
                
            }
            //Check search result list is not null
            if (resultList != null)
            {
                //filter list if contain active units - 1
                obj2.TitleList = resultList.FindAll(t => t.UnitStatus == 1);
                //Check active units count is 0
                if (obj2.TitleList.Count() == 0)
                {
                    //filter list if contain payoff units - 2
                    obj2.TitleList = resultList.FindAll(t => t.UnitStatus == 2);
                    //Check inactive units count is 0
                    if (obj2.TitleList.Count() == 0)
                    {
                        //filter list if contain inactive units - 0
                        obj2.TitleList = resultList.FindAll(t => t.UnitStatus == 0);

                    }
                }
                //return search result list to view
                return PartialView(obj2);
            }
            else
            {
                obj2.TitleList = new List<Models.Unit>();
                //return search result list to view
                return PartialView(obj2);
            }
            
        }
        /*

        Frontend page   : Add Unit 
        Title           : Add or Advance Units
        Designed        : Kasun Samarawickrama
        User story      : 
        Developed       : Kasun Samarawickrama
        Date created    : 02/24/2016

        */
        public ActionResult AddUnit()
        {
            // Handle Record successfully update or Error message

            int Flag = 0;
            if (TempData["Msg"] != null)
            {
                Flag = int.Parse(TempData["Msg"].ToString());
                if (Flag == 1)
                {
                    ViewBag.Msg = "Success";
                }
                else if (Flag == 3)
                {
                    ViewBag.Msg = "Requested";
                }
                else if (Flag == 2)
                {
                    ViewBag.Msg = "Error";
                }
            }
           

            int userId = userData.UserId;
            ViewBag.Role = userData.RoleId; ;

            //Check loan is null or not
            if (Session["loanCode"] == null || Session["loanCode"].ToString() == "")
                return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });

            // for role id3 - user section
            if (userData.RoleId == 3)
            {
                // check user has rights to access this loan - if not redirect to dashboard
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    var checkAdvance = false;

                    // check user permission to the site
                    string rgts = "";
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList =null;
                    //spit the permission string
                    if (rgts != "") {
                        rgtList = rgts.Split(',');
                    }
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            //check user have rights to add unit page
                            if (x == "U04")
                            {
                                checkPermission = true;
                            }
                            // check user have right to advance units in this page
                            if (x == "U01")
                            {
                                checkAdvance = true;
                            }
                        }
                        if (checkAdvance == true)
                        {
                            ViewBag.advanceAllow = true;
                        }
                        else {
                            ViewBag.advanceAllow = false;
                        }
                        if (checkPermission == false)
                        {
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        return RedirectToAction("UserDetails", "UserManagement");
                    }
                    
                }
            }
            string loanCode = Session["loanCode"].ToString();
            // retrive loan details
            LoanSetupStep1 loan = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);

            int loanId = loan.loanId;
            Session["addUnitloan"] = loan;


            ViewBag.loanDetails = loan;
            //set default unit type for add unit page
            if (loan.selectedUnitTypes.Count == 1) {
                ViewBag.UnitTypeId = loan.selectedUnitTypes[0].unitTypeName;
            }

            Models.Unit unit = new Models.Unit();

            unit.AdvancePt = loan.advancePercentage;
            unit.LoanId = loanId;
            unit.LoanAmount = loan.loanAmount;
            unit.AdvanceDate = DateTime.Now;
            unit.StartDate = loan.startDate;
            unit.EndDate = loan.maturityDate;

            //get company type
            //1 - Lender
            //2 - Dealer
            BranchAccess ba = new BranchAccess();
            int companyType = ba.getCompanyTypeByUserId(userId);

            ViewBag.CompabyType = companyType;
            ViewBag.RoleId = userData.RoleId;

            //Check title 
            TitleAccess ta = new TitleAccess();
            Title title = ta.getTitleDetails(loan.loanId);
            // check title track allow or not
            if (title != null)
            {
                bool isTitleTrack = title.IsTitleTrack;
                if (isTitleTrack)
                    ViewBag.IsTitleTrack = "Yes";

                string upload = title.TitleAcceptMethod;
                if (!string.IsNullOrEmpty(upload) && upload == "Scanned Title Adequate")
                    ViewBag.Upload = "Yes";

            }
            // loan Details for (loan Detail box) in the page 
            UnitAccess ua = new UnitAccess();
            LoanPaymentDetails loanPaymentDetails = ua.GetLoanPaymentDetailsByLoanId(loanId);

            unit.Balance = loanPaymentDetails.BalanceAmount;
            // check balane field is editable or not for this loan
            ViewBag.Editable = loan.isEditAllowable ? "Yes" : "No";

            
            //set user role to restrict add & advance unit if this user is dealer user(role id = 4)
            ViewBag.RoleId = userData.RoleId; 

            return PartialView(unit);
        }