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);
        }
        /*

          Frontend page: Fee Page
          Title: get fees by selected date
          Designed: Nadeeka
          User story:
          Developed: Nadeeka
          Date created: 4/21/2016

       */
        
        public ActionResult PayFeesForSelectedDueDate(DateTime dueDate, string type)
        {
                LoanSetupStep1 loanDetails = new LoanSetupStep1();
                loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(Session["loanCode"].ToString()); // take the loan detail of selected loan
                // pass the loan details to the view
                ViewBag.loanDetails = loanDetails;

                FeeAccess feeAccess = new FeeAccess();
                List<Fees> lstFee = feeAccess.GetFeesByDueDate(loanDetails.loanId, dueDate, type); // get fees list by duedate and type of fee
                FeesModel feeModel = new FeesModel();
                feeModel.FeeModelList = new List<Fees>();
                feeModel.Type = type;

                // if list exists, add to model and session for searching
                if (lstFee != null && lstFee.Count > 0)
                {
                    feeModel.FeeModelList.AddRange(lstFee);
                    Session["feeList"] = feeModel.FeeModelList;
                   
                }

               // return partial view of selected fee page
                return PartialView(feeModel);
                

                        
        }
        /// <summary>
        /// Frontend page: Advance Unit
        /// Title: Get loan details and not advanced unit details from database and return to view
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 02/24/2016
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Return partial view</returns>
        public ActionResult Advance()
        {
            int flag = -1;
            //assign logged user id to variable
            int userId = userData.UserId;
            string loanCode;
            try
            {
                //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                //if exception occured return to login page
                return RedirectToAction("UserLogin", "Login");
            }
            BranchAccess branch = new BranchAccess();
            //retrieve company type for given user id
            int companyType = branch.getCompanyTypeByUserId(userId);
            //check company type 1-Lender
            if (companyType == 1)
            {
                ViewBag.isLender = true;
            }
            //company type 2 - Dealer
            else
            {
                ViewBag.isLender = false;
            }

            ViewBag.unitClickId = "";
            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            //retrieve loan delails for given loan code
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);
            //check logged user role is user
            if (userData.RoleId == 3)
            {
                //check Session["CurrentLoanRights"] is null or empty
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    string rgts = "";
                    //convert Session["CurrentLoanRights"] to string variable
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList = null;
                    //check right string is not empty
                    if (rgts != "")
                    {
                        //split string
                        rgtList = rgts.Split(',');
                    }
                    //check right list is not null
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            //check relevant right for Advance Unit page contains in the user right list
                            if (x == "U01")
                            {
                                checkPermission = true;
                            }
                        }
                        //check permission value is false
                        if (checkPermission == false)
                        {
                            //return to dashboard
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        //return to dashboard
                        return RedirectToAction("UserDetails", "UserManagement");
                    }

                }
            }
            //check logged user is dealer user
            else if (userData.RoleId == 4)
            {
                //return to dashboard
                return RedirectToAction("UserDetails", "UserManagement");
            }
            ViewBag.loanDetails = loanDetails;
            Models.Unit unit = new Models.Unit();
            //get units which need to advance for given loan id
            AdvanceUnit advanceUnit = this.GetAdvanceUnitList(loanDetails.loanId);
            //assign loan id to session object
            Session["advUnitloanId"] = loanDetails.loanId;
            //assign not advanced unit list to session object
            Session["notAdvancedList"] = advanceUnit.NotAdvanced;
            ViewBag.advanceList = advanceUnit.NotAdvanced;
            //check update result of Advance Unit page
            if((TempData["updateReslt"]!=null)&&(TempData["updateReslt"].ToString() != ""))
            {
                //convert result to integer
                flag = int.Parse(TempData["updateReslt"].ToString());
            }
            //check result value is 1
            if (flag == 1)
            {
                //flag 1 - success
                ViewBag.Msg = "Success";
            }
            else if (flag == 0)
            {
                //flag 0 - error
                ViewBag.Msg = "Error";
            }
            else if (flag == 2)
            {
                //flag 2 - Advance amount error
                ViewBag.Msg = "Advance amount error";
            }else if(flag == 3)
            {
                //flag 3 - Advance error
                ViewBag.Msg = "Advance Error";
            }
            
            //return advance unit list to view
            return View(advanceUnit);
        }
        /// <summary>
        /// CreatedBy : Nadeeka
        /// CreatedDate: 2016/02/09
        /// 
        /// Insert curtailment details
        /// 
        /// argument : curtailment list
        /// 
        /// </summary>
        /// <returns>1</returns>
        public LoanSetupStep1 GetLoanDetailsByLoanId(int loanId)
        {
            try
            {
                LoanSetupStep1 loan = new LoanSetupStep1();
                DataHandler dataHandler = new DataHandler();
                List<object[]> paramertList = new List<object[]>();
                paramertList.Add(new object[] { "@loan_id", loanId });

                DataSet dataSet = dataHandler.GetDataSet("spGetLoanDetailsByLoanId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    DataRow dataRow = dataSet.Tables[0].Rows[0];
                    loan.loanNumber = dataRow["loan_number"].ToString();
                    loan.startDate = Convert.ToDateTime(dataRow["start_date"]);
                    loan.maturityDate = Convert.ToDateTime(dataRow["maturity_date"]);
                    loan.loanAmount = Convert.ToDecimal(dataRow["loan_amount"]);
                    loan.advancePercentage = Convert.ToInt32(dataRow["advance"]);
                    //0 - day, 1 - month
                    loan.payOffPeriodType = 1;
                    if (dataRow["pay_off_type"].ToString() == "d")
                        loan.payOffPeriodType = 0;

                    //loan.payOffPeriod = Convert.ToInt32(dataRow["pay_off_period"]);
                    loan.LoanStatus = Convert.ToBoolean(dataRow["loan_status"]);
                    loan.isInterestCalculate = Convert.ToBoolean(dataRow["is_interest_calculate"]);
                    loan.isEditAllowable = Convert.ToBoolean(dataRow["is_edit_allowable"]);
                    loan.CurtailmentDueDate = dataRow["curtailment_due_date"].ToString();
                    loan.CurtailmentAutoRemindEmail = dataRow["curtailment_auto_remind_email"].ToString();
                    if (!string.IsNullOrEmpty(dataRow["curtailment_remind_period"].ToString()))
                    {
                        loan.CurtailmentEmailRemindPeriod = Convert.ToInt32(dataRow["curtailment_remind_period"].ToString());
                    }

                    loan.CurtailmentCalculationBase = dataRow["curtailment_calculation_type"].ToString();

                    return loan;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : Nadeeka
        /// CreatedDate: 2016/03/15
        /// 
        /// Get loan curtailment schedule by loan id
        /// 
        /// </summary>
        /// <param name="loanId">loan id</param>
        /// <returns>curtialment breakdown as a DataSet</returns>
        public LoanSetupStep1 GetLoanCurtailmentBreakdown(int loanId)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@loan_id", loanId });

            DataSet dataSet = dataHandler.GetDataSet("spGetLoanCurtailmentBreakdown", paramertList);
            if (dataSet != null && dataSet.Tables.Count != 0)
            {
                LoanSetupStep1 loan = new LoanSetupStep1();
                loan.curtailmetList = new List<Curtailment>();
                loan.payOffPeriodType = dataSet.Tables[0].Rows[0]["pay_off_type"].ToString().Equals("d") ? 0 : 1;
                //loan.payOffPeriod = Convert.ToInt32(dataSet.Tables[0].Rows[0]["pay_off_period"].ToString());
                loan.CurtailmentCalculationBase = dataSet.Tables[0].Rows[0]["curtailment_calculation_type"].ToString();
                loan.advancePercentage = Convert.ToInt32(dataSet.Tables[0].Rows[0]["advance"].ToString());
                foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                {
                    Curtailment curtailment = new Curtailment();
                    curtailment.CurtailmentId = Convert.ToInt32(dataRow["curtailment_id"].ToString());
                    curtailment.TimePeriod = Convert.ToInt32(dataRow["time_period"].ToString());
                    curtailment.Percentage = Convert.ToInt32(dataRow["percentage"].ToString());
                    loan.curtailmetList.Add(curtailment);
                }

                return loan;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// CreatedBy : iRFAN
        /// CreatedDate: 2016/02/25
        /// 
        /// GET LOAN DETAILS BY NON REG BRANCH ID
        /// 
        /// 
        /// 
        /// </summary>
        /// <returns>1</returns>

        public List<LoanSetupStep1> GetLoanDetailsByNonRegBranchId(int nonRegBranchId)
        {
            List<LoanSetupStep1> loanList = new List<LoanSetupStep1>();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@non_reg_branch_id", nonRegBranchId });

            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetLoanDetailsByNonRegBranchId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        LoanSetupStep1 loan = new LoanSetupStep1();
                        loan.loanNumber = dataRow["loan_number"].ToString();
                        loan.startDate = Convert.ToDateTime(dataRow["start_date"]);
                        loan.maturityDate = Convert.ToDateTime(dataRow["maturity_date"]);
                        loan.loanAmount = Convert.ToDecimal(dataRow["loan_amount"]);
                        loan.advancePercentage = Convert.ToInt32(dataRow["advance"]);

                        //0 - day, 1 - month
                        if (dataRow["pay_off_type"].ToString() == "d")
                            loan.payOffPeriodType = 0;
                        loan.payOffPeriodType = 1;
                        //loan.payOffPeriod = Convert.ToInt32(dataRow["pay_off_period"]);
                        loan.LoanStatus = Convert.ToBoolean(dataRow["loan_status"]);
                        loan.loanCode = dataRow["loan_code"].ToString();
                        loan.isEditAllowable = Convert.ToBoolean(dataRow["is_edit_allowable"]);

                        loanList.Add(loan);
                    }
                }
                return loanList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        internal int insertLoanStepOne(LoanSetupStep1 loanSetupStep1, int loanId)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            try
            {
            paramertList.Add(new object[] { "@loan_id", loanId });
            paramertList.Add(new object[] { "@advance", loanSetupStep1.advancePercentage});
            paramertList.Add(new object[] { "@auto_remind_email", loanSetupStep1.autoReminderEmail });
            paramertList.Add(new object[] { "@auto_remind_period", loanSetupStep1.autoReminderPeriod });
            paramertList.Add(new object[] { "@default_unit_type", loanSetupStep1.defaultUnitType });
            paramertList.Add(new object[] { "@is_edit_allowable", loanSetupStep1.isEditAllowable });
            paramertList.Add(new object[] { "@is_interest_calculate", loanSetupStep1.isInterestCalculate });
            paramertList.Add(new object[] { "@loan_amount", loanSetupStep1.loanAmount });
            paramertList.Add(new object[] { "@loan_number", loanSetupStep1.loanNumber });
            paramertList.Add(new object[] { "@maturity_date", loanSetupStep1.maturityDate });
            paramertList.Add(new object[] { "@non_reg_branch_id", loanSetupStep1.nonRegisteredBranchId });
            paramertList.Add(new object[] { "@payment_method", loanSetupStep1.paymentMethod });
            //paramertList.Add(new object[] { "@pay_off_period", loanSetupStep1.payOffPeriod });
            //paramertList.Add(new object[] { "@pay_off_type", ((loanSetupStep1.payOffPeriodType == 0) ? 'd' : 'm') });
            paramertList.Add(new object[] { "@loan_code", (new BranchAccess()).getBranchByBranchId(loanSetupStep1.RegisteredBranchId).BranchCode + "-" + loanSetupStep1.loanNumber });
            paramertList.Add(new object[] { "@start_date", loanSetupStep1.startDate });
            paramertList.Add(new object[] { "@created_date", DateTime.Now });
            paramertList.Add(new object[] { "@loan_status", false });
            paramertList.Add(new object[] { "@is_delete", false });

                //DataSet dataSet = dataHandler.GetDataSet("spInsertLoanStepOne", paramertList);
                //if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                //{
                //    loanId =int.Parse(dataSet.Tables[0].Rows[0]["return"].ToString());

                //}

                loanId=dataHandler.ExecuteSQLWithReturnVal("spInsertLoanStepOne", paramertList);

                if (loanId == 0)
                {
                    return loanId;
                }
                else
                {
                    foreach (UnitType UnitType in loanSetupStep1.allUnitTypes)
                    {
                        if (UnitType.isSelected == true)
                        {
                            List<object[]> paramertList1 = new List<object[]>();
                            paramertList1.Add(new object[] { "@loan_id", loanId });
                            paramertList1.Add(new object[] { "@unit_type_id", UnitType.unitTypeId });

                            dataHandler.GetDataSet("spInsertLoanUniType", paramertList1);
                        }


                    }

                    return loanId;
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : Kasun
        /// CreatedDate: 2016/03/30
        /// 
        /// get permissioned loans with branch , non reg branch and loan details
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public LoanSelection GetPermisssionGivenLoanwithBranchDeatils(int userId,int companyId,int? branchId,int roleId)
        {
            LoanSelection detailList = new LoanSelection();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();

            paramertList.Add(new object[] { "@userId", userId });
            paramertList.Add(new object[] { "@companyId", companyId });
            paramertList.Add(new object[] { "@branchId", branchId });
            paramertList.Add(new object[] { "@roleId", roleId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spRetrivePermissionGivenLoans", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0)
                {
                    List<Branch> RegBranches = new List<Branch>();
                    List<NonRegBranch> NonRegBranchList = new List<NonRegBranch>();
                    List<LoanSetupStep1> LoanList =  new List<LoanSetupStep1>();

                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        Branch branch = new Branch();
                        NonRegBranch nonRegBranch = new NonRegBranch();
                        LoanSetupStep1 loan = new LoanSetupStep1();

                        branch.BranchId = int.Parse(dataRow["branch_id"].ToString());
                        branch.BranchName = dataRow["regBranchName"].ToString();

                        nonRegBranch.NonRegBranchId = int.Parse(dataRow["non_reg_branch_id"].ToString());
                        nonRegBranch.BranchId = branch.BranchId;
                        nonRegBranch.CompanyNameBranchName = dataRow["nonRegBranchName"].ToString();

                        loan.loanId = int.Parse(dataRow["loan_id"].ToString());
                        loan.loanNumber = dataRow["loan_number"].ToString();
                        loan.loanCode = dataRow["loan_code"].ToString();
                        loan.rightId = dataRow["right_id"].ToString();
                        loan.loanAmount = decimal.Parse(dataRow["loan_amount"].ToString());
                        loan.startDate = DateTime.Parse(dataRow["start_date"].ToString());
                        loan.maturityDate = DateTime.Parse(dataRow["maturity_date"].ToString()) ;
                        loan.CreatedDate = DateTime.Parse(dataRow["created_date"].ToString()) ;

                        if (dataRow["is_title_tracked"].ToString() != null && dataRow["is_title_tracked"].ToString() != "") {
                            loan.titleTracked = bool.Parse(dataRow["is_title_tracked"].ToString());
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_lot_inspection_fee"].ToString()))
                        {
                            if (bool.Parse(dataRow["has_lot_inspection_fee"].ToString()))
                            {
                                loan.LotInspectionFee = 1;
                            }
                            else
                            {
                                loan.LotInspectionFee = 0;
                            }
                        }

                        else
                        {
                            loan.LotInspectionFee = 0;
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_monthly_loan_fee"].ToString()))
                        {
                            if (bool.Parse(dataRow["has_monthly_loan_fee"].ToString()))
                            {
                                loan.MonthlyLoanFee = 1;
                            }
                            else
                            {
                                loan.MonthlyLoanFee = 0;
                            }
                        }

                        else
                        {
                            loan.MonthlyLoanFee = 0;
                        }
                        if (!string.IsNullOrEmpty(dataRow["has_advance_fee"].ToString()))
                        {
                            if (bool.Parse(dataRow["has_advance_fee"].ToString()))
                            {
                                loan.AdvanceFee = 1;
                            }
                            else
                            {
                                loan.AdvanceFee = 0;
                            }
                            if (!string.IsNullOrEmpty(dataRow["payment_due_method"].ToString()))
                            {
                                if (dataRow["payment_due_method"].ToString().Contains("Vehicle Payoff"))
                                {
                                    loan.AdvanceFeePayAtPayoff = true;
                                }
                                else
                                {
                                    loan.AdvanceFeePayAtPayoff = false;
                                }

                            }
                        }

                        else
                        {
                            loan.AdvanceFee = 0;
                        }
                        loan.nonRegisteredBranchId = nonRegBranch.NonRegBranchId;
                        bool checkBranch = false;
                        bool checkNonRegBranch = false;
                        bool checkLoan = false;
                        foreach (var br in RegBranches) {
                            if (br.BranchId == branch.BranchId) {
                                checkBranch = true;
                            }
                        }
                        if (checkBranch == false) {
                            RegBranches.Add(branch);
                        }
                        foreach (var nrbr in NonRegBranchList)
                        {
                            if (nrbr.NonRegBranchId == nonRegBranch.NonRegBranchId)
                            {
                                checkNonRegBranch = true;
                            }
                        }
                        if (checkNonRegBranch == false)
                        {
                            NonRegBranchList.Add(nonRegBranch);
                        }

                        foreach (var l in LoanList)
                        {
                            if (l.loanId == loan.loanId)
                            {
                                checkLoan = true;
                            }
                        }
                        if (checkLoan == false)
                        {
                            LoanList.Add(loan);
                        }
                        
                    }
                    detailList.RegBranches = RegBranches;
                    detailList.NonRegBranchList = NonRegBranchList;
                    detailList.LoanList = LoanList;

                    return detailList;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /*

 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);
        }
        /*

  Frontend page: Curtailment Page
  Title: Load curtailment page
  Designed: Nadeeka
  User story: 
  Developed: Nadeeka
  Date created: 3/21/2016

*/
        public ActionResult PayCurtailments()
        {

            // if user access via url -- wrong access
            if (Session["loanCode"] == null || Session["loanCode"].ToString() == "")
                return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });

            lCode = Session["loanCode"].ToString(); // take the loan code


            // if user is a normal user, check his user rights
            if (userData.RoleId == 3)
            {
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    string rgts = "";
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList = null;
                    if (rgts != "")
                    {
                        rgtList = rgts.Split(',');
                    }
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            if (x == "U05")
                            {
                                checkPermission = true;
                            }
                        }
                        if (checkPermission == false)
                        {
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        return RedirectToAction("UserDetails", "UserManagement");
                    }

                }
            }

            // if user is a dealer user -- he is not allowed
            else if (userData.RoleId == 4)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }


            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(Session["loanCode"].ToString()); // take the loan details
            Session["curtLaonId"] = loanDetails.loanId;  // save the loan id on session
            ViewBag.curtTotal = (new CurtailmentAccess()).GetCurtailmentsTotal(loanDetails.loanId); // pass the total amount of curtailment to the view

            // pass the loan details to the view
            ViewBag.loanDetails = loanDetails;
            ViewBag.LoanId = loanDetails.loanId;

            // return pay curtailment page
            return View();
        }
        public ActionResult Step6(string dashbrd)
        {
            //dashbrd = 6;
            int userrole = userData.RoleId;
            int userId = userData.UserId;

            if (userrole >= 3)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }

            UserManageAccess uma = new UserManageAccess();

            // check if step is less than 6, not allowed to this page...

            int stepNo = loanData.stepId;


            if (stepNo < 0)
            {
                return RedirectToAction("UserLogin", "Login", new { lbl = "You are not Allowed." });
            }
            else if ((stepNo == 0)&&(dashbrd== "bshdrdoanl"))
            {
                stepNo = 6;
                loanData.stepId = 1;
                Session["dashboard"] = 1;

                // set the loan setup session to step 1

               
                Session["companyStep"] = 5;
                loanData.stepId = 1;
                Session["loanStep"] = loanData;



            }

            if(TempData["error"] != null && TempData["error"].ToString() == "error")
            {
                ViewBag.Error = "Failed to create loan";
            }

            // get the Role Name for front end view
            ViewBag.userroleName = uma.getUserRoleName(userId);

            BranchAccess ba = new BranchAccess();

            // get the Company type for front end view
            int comType = ba.getCompanyTypeByUserId(userId);
            //int comType = userData.CompanyType;
            ViewBag.ThisCompanyType = (comType == 1) ? "Lender" : "Dealer";//

            // retrieve registered branches, nonregistered branches using his company Id

            List<Branch> RegisteredBranchLists = (new BranchAccess()).getBranches(userData.Company_Id);
            List<NonRegBranch> NonRegisteredBranchLists = (new BranchAccess()).getNonRegBranches(userData.Company_Id);

            // get the payments method for front End View
            List<string> paymentMethods = new List<string>();
            paymentMethods.Add("Auto Deduct/Deposit");
            paymentMethods.Add("Invoice/Check");
            ViewBag.paymentMethods = paymentMethods;


            // Defaul loan setup form and default dates
            LoanSetupStep1 loanSetupStep1 = new LoanSetupStep1();
            loanSetupStep1.startDate = DateTime.Today;
            loanSetupStep1.maturityDate = DateTime.Today.AddDays(1);

            // get loan Id for each user
            LoanSetupAccess la = new LoanSetupAccess();
            int loanId = 0;

            if ((userrole == 1) || (userrole == 2))
            {
                loanId = loanData.loanId;
            }

            // if loan number exists get the loan details
            if (loanId > 0)
            {
                loanSetupStep1 = la.GetLoanStepOne(loanId);
            }

            if (userrole == 2)
            {
                // if user is a admin, his branch id is registerd branch id
                loanSetupStep1.RegisteredBranchId = userData.BranchId;

                // the get registered branch detail from the company branches list
                foreach (Branch branch in RegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {
                        var newList = new List<Branch>();
                        newList.Add(branch);
                        ViewBag.RegisteredBranchId = new SelectList(newList, "BranchId", "BranchName", userData.BranchId);
                    }
                }
                var newNonRegList = new List<Branch>();

                // the get non registered branches details for perticular branch  from the non registeres branches list
                foreach (NonRegBranch branch in NonRegisteredBranchLists)
                {
                    if (branch.BranchId == userData.BranchId)
                    {

                        newNonRegList.Add(branch);


                    }
                }



                ViewBag.NonRegisteredBranchId = new SelectList(newNonRegList, "NonRegBranchId", "CompanyNameBranchName");


            }
            // if he is a super admin, add all company branches and non registered branches in to the list
            else
            {
                // if super admin get the branch id of the loan
                if (loanId > 0)
                {
                    NonRegBranch nonRegBranch = (new BranchAccess()).getNonRegBranchByNonRegBranchId(loanSetupStep1.nonRegisteredBranchId);
                    loanSetupStep1.RegisteredBranchId = nonRegBranch.BranchId;

                }

                // add banches which contain non reg branches only
                List<Branch> newBranches = new List<Branch>();
                foreach (Branch branch in RegisteredBranchLists)
                {
                    foreach (NonRegBranch nonbranch in NonRegisteredBranchLists)
                    {
                        if (branch.BranchId == nonbranch.BranchId)
                        {

                            newBranches.Add(branch);

                            break;
                        }
                    }
                }


                ViewBag.RegisteredBranchId = new SelectList(newBranches, "BranchId", "BranchName");

                if (newBranches.Count >= 1)
                {
                    ViewBag.NonRegisteredBranchId = new SelectList(NonRegisteredBranchLists, "NonRegBranchId", "CompanyNameBranchName");
                }

            }

            if (NonRegisteredBranchLists.Count == 1)
            {   
                if(userData.RoleId == 1)
                {
                    // the get registered branch detail from the company branches list
                    foreach (Branch branch in RegisteredBranchLists)
                    {
                        if (branch.BranchId == NonRegisteredBranchLists[0].BranchId)
                        {
                            var newList = new List<Branch>();
                            newList.Add(branch);
                            ViewBag.RegisteredBranchId = new SelectList(newList, "BranchId", "BranchName", userData.BranchId);
                        }
                    }
                }
                loanSetupStep1.nonRegisteredBranchId = NonRegisteredBranchLists[0].NonRegBranchId;
            }

            loanSetupStep1.allUnitTypes = (new LoanSetupAccess()).getAllUnitTypes();

            if (loanId > 0)
            {

                loanSetupStep1.allUnitTypes = (new LoanSetupAccess()).getAllUnitTypes();
                //(new LoanSetupAccess()).getSelectedUnitTypes(loanId, loanSetupStep1);
                foreach (UnitType unitType in (List<UnitType>)loanSetupStep1.selectedUnitTypes)
                {
                    foreach (UnitType allUnitType in (List<UnitType>)loanSetupStep1.allUnitTypes)
                    {
                        if (allUnitType.unitTypeId == unitType.unitTypeId)
                        {
                            allUnitType.isSelected = true;
                            continue;
                        }
                    }

                }


            }



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

                return View(loanSetupStep1);
            }
        }
        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." });
        }
        public ActionResult Step6_Post(LoanSetupStep1 loanSetupStep1)
        {
            int userId = userData.UserId;
          
            if (!CheckTheRangeOfPayOffPeriod(loanSetupStep1.autoReminderPeriod, loanSetupStep1.startDate, loanSetupStep1.maturityDate, 0))
            {

                return new HttpStatusCodeResult(404, "Auto reminder period is out of range");
            }

            if (!IsAtleastOneSelectUnitType(loanSetupStep1.allUnitTypes))
            {
                return new HttpStatusCodeResult(404, "Select Atleast One Unit Type");
            }

            // check he is super admin or admin
            if (userData.RoleId > 2)
            {
                return new HttpStatusCodeResult(404, "Not Allowed");
            }

            if ((Session["dashboard"] !=null))
            {
                loanData.stepId = 1;
            }
            // check if   step is 6...
            StepAccess sa = new StepAccess();
            if (loanData.stepId < 1)
            {
                return new HttpStatusCodeResult(404, "Not Allowed");
            }

            LoanSetupAccess loanSetupAccess = new LoanSetupAccess();

            LoanSetupAccess la = new LoanSetupAccess();
            int loanId = loanData.loanId;

            loanData.CompanyId = userData.Company_Id;

            
            Session["loanStep"] = loanData;

            if (loanId > 0)
            {
                loanId = loanSetupAccess.insertLoanStepOne(loanSetupStep1, loanId);
                if (loanId > 0)
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, loanSetupStep1.RegisteredBranchId, loanId, "Loan Details", "Edited Loan : " + loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                }
                else
                {
                    TempData["error"] = "error";
                    return RedirectToAction("step6");
                }
              
            }
            else
            {
                //loanId = la.getLoanIdByUserId(userId);


                loanId = loanSetupAccess.insertLoanStepOne(loanSetupStep1, loanId);
                if (loanId > 0)
                {
                    Log log = new Log(userData.UserId, userData.Company_Id, loanSetupStep1.RegisteredBranchId, loanId, "Loan Details", "Inserted Loan : " + loanId, DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                }
                //need to update loanSetup object
                else
                {
                    TempData["error"] = "error";
                    return RedirectToAction("step6");
                }


            }
            if (loanId > 0)
            {
                if (loanSetupStep1.isInterestCalculate)
                {
                    
                    sa.UpdateLoanSetupStep(userData.UserId, loanData.CompanyId, loanSetupStep1.RegisteredBranchId, loanSetupStep1.nonRegisteredBranchId, loanId, 2);
                    if (loanData.stepId < 2)
                    {
                        loanData.stepId = 2;
                    }
                    //loanData.stepId = 2;
                }
                else
                {
                    sa.UpdateLoanSetupStep(userData.UserId,loanData.CompanyId, loanSetupStep1.RegisteredBranchId, loanSetupStep1.nonRegisteredBranchId, loanId, 3);
                    if (loanData.stepId < 3)
                    {
                        loanData.stepId = 3;
                    }
                }
                loanData.BranchId = loanSetupStep1.RegisteredBranchId;
                loanData.nonRegisteredBranchId = loanSetupStep1.nonRegisteredBranchId;
                loanData.loanId = loanId;
                
                Session["loanStep"] = loanData;
            }
            Session["loanStep"] = loanData;
            if (loanSetupStep1.isInterestCalculate)
            {
                return RedirectToAction("step7");
            }
            else
            {
                //sa.UpdateLoanSetupStep(loanData.CompanyId, loanData.BranchId, loanSetupStep1.nonRegisteredBranchId, loanId, 3);
                return RedirectToAction("step8");
            }






        }
        public int PayFees(List<Fees> lstFee, string type)
        {
            int userId = userData.UserId;  // set the user id
            FeeAccess feeAccess = new FeeAccess();
            LoanSetupStep1 loanDetails = new LoanSetupStep1();
            loanDetails = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(Session["loanCode"].ToString()); // take the loan details by loan code
            int returnValue = feeAccess.updateFees(lstFee, lstFee[0].PaidDate, loanDetails.loanId, userId); // update fee details

            //if successfully updated, insert to log 
            if (returnValue == 1)
            {
                Log log;

                // if fee type is advance -- save details to log as advance fee
                if (type == "advanceFee")
                {
                    List<string> IDNumbers = new List<string>();
                    foreach (var fee in lstFee)
                    {
                        IDNumbers.Add(fee.IdentificationNumber);
                    }
                    log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanDetails.loanId, "Pay Fees", "Advance Fee Paid for the unit(s) : " + string.Join(",", IDNumbers) + " , Pay Date : " + lstFee[0].PaidDate.ToString("dd/MM/yyyy"), DateTime.Now);
                    (new LogAccess()).InsertLog(log);

                }

                // if fee type is monthly loan -- save details to log as monthly loan fee
                else if (type == "monthlyLoanFee")
                {
                    List<string> DueDates = new List<string>();
                    foreach (var fee in lstFee)
                    {
                        DueDates.Add(fee.DueDate);
                    }

                    log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanDetails.loanId, "Pay Fees", " Monthly Loan Fee Paid for the due date(s) : { " + string.Join(",", DueDates) + "}" + ", Pay Date : " + lstFee[0].PaidDate.ToString("dd/MM/yyyy"), DateTime.Now);
                    (new LogAccess()).InsertLog(log);
                }

                // if fee type is lot inspection fee -- save details to log as lot inspection fee
                else if (type == "lotInspectionFee")
                {
                    List<string> DueDates = new List<string>();

                    foreach (var fee in lstFee)
                    {
                        DueDates.Add(fee.DueDate);
                    }

                    log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanDetails.loanId, "Pay Fees", "Lot Inspection Fee Paid for the due date(s) : { " + string.Join(",", DueDates) + " } " + ", Pay Date : " + lstFee[0].PaidDate.ToString("dd/MM/yyyy"), DateTime.Now);
                    (new LogAccess()).InsertLog(log);

                }
            }

            // return the value to view
            return returnValue;
        }
        internal LoanSetupStep1 GetLoanStepOne(int loanId)
        {
            LoanSetupStep1 loanSetupStep1 = new LoanSetupStep1();
            IList<UnitType> unittypes = new List<UnitType>();

            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@loan_id", loanId });

            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetLoanStepOneByLoanId", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    DataRow dataRow = dataSet.Tables[0].Rows[0];

                    loanSetupStep1.advancePercentage = int.Parse(dataRow["advance"].ToString());
                    //loanSetupStep1.allUnitTypes
                    loanSetupStep1.autoReminderEmail = dataRow["auto_remind_email"].ToString();
                    loanSetupStep1.autoReminderPeriod = int.Parse(dataRow["auto_remind_period"].ToString());
                    loanSetupStep1.defaultUnitType = int.Parse(dataRow["default_unit_type"].ToString());
                    loanSetupStep1.isEditAllowable = Convert.ToBoolean(dataRow["is_edit_allowable"].ToString());
                    loanSetupStep1.isInterestCalculate = Convert.ToBoolean(dataRow["is_interest_calculate"].ToString());
                    loanSetupStep1.loanAmount = Convert.ToDecimal(dataRow["loan_amount"].ToString());
                    loanSetupStep1.loanNumber = dataRow["loan_number"].ToString();
                    //loanSetupStep1.loanNumberForDisplay = loanSetupStep1.loanNumber;
                    loanSetupStep1.maturityDate = Convert.ToDateTime(dataRow["maturity_date"].ToString());
                    loanSetupStep1.nonRegisteredBranchId = int.Parse(dataRow["non_reg_branch_id"].ToString());
                    loanSetupStep1.paymentMethod = dataRow["payment_method"].ToString();
                    //loanSetupStep1.payOffPeriod = int.Parse(dataRow["pay_off_period"].ToString());
                    //loanSetupStep1.payOffPeriodType = (Convert.ToChar(dataRow["pay_off_type"].ToString()) == 'd') ? 0 : 1;
                    //loanSetupStep1.selectedUnitTypes
                    loanSetupStep1.startDate = Convert.ToDateTime(dataRow["start_date"].ToString());
                    loanSetupStep1.loanCode = dataRow["loan_code"].ToString();
                }

                DataSet dataSet2 = dataHandler.GetDataSet("spGetLoanUnitTypesByLoanId", paramertList);
                if (dataSet2 != null && dataSet2.Tables.Count != 0 && dataSet2.Tables[0].Rows.Count != 0)
                {
                    foreach (DataRow dataRow2 in dataSet2.Tables[0].Rows)
                    {
                        UnitType unitType = new UnitType();
                        unitType.unitTypeId = int.Parse(dataRow2["unit_type_id"].ToString());
                        unitType.unitTypeName = dataRow2["unit_type_name"].ToString();
                        unittypes.Add(unitType);
                    }
                    loanSetupStep1.selectedUnitTypes = unittypes;
                }
                return loanSetupStep1;
            }
            catch (Exception ex)
            {
                throw ex;
            }



            //using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AutoDealersConnection"].ConnectionString))
            //{
            //    try
            //    {
            //        using (SqlCommand cmd = new SqlCommand("spGetLoanStepOneByLoanId", con))
            //        {
            //            cmd.CommandType = CommandType.StoredProcedure;
            //            cmd.Parameters.Add("@loan_id", SqlDbType.Int).Value = loanId;
            //            con.Open();
            //            SqlDataReader reader = cmd.ExecuteReader();

            //            LoanSetupStep1 loanSetupStep1 = new LoanSetupStep1();


            //            while (reader.Read())
            //            {

            //                loanSetupStep1.advancePercentage = int.Parse(reader["advance"].ToString());
            //                //loanSetupStep1.allUnitTypes
            //                loanSetupStep1.autoReminderEmail = reader["auto_remind_email"].ToString();
            //                loanSetupStep1.autoReminderPeriod = int.Parse(reader["auto_remind_period"].ToString());
            //                loanSetupStep1.defaultUnitType = int.Parse(reader["default_unit_type"].ToString());
            //                loanSetupStep1.isEditAllowable = Convert.ToBoolean(reader["is_edit_allowable"].ToString());
            //                loanSetupStep1.isInterestCalculate = Convert.ToBoolean(reader["is_interest_calculate"].ToString());
            //                loanSetupStep1.loanAmount = Convert.ToDecimal(reader["loan_amount"].ToString());
            //                loanSetupStep1.loanNumber = reader["loan_number"].ToString();
            //                loanSetupStep1.loanNumberForDisplay = loanSetupStep1.loanNumber;
            //                loanSetupStep1.maturityDate = Convert.ToDateTime(reader["maturity_date"].ToString());
            //                loanSetupStep1.nonRegisteredBranchId = int.Parse(reader["non_reg_branch_id"].ToString());
            //                loanSetupStep1.paymentMethod = reader["payment_method"].ToString();
            //                loanSetupStep1.payOffPeriod = int.Parse(reader["pay_off_period"].ToString());
            //                loanSetupStep1.payOffPeriodType = (Convert.ToChar(reader["pay_off_type"].ToString()) == 'd') ? 0 : 1;
            //                //loanSetupStep1.selectedUnitTypes
            //                loanSetupStep1.startDate = Convert.ToDateTime(reader["start_date"].ToString());
            //                loanSetupStep1.loanCode = reader["loan_code"].ToString();

            //            }

            //            reader.Close();
            //            IList<UnitType> unittypes = new List<UnitType>();
            //            using (SqlCommand cmd2 = new SqlCommand("spGetLoanUnitTypesByLoanId", con))
            //            {
            //                cmd2.CommandType = CommandType.StoredProcedure;
            //                cmd2.Parameters.Add("@loan_id", SqlDbType.Int).Value = loanId;
            //                //con.Open();
            //                SqlDataReader reader2 = cmd2.ExecuteReader();

            //                while (reader2.Read())
            //                {
            //                    UnitType unitType = new UnitType();
            //                    unitType.unitTypeId = int.Parse(reader2["unit_type_id"].ToString());
            //                    unitType.unitTypeName = reader2["unit_type_name"].ToString();
            //                    unittypes.Add(unitType);

            //                }
            //                loanSetupStep1.selectedUnitTypes = unittypes;

            //                return loanSetupStep1;
            //            }
            //        }
            //    }


            //    catch (Exception ex)
            //    {
            //        throw ex;

            //    }
            //    finally
            //    {
            //        con.Close();
            //    }
            //}
        }
        /*

   Frontend page: Fee Page
   Title: Load the Fee Page
   Designed: Nadeeka
   User story:
   Developed: Nadeeka
   Date created: 4/20/2016

*/

        public ActionResult PayFees()
        {
            try
            {
                lCode = Session["loanCode"].ToString(); // take the loan code on session
            }

            // if there is no loan on Session -- redirect to login
            catch (Exception)
            {
                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(Session["loanCode"].ToString()); // take the loan details of loan code

            // pass loan details to the view
            ViewBag.loanDetails = loanDetails;

            Loan loanSelected = new Loan();

            // take the loan which was selected from the dashboard and pass it to the view
            if (Session["loanDashboard"] != null)
            {
                loanSelected = (Loan)Session["loanDashboard"];
            }
            else if (Session["oneLoanDashboard"] != null)
            {
                loanSelected = (Loan)Session["oneLoanDashboard"];
            }
            else
            {
                // if there is no loan selected from dashboard -- wrong access
                return RedirectToAction("Login", "UserLogin");
            }
            ViewBag.loanSelected = loanSelected;


            // if user is a normal user, checking the user permission
            if (userData.RoleId == 3)
            {
                if (Session["CurrentLoanRights"] == null || Session["CurrentLoanRights"].ToString() == "")
                {
                    return RedirectToAction("UserDetails", "UserManagement");
                }
                else {
                    var checkPermission = false;
                    string rgts = "";
                    rgts = (string)Session["CurrentLoanRights"];
                    string[] rgtList = null;
                    if (rgts != "")
                    {
                        rgtList = rgts.Split(',');
                    }
                    if (rgtList != null)
                    {
                        foreach (var x in rgtList)
                        {
                            if (x == "U07")
                            {
                                checkPermission = true;
                            }
                        }
                        if (checkPermission == false)
                        {
                            return RedirectToAction("UserDetails", "UserManagement");
                        }
                    }
                    else {
                        return RedirectToAction("UserDetails", "UserManagement");
                    }

                }
            }

            // if user is a dealer user -- he is not allowed to fee page
            else if (userData.RoleId == 4)
            {
                return RedirectToAction("UserDetails", "UserManagement");
            }

            // take the due dates of advance fee, monthly loan fee and lot inspection fee
            string advDuedate;
            string monDueDate;
            string lotDuedate;
            bool returnValue = (new FeeAccess()).GetFeesDueDates(loanDetails.loanId, out advDuedate, out monDueDate, out lotDuedate);

            // pass due dates to view
            ViewBag.advDuedate = advDuedate;
            ViewBag.monDueDate = monDueDate;
            ViewBag.lotDuedate = lotDuedate;


            // return fee page
            return View();
        }
        /// <summary>
        /// CreatedBy:  Kanishka
        /// CreatedDate:02/29/2016
        /// get loan details by loan code
        /// </summary>
        /// <param name="loanCode"></param>
        /// <returns></returns>
        
        
        internal LoanSetupStep1 GetLoanDetailsByLoanCode(string loanCode)
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AutoDealersConnection"].ConnectionString))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand("spGetLoanDetailsByLoanCode", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@loan_code", SqlDbType.VarChar).Value = loanCode;
                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();

                        LoanSetupStep1 loanSetupStep1 = new LoanSetupStep1();


                        while (reader.Read())
                        {
                            loanSetupStep1.loanId = Convert.ToInt32(reader["loan_id"]);
                            loanSetupStep1.advancePercentage = int.Parse(reader["advance"].ToString());
                            loanSetupStep1.autoReminderEmail = reader["auto_remind_email"].ToString();
                            loanSetupStep1.autoReminderPeriod = int.Parse(reader["auto_remind_period"].ToString());
                            loanSetupStep1.defaultUnitType = int.Parse(reader["default_unit_type"].ToString());
                            loanSetupStep1.isEditAllowable = Convert.ToBoolean(reader["is_edit_allowable"].ToString());
                            loanSetupStep1.isInterestCalculate = Convert.ToBoolean(reader["is_interest_calculate"].ToString());
                            loanSetupStep1.loanAmount = Convert.ToDecimal(reader["loan_amount"].ToString());
                            loanSetupStep1.loanNumber = reader["loan_number"].ToString();
                            loanSetupStep1.maturityDate = Convert.ToDateTime(reader["maturity_date"].ToString());
                            loanSetupStep1.nonRegisteredBranchId = int.Parse(reader["non_reg_branch_id"].ToString());
                            loanSetupStep1.paymentMethod = reader["payment_method"].ToString();
                            loanSetupStep1.startDate = Convert.ToDateTime(reader["start_date"].ToString());

                            loanSetupStep1.RegisteredBranchId = Convert.ToInt32(reader["branch_id"].ToString());
                            loanSetupStep1.LoanStatus = Convert.ToBoolean(reader["loan_status"]);
                            loanSetupStep1.RegisteredBranchCode = reader["r_branch_code"].ToString();
                            loanSetupStep1.RegisteredCompanyCode = reader["company_code"].ToString();
                            if(reader["curtailment_due_date"].ToString()== "EoM") {
                                loanSetupStep1.CurtailmentDueDate = "End of Month";
                            }
                            else {
                                string dueDate = reader["curtailment_due_date"].ToString();
                                if (dueDate.Length > 0)
                                {
                                    if (dueDate.Length == 1)
                                    {
                                        if (dueDate.Contains("1"))
                                        {
                                            loanSetupStep1.CurtailmentDueDate = dueDate+ "st of each month";
                                        }
                                        else if (dueDate.Contains("2"))
                                        {
                                            loanSetupStep1.CurtailmentDueDate = dueDate + "nd of each month";
                                        }
                                        else if (dueDate.Contains("3"))
                                        {
                                            loanSetupStep1.CurtailmentDueDate = dueDate + "rd of each month";
                                        }
                                        else
                                        {
                                            loanSetupStep1.CurtailmentDueDate = dueDate + "th of each month";
                                        }
                                    }
                                    else if(dueDate.Length > 1)
                                    {
                                        if (!dueDate.ElementAt(dueDate.Length - 2).ToString().Contains("1"))
                                        {
                                            if (dueDate.ElementAt(dueDate.Length - 1).ToString().Contains("1"))
                                            {
                                                loanSetupStep1.CurtailmentDueDate = dueDate + "st of each month";
                                            }
                                            else if (dueDate.ElementAt(dueDate.Length - 1).ToString().Contains("2"))
                                            {
                                                loanSetupStep1.CurtailmentDueDate = dueDate + "nd of each month";
                                            }
                                            else if (dueDate.ElementAt(dueDate.Length - 1).ToString().Contains("3"))
                                            {
                                                loanSetupStep1.CurtailmentDueDate = dueDate + "rd of each month";
                                            }
                                            else
                                            {
                                                loanSetupStep1.CurtailmentDueDate = dueDate + "th of each month";
                                            }
                                        }
                                        else
                                        {
                                            loanSetupStep1.CurtailmentDueDate = dueDate + "th of each month";
                                        }
                                    }
                                }
                                //loanSetupStep1.CurtailmentDueDate = reader["curtailment_due_date"].ToString()+"th of each month";
                            }
                            //loanSetupStep1.CurtailmentDueDate = reader["curtailment_due_date"].ToString();
                        }

                        reader.Close();

                        IList<UnitType> unittypes = new List<UnitType>();
                        using (SqlCommand cmd2 = new SqlCommand("spGetLoanUnitTypesByLoanId", con))
                        {
                            cmd2.CommandType = CommandType.StoredProcedure;
                            cmd2.Parameters.Add("@loan_id", SqlDbType.Int).Value = loanSetupStep1.loanId;
                            //con.Open();
                            SqlDataReader reader2 = cmd2.ExecuteReader();

                            while (reader2.Read())
                            {
                                UnitType unitType = new UnitType();
                                unitType.unitTypeId = int.Parse(reader2["unit_type_id"].ToString());
                                unitType.unitTypeName = reader2["unit_type_name"].ToString();
                                unittypes.Add(unitType);

                            }
                            loanSetupStep1.selectedUnitTypes = unittypes;

                            return loanSetupStep1;

                        }
                    }
                }


                catch (Exception ex)
                {
                    throw ex;

                }
                finally
                {
                    con.Close();
                    con.Dispose();
                }
            }
        }
        /// <summary>
        /// CreatedBy:Asanka Senarathna
        /// CreatedDate:6/27/2016
        /// Get Active Loans for Inactive
        /// </summary>
        /// <param name="company_Id"></param>
        /// <param name="branchId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public LoanSelection GetActiveLoanforInactive( int companyId, int branchId, int roleId)
        {
            LoanSelection detailList = new LoanSelection();
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();

            paramertList.Add(new object[] { "@companyId", companyId });
            paramertList.Add(new object[] { "@branchId", branchId });
            paramertList.Add(new object[] { "@roleId", roleId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetActiveLoansforInactive", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0)
                {
                    List<Branch> RegBranches = new List<Branch>();
                    List<NonRegBranch> NonRegBranchList = new List<NonRegBranch>();
                    List<LoanSetupStep1> LoanList = new List<LoanSetupStep1>();

                    foreach (DataRow dataRow in dataSet.Tables[0].Rows)
                    {
                        Branch branch = new Branch();
                        NonRegBranch nonRegBranch = new NonRegBranch();
                        LoanSetupStep1 loan = new LoanSetupStep1();

                        branch.BranchId = int.Parse(dataRow["branch_id"].ToString());
                        branch.BranchName = dataRow["regBranchName"].ToString();

                        nonRegBranch.NonRegBranchId = int.Parse(dataRow["non_reg_branch_id"].ToString());
                        nonRegBranch.BranchId = branch.BranchId;
                        nonRegBranch.CompanyNameBranchName = dataRow["nonRegBranchName"].ToString();

                        loan.loanId = int.Parse(dataRow["loan_id"].ToString());
                        loan.loanNumber = dataRow["loan_number"].ToString();
                        loan.loanCode = dataRow["loan_code"].ToString();
                        loan.loanAmount = decimal.Parse(dataRow["loan_amount"].ToString());
                        loan.CreatedDate = DateTime.Parse(dataRow["created_date"].ToString());
                        loan.startDate = DateTime.Parse(dataRow["start_date"].ToString());
                        loan.maturityDate = DateTime.Parse(dataRow["maturity_date"].ToString());
                        loan.CurrentLoanStatus = bool.Parse(dataRow["loan_status"].ToString());

                        loan.nonRegisteredBranchId = nonRegBranch.NonRegBranchId;
                        bool checkBranch = false;
                        bool checkNonRegBranch = false;
                        bool checkLoan = false;
                        foreach (var br in RegBranches)
                        {
                            if (br.BranchId == branch.BranchId)
                            {
                                checkBranch = true;
                            }
                        }
                        if (checkBranch == false)
                        {
                            RegBranches.Add(branch);
                        }
                        foreach (var nrbr in NonRegBranchList)
                        {
                            if (nrbr.NonRegBranchId == nonRegBranch.NonRegBranchId)
                            {
                                checkNonRegBranch = true;
                            }
                        }
                        if (checkNonRegBranch == false)
                        {
                            NonRegBranchList.Add(nonRegBranch);
                        }

                        foreach (var l in LoanList)
                        {
                            if (l.loanId == loan.loanId)
                            {
                                checkLoan = true;
                            }
                        }
                        if (checkLoan == false)
                        {
                            LoanList.Add(loan);
                        }

                    }
                    detailList.RegBranches = RegBranches;
                    detailList.NonRegBranchList = NonRegBranchList;
                    detailList.LoanList = LoanList;

                    return detailList;
                }
                else
                {
                    return null;
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
            /*
        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;
            }
        }