/// <summary>
        /// CreatedBy:  Kasun
        /// CreatedDate:05/04/2016
        /// 
        /// get loan details by loan code
        /// </summary>
        /// <param name="loanCode"></param>
        /// <returns></returns>
        public Loan GetLoanByLoanCode(int loanId,string loanCode)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@loan_code", loanCode });
            paramertList.Add(new object[] { "@loan_id", loanId });

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

                    loan.LoanId = Convert.ToInt32(dataRow["loan_id"]);
                    loan.LoanAmount = Convert.ToDecimal(dataRow["loan_amount"]);
                    loan.LoanCode = dataRow["loan_code"].ToString();
                    loan.MaturityDate = Convert.ToDateTime(dataRow["maturity_date"]);
                    loan.StartDate = Convert.ToDateTime(dataRow["start_date"]);
                    loan.LoanStatus = Convert.ToBoolean(dataRow["loan_status"]);                    
                    loan.LoanNumber = dataRow["loan_number"].ToString();

                    return loan;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Created by : kasun
        /// CreatedDate:05/04/2016
        /// 
        /// Loan Renew date insert(update maturity date)
        /// </summary>
        /// <param name="l"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool LoanRenew(Loan l, int userId) {

            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["AutoDealersConnection"].ToString()))
            {
                try
                {
                    var command = new SqlCommand("spUpdateLoanRenewalDateByLoanId", con);
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@user_id", userId);
                    command.Parameters.AddWithValue("@loan_id", l.LoanId);
                    command.Parameters.AddWithValue("@loan_code", l.LoanCode);
                    command.Parameters.AddWithValue("@maturity_date", l.MaturityDate);
                    command.Parameters.AddWithValue("@renewal_date", l.RenewalDate);
                    command.Parameters.AddWithValue("@changed_date", DateTime.Now);

                    SqlParameter returnParameter = command.Parameters.Add("@ReturnValue", SqlDbType.Bit);
                    returnParameter.Direction = ParameterDirection.ReturnValue;

                    con.Open();
                    command.ExecuteNonQuery();

                    if ((int)returnParameter.Value > 0)
                    {
                        return true;
                    }
                    else {
                        return false;
                    }
                    
                }
                catch (Exception ex)
                {
                    throw ex;

                }
            }
        }
        /// <summary>
        /// CreatedBy: Piyumi
        /// CreatedDate: 3/30/2016
        /// get loan details
        /// </summary>
        /// <param name="id"></param>
        /// <param name="role"></param>
        /// <returns>Loan</returns>
        public Loan GetLoanDetails(int id,int role)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            paramertList.Add(new object[] { "@para", id });
            paramertList.Add(new object[] { "@role", role });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetLoan", paramertList);
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    Loan loanObj = new Loan();
                    loanObj.LoanNumber = dataSet.Tables[0].Rows[0]["loan_number"].ToString();
                    //loanObj.PartnerName = dataSet.Tables[0].Rows[0]["company_name"].ToString()+" - " + dataSet.Tables[0].Rows[0]["non_reg_branch_name"].ToString(); comment by asanka
                    loanObj.PartnerName =  dataSet.Tables[0].Rows[0]["non_reg_branch_name"].ToString();
                    loanObj.LoanCode = dataSet.Tables[0].Rows[0]["loan_code"].ToString();

                    loanObj.PartnerType = int.Parse(dataSet.Tables[0].Rows[0]["company_type"].ToString());
                    loanObj.BranchName = dataSet.Tables[0].Rows[0]["branch_name"].ToString();
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["is_title_tracked"].ToString()))
                    {
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["is_title_tracked"].ToString()))
                        {
                            loanObj.IsTitleTrack = 1;
                        }
                        else
                        {
                            loanObj.IsTitleTrack = 0;
                        }
                    }
                      
                    else
                    {
                        loanObj.IsTitleTrack = 0;
                    }
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["has_lot_inspection_fee"].ToString()))
                    {
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["has_lot_inspection_fee"].ToString()))
                        {
                            loanObj.LotInspectionFee = 1;
                        }
                        else
                        {
                            loanObj.LotInspectionFee = 0;
                        }
                    }

                    else
                    {
                        loanObj.LotInspectionFee = 0;
                    }
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["has_monthly_loan_fee"].ToString()))
                    {
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["has_monthly_loan_fee"].ToString()))
                        {
                            loanObj.MonthlyLoanFee = 1;
                        }
                        else
                        {
                            loanObj.MonthlyLoanFee = 0;
                        }
                    }

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

                    else
                    {
                        loanObj.AdvanceFee = 0;
                    }
                    if (role == 3)
                    {
                        if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["right_id"].ToString()))
                        {
                            loanObj.Rights = dataSet.Tables[0].Rows[0]["right_id"].ToString();
                        }
                       
                    }

                    loanObj.NonRegBranchId = int.Parse(dataSet.Tables[0].Rows[0]["non_reg_branch_id"].ToString());
                    loanObj.LoanId = int.Parse(dataSet.Tables[0].Rows[0]["loan_id"].ToString());

                    return loanObj;

                }
                return null;
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Frontend page: Advance Unit
        /// Title: Advance more than one unit
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 02/25/2016
        /// CreatedBy : Nadeeka
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Return partial view</returns>
        public int UpdateAdvanceAll(ListViewModel list)
        {           
            string loanCode;
            try
            {
                //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                throw;
            }
            //get loan details by loan code
            LoanSetupStep1 loanSetupStep1 = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);
            ViewBag.ErrorMsg = "";
            //check Session["notAdvancedList"] is not null
            if (Session["notAdvancedList"] != null)
            {
                List<Models.Unit> lstUnit = (List<Models.Unit>)Session["notAdvancedList"];
                foreach (Models.Unit modifiedUnit in list.ItemList)
                {
                    //check advance amount can not be edited and given advance amount in loanset up and advance amount of selected unit is equal
                    if (!loanSetupStep1.isEditAllowable && lstUnit.Find(a => a.UnitId == modifiedUnit.UnitId).AdvanceAmount != modifiedUnit.AdvanceAmount)
                    {
                        TempData["updateReslt"] = 3;
                        return 0;
                    }
                }

            }

            UnitAccess unitAccess = new UnitAccess();
            //get result of advance item list
            int reslt = unitAccess.AdvanceItemList(list.ItemList, loanSetupStep1.loanId, userData.UserId, list.ItemList[0].AdvanceDate);
            TempData["updateReslt"] = reslt;

            // after success save**
            if (reslt == 1)
            {
                string[] arrList = new string[list.ItemList.Count];
                int i = 0;
                foreach (var x in list.ItemList)
                {
                    if (!string.IsNullOrEmpty(x.UnitId))
                    {
                        arrList[i] = "Advanced Unit: " + x.IdentificationNumber + " ,Advance amount:" + x.AdvanceAmount + " ,Advance date: " + x.AdvanceDate;
                        i++;
                    }
                }
                
         
                string units = string.Join(",", arrList);
                //insert log data
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanSetupStep1.loanId, "Advance Unit", units, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);
                //if mention advance fee, then insert in to fee table - asanka
                if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                {
                    Loan loanObj = new Loan();
                    if (Session["loanDashboard"] != null)
                    {
                        loanObj = (Loan)Session["loanDashboard"];
                    }
                    else
                    {
                        loanObj = (Loan)Session["oneLoanDashboard"];
                    }
                        //loanObj = (Loan)Session["loanDashboard"]; 
                    if (loanObj.AdvanceFee == 1)
                    {
                        //check advance amount and other details
                        foreach (BankLoanSystem.Models.Unit unitObj in list.ItemList)
                        {
                            unitAccess.insertFreeDetailsForAdvance(unitObj, loanSetupStep1.loanId);
                        }
                    }
                }

                // saving for reporting purpose
                if (Session["AdvItems"] == null)
                {
            Session["AdvItems"] = list.ItemList;
            }
            else
            {
                List<Models.Unit> unitlist = new List<Models.Unit>();
                unitlist = (List<Models.Unit>)Session["AdvItems"];
                unitlist.AddRange(list.ItemList);
                Session["AdvItems"] = unitlist;
            }
            }
            return reslt;        
        }
        /// <summary>
        /// Frontend page: Advance Unit
        /// Title: Advance one unit
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 02/24/2016
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Return partial view</returns>
        public int UpdateAdvance(BankLoanSystem.Models.Unit unit)
        {            
            string loanCode;
            try
            {
                //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            catch (Exception)
            {
                throw;
            }
            //get loan details by loan code
            LoanSetupStep1 loanSetupStep1 = (new LoanSetupAccess()).GetLoanDetailsByLoanCode(loanCode);           
            ViewBag.ErrorMsg = "";
            UnitAccess unitAccess = new UnitAccess();
            //check Session["notAdvancedList"] is not null
            if (Session["notAdvancedList"] != null)
            {
                //convert Session["notAdvancedList"] to list object
                List<Models.Unit> lstUnit = (List<Models.Unit>)Session["notAdvancedList"];
                //check advance amount can not be edited and given advance amount in loanset up and advance amount of selected unit is equal
                if(!loanSetupStep1.isEditAllowable && lstUnit.Find(a => a.UnitId == unit.UnitId).AdvanceAmount != unit.AdvanceAmount)
                {
                   
                    TempData["updateReslt"] = 3;
                    return 3;
                    
                }
                
            }
            //get result of advance one item
            int reslt = unitAccess.AdvanceItem(unit, loanSetupStep1.loanId, userData.UserId, unit.AdvanceDate);
            TempData["updateReslt"] = reslt;

            // after success save**
            //check result of advance
            if (reslt == 1)
            {
                //if mention advance fee, then insert in to fee table - asanka
                if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                {
                    Loan loanObj = new Loan();
                    if(Session["loanDashboard"] != null){
                        loanObj = (Loan)Session["loanDashboard"];
                    }
                    else if (Session["oneLoanDashboard"] != null)
                    {
                        loanObj = (Loan)Session["oneLoanDashboard"];
                    }
                    if (loanObj.AdvanceFee == 1)
                    {
                        //check advance amount and other details
                        unitAccess.insertFreeDetailsForAdvance(unit, loanSetupStep1.loanId);
                    }
                }

                //insert to log 
                
                Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, loanSetupStep1.loanId, "Advance Unit", "Advanced Unit:" + unit.IdentificationNumber + (unit.Cost * loanSetupStep1.advancePercentage / 100 != unit.AdvanceAmount ? ",Advance amount edited to: " + unit.AdvanceAmount : ",Advance amount: " + unit.AdvanceAmount) + " ,Advance date:" + unit.AdvanceDate, DateTime.Now);

                int islog = (new LogAccess()).InsertLog(log);
                // saving for reporting purpose
                if (Session["AdvItems"] == null)
            {
                List<Models.Unit> unitlist = new List<Models.Unit>();
                unitlist.Add(unit);
                Session["AdvItems"] = unitlist;
            }
            else
            {
                List<Models.Unit> unitlist = new List<Models.Unit>();
                unitlist = (List<Models.Unit>)Session["AdvItems"];
                unitlist.Add(unit);
                Session["AdvItems"] = unitlist;
            }
            }
           

            return reslt;
        }
        /// <summary>
        /// CreatedBy : Piyumi
        /// CreatedDate: 2016/04/20
        /// 
        /// edit loan
        /// 
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult EditLoan()
        {
            Session.Remove("popUpSelectionType");
            Loan loan = new Loan();
            if (Session["oneLoanDashboard"] != null)
            {
                loan = (Loan)Session["oneLoanDashboard"];
                //Session.Remove("oneLoanDashboard");
            }
            if (Session["loanDashboardAssignUser"] != null)
            {
                loan = (Loan)Session["loanDashboardAssignUser"];
            }
            if (Session["loanDashboardEditLoan"] != null)
            {
                loan = (Loan)Session["loanDashboardEditLoan"];
            }
            if (TempData["EditReslt"] != null)
            {
                if ((string)TempData["EditReslt"] == "success")
                {
                    ViewBag.SuccessMsg = "Loan Status Successfully Updated";
                    if ((Session["loanDashboardEditLoan"] != null) && (Session["loanDashboardEditLoan"].ToString() != ""))
                    {
                        loan.CurrentLoanStatus = true;
                    }

                    Session["loanDashboardEditLoan"] = loan;
                    //loan = new Loan();
                    //return View(loan);
                }
                else if ((string)TempData["EditReslt"] == "failed")
                {
                    ViewBag.ErrorMsg = "Failed To Update Loan Status";
                }
            }
            if ((Session["loanDashboardEditLoan"] != null)&&(Session["loanDashboardEditLoan"].ToString()!=""))
            {
            
                
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(loan);
                }
                else
                {

                    return View(loan);
                }
                //return View();
            }
            else {
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return RedirectToAction("UserDetails");
                }
                else
                {

                    return RedirectToAction("UserDetails");
                }
            }
            //return View();
        }
        /// <summary>
        /// Frontend page: Assign rights
        /// Title: Assign new rights for a loan for users and edit rights
        /// Designed : Kasun Samarawickrama
        /// User story: 
        /// Developed: Kasun Samarawickrama
        /// Date created: 
        /// </summary>
        /// <returns></returns>
        public ActionResult AssignRights()
        {
            Session.Remove("popUpSelectionType");
            Loan loan = new Loan();
            // get loan details from session
            if (Session["oneLoanDashboard"] != null)
            {
                loan = (Loan)Session["oneLoanDashboard"];
                //Session.Remove("oneLoanDashboard");
            }
            if (Session["loanDashboardAssignUser"] != null)
            {
                loan = (Loan)Session["loanDashboardAssignUser"];
            }
            //check from submission 
            if (TempData["submit"] != null) {
                if ((string)TempData["submit"] == "success") {
                    ViewBag.SuccessMsg = "User Rights Successfully Updated";
                }
                else if ((string)TempData["submit"] == "failed")
                {
                    ViewBag.ErrorMsg = "Failed To Update User Rights";
                }
            }
            // check loan null or not
            if (Session["oneLoanDashboard"] != null || Session["loanDashboardAssignUser"] != null)
            {
                ViewBag.LoanId = loan.LoanId;
                ViewBag.LoanNumber = loan.LoanNumber;
                UserManageAccess ua = new UserManageAccess();

                // get user list for that branch
                List<User> userList = ua.getUsersByRoleBranch(3, loan.BranchId);
                List<User> tempRoleList = new List<User>();

                // add users to select list for front end 
                for (int i = 0; i < userList.Count; i++)
                {
                    User tempRole = new User()
                    {
                        UserId = userList[i].UserId,
                        UserName = userList[i].UserName
                    };
                    tempRoleList.Add(tempRole);
                }
                ViewBag.userSelectList = tempRoleList;

                User user = new Models.User();
                List<Right> list = new List<Right>();

                user.UserRightsList = new List<Right>();

                // retrive all rights from table
                list = (new UserRightsAccess()).getRights();

                // check title track yes or no.
                if ( loan.IsTitleTrack !=  1)
                {
                    foreach (var x in list)
                    {
                        // title page right
                        if (x.rightId != "U02")
                        {
                            user.UserRightsList.Add(x);
                        }
                    }
                }

                else {
                    user.UserRightsList = list;
                }

                //get all report list
                
                List<Right> ReportRightsList = (new UserRightsAccess()).getReportRights();
                user.ReportRightsList = new List<Right>();
                // filter report rights according to the loan
                if (ReportRightsList != null && ReportRightsList.Count > 0)
                {
                    foreach (Right rgt in ReportRightsList)
                    {
                        //Check dealer user can view the report
                        if (!rgt.UserView)
                        {
                            continue;
                        }
                        else
                        {
                            //check title need not to be tracked for selected loan and report right for Title Status
                            if ((loan.IsTitleTrack == 0) && (rgt.rightId == "R04"))
                            {
                                //if title need not to be tracked report right for Title Status is not added to right list
                                continue;
                            }
                            //check there is no advance fee for selected loan and report right for advance fee invoice and advance fee receipt
                            if ((loan.AdvanceFee == 0) && ((rgt.rightId == "R07") || (rgt.rightId == "R08")))
                            {
                                //if there is no advance fee, report right for advance fee invoice and advance fee receipt are not added to right list
                                continue;
                            }
                            //check there is no monthly loan fee for selected loan and report right for monthly loan fee invoice and monthly loan fee receipt
                            if ((loan.MonthlyLoanFee == 0) && ((rgt.rightId == "R09") || (rgt.rightId == "R10")))
                            {
                                //if there is no monthly loan fee, report right for monthly loan fee invoice and monthly loan fee receipt are not added to right list
                                continue;
                            }
                            //check there is no lot inspection fee for selected loan and report right for lot inspection fee invoice and lot inspection fee receipt
                            if ((loan.LotInspectionFee == 0) && ((rgt.rightId == "R11") || (rgt.rightId == "R12")))
                            {
                                //if there is no lot inspection fee, report right for lot inspection fee invoice and lot inspection fee receipt are not added to right list
                                continue;
                            }
                        }
                        user.ReportRightsList.Add(rgt);
                    }
                }
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return PartialView(user);
                }
                else
                {
           
                    return View(user);
                }
                //return View();
            }
            else {
            if (HttpContext.Request.IsAjaxRequest())
            {
                ViewBag.AjaxRequest = 1;
                    return RedirectToAction("UserDetails");
            }
            else
            {

                    return RedirectToAction("UserDetails");
                }
            }
        }
        ///<summary>
        /// Frontend page: Inactive Loan
        /// Title: create view and get active loan details for inactive
        /// Designed : Asanka Senarathna
        /// User story: DFP-103
        /// Developed: Asanka Senarathna
        /// Date created: 6/27/2016
        ///</summary>

        public ActionResult InactiveLoan()
        {
            Session.Remove("popUpSelectionType");
            Loan loan = new Loan();
            // If session not null then assign value to loan object
            if (Session["oneLoanDashboard"] != null)
            {
                loan = (Loan)Session["oneLoanDashboard"];
            }
            if (Session["loanDashboardAssignUser"] != null)
            {
                loan = (Loan)Session["loanDashboardAssignUser"];
            }
            if (Session["loanDashboardActiveLoanInact"] != null)
            {
                loan = (Loan)Session["loanDashboardActiveLoanInact"];
            }
            if (TempData["EditReslt"] != null)
            {
                //Check pass value in view and display message
                if ((string)TempData["EditReslt"] == "success")
                {
                    ViewBag.SuccessMsg = "Loan Status Successfully Updated";
                    if ((Session["loanDashboardActiveLoanInact"] != null) && (Session["loanDashboardActiveLoanInact"].ToString() != ""))
                    {
                        loan.CurrentLoanStatus = true;
                    }

                    Session["loanDashboardActiveLoanInact"] = loan;
                }
                else if ((string)TempData["EditReslt"] == "failed")
                {
                    ViewBag.ErrorMsg = "Failed To Update Loan Status";
                }
            }
            if ((Session["loanDashboardActiveLoanInact"] != null) && (Session["loanDashboardActiveLoanInact"].ToString() != ""))
            {

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

                    return View(loan);
                }
            }
            else {
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return RedirectToAction("UserDetails");
                }
                else
                {
                    return RedirectToAction("UserDetails");
                }
            }
        }
        /// <summary>
        /// Frontend Page:Bottom Link Bar of each page in floor plan management section
        /// Title: return view according to user rights and loan setup details
        /// Designed: Irfan MAM
        /// User Story:
        /// Developed: Piyumi Perera
        /// Date created:
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLinkBar()
        {
        //assign logged user id to int variable
            int userId = userData.UserId;
            string loanCode = "";

            UserRightsAccess access = new UserRightsAccess();

            //retrive all rights
            List<Right> rights = new List<Right>();
            //assign logged user role to int variable
            int userRole = userData.RoleId;
            //check Session["loanCode"] is not null and not empty
            if ((Session["loanCode"] != null) && (!string.IsNullOrEmpty(Session["loanCode"].ToString())))
            {
            //convert session to string variable
                loanCode = Session["loanCode"].ToString();
            }
            //check user role is user
            if (userRole == 3)
            {
            //retrieve rigts given for the loan 
                rights = access.GetUserRightsByLoanCode(loanCode, userId);
            }
            //assign user role to viewbag variable
            ViewBag.Role = userRole;

            //check Session["addUnitloan"] is null
            if (Session["addUnitloan"] == null)
            {
            //return to login page
                return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });
            }
            //convert session to loan object
            LoanSetupStep1 loan = (LoanSetupStep1)Session["addUnitloan"];
            //check  Session["IsTitleTrack"] is not null
            if (Session["IsTitleTrack"] != null)
            {
            //check session value
                if (int.Parse(Session["IsTitleTrack"].ToString())==1)
                    {
                    //if 1 - title need to be tracked
                        ViewBag.ttlAccess = 1;
                    }
                    else
                    {
                    //else title no need to be tracked
                        ViewBag.ttlAccess = 0;

                    }
                
                
            }
            else
            {
                //else title no need to be tracked
                ViewBag.ttlAccess = 0;

            }
            //check Session["oneLoanDashboard"] which contains loan data if logged user has one loan is not null and not empty
            if ((Session["oneLoanDashboard"] != null) && (!string.IsNullOrEmpty(Session["oneLoanDashboard"].ToString())))
            {
                Loan loanObj = new Loan();
                //convert session to loan object
                    loanObj = (Loan)Session["oneLoanDashboard"];
                    //check if loan has at least one fee
                if ((loanObj.LotInspectionFee == 1) || (loanObj.MonthlyLoanFee == 1) || (loanObj.AdvanceFee == 1))
                    {
                    //assign value 1 for ViewBag.FeeLB
                    ViewBag.FeeLB = 1;
                    }
                    else
                    {
                    //assign value 0 for ViewBag.FeeLB
                    ViewBag.FeeLB = 0;
                    }
            }
            //check Session["loanDashboard"] which contains loan data if logged user select in popup is not null and not empty
            else if ((Session["loanDashboard"] != null) && (!string.IsNullOrEmpty(Session["loanDashboard"].ToString())))
            {
                Loan loanObj = new Loan();
                //convert session to loan object
                loanObj = (Loan)Session["loanDashboard"];
                //check if loan has at least one fee
                if ((loanObj.LotInspectionFee == 1) || (loanObj.MonthlyLoanFee == 1) || (loanObj.AdvanceFee == 1))
                {
                    //assign value 1 for ViewBag.FeeLB
                    ViewBag.FeeLB = 1;
                }
                else
                {
                    //assign value 0 for ViewBag.FeeLB
                    ViewBag.FeeLB = 0;
                }
            }
            //check Session["loanDashboard"] and check Session["oneLoanDashboard"] is null
            else if ((Session["oneLoanDashboard"] == null) && (Session["loanDashboard"] == null))
            {
            //return to login page
                return RedirectToAction("UserLogin", "Login");
            }
            //return right list to partial view
            return PartialView(rights);

        }
        public ActionResult setLoanCode(string loanCode)//, string action
        {

            Session["loanCode"] = loanCode;
            if (loanCode == null || Session["detail"] == null)
            {

                // if request come without select the list of loans
                if(Session["detail"] == null && loanCode != null && loanCode != "")
                {
                   Loan loan = (new DashBoardAccess()).GetALoanDetailsbyLoanCode(loanCode, userData.RoleId,userData.UserId);
                    Session["loanDashboard"] = loan;
                    if (userData.RoleId == 3)
                    {
                        Session["CurrentLoanRights"] = loan.Rights;

                        
                    }
                }


                return RedirectToAction("UserDetails");
            }
            LoanSelection list3 = (LoanSelection)Session["detail"];
            Loan finalSelectedLoan = new Loan();
            foreach (var l in list3.LoanList)
            {
                if (l.loanCode == loanCode)
                {
                    if (userData.RoleId == 3)
                    {
                        string permission = "";
                        List<Right> permissionString = (new UserRightsAccess()).getRightsString(userData.UserId, l.loanId);
                        if (permissionString.Count >= 1)
                        {
                            permission = permissionString[0].rightsPermissionString;
                            Session["CurrentLoanRights"] = permission;
                        }
                        else {
                            Session["CurrentLoanRights"] = "";
                        }
                    }
                    finalSelectedLoan.NonRegBranchId = l.nonRegisteredBranchId;
                    finalSelectedLoan.LoanId = l.loanId;
                    finalSelectedLoan.LoanNumber = l.loanNumber;
                    finalSelectedLoan.LoanCode = l.loanCode;
                    finalSelectedLoan.Rights = l.rightId;
                    finalSelectedLoan.AdvanceFee = l.AdvanceFee;
                    finalSelectedLoan.MonthlyLoanFee = l.MonthlyLoanFee;
                    finalSelectedLoan.LotInspectionFee = l.LotInspectionFee;
                    if (l.titleTracked == true)
                    {
                        finalSelectedLoan.IsTitleTrack = 1;
                    }
                    else {
                        finalSelectedLoan.IsTitleTrack = 0;
                    }
                    //finalSelectedLoan.IsTitleTrack =
                    //for edit loan
                    finalSelectedLoan.CurrentLoanStatus = l.CurrentLoanStatus;
                    finalSelectedLoan.CreatedDate = l.CreatedDate;
                    finalSelectedLoan.StartDate = l.startDate;
                    finalSelectedLoan.MaturityDate = l.maturityDate;
                    finalSelectedLoan.LoanAmount = l.loanAmount;
                    foreach (var nrbr in list3.NonRegBranchList)
                    {
                        if (nrbr.NonRegBranchId == l.nonRegisteredBranchId)
                        {
                            finalSelectedLoan.BranchId = nrbr.BranchId;
                            finalSelectedLoan.PartnerName = nrbr.CompanyNameBranchName;

                            foreach (var br in list3.RegBranches)
                            {
                                if (br.BranchId == finalSelectedLoan.BranchId)
                                {
                                    finalSelectedLoan.BranchName = br.BranchName;
                                }
                            }
                        }
                    }
                    if ((string)Session["popUpSelectionType"] == "linkDealer")
                    {
                        Session["loanDashboardJoinDealer"] = finalSelectedLoan;
                    } else if ((string)Session["popUpSelectionType"] == "assignRights")
                    {
                        Session["loanDashboardAssignUser"] = finalSelectedLoan;

                    }
                    else if ((string)Session["popUpSelectionType"] == "tidenaol")
                    {
                        Session["loanDashboardEditLoan"] = finalSelectedLoan;

                    }
                    else if ((string)Session["popUpSelectionType"] == "tcaninaol")
                    {
                        Session["loanDashboardActiveLoanInact"] = finalSelectedLoan;

                    }
                    else if ((string)Session["popUpSelectionType"] == "aticno")
                    {
                        Session["loanDashboardRenewLoan"] = finalSelectedLoan;

                    }
                    else {
                        Session["loanDashboard"] = finalSelectedLoan;
                    }
                }
            }
            Session["detail"] = null;
            if ((string)Session["popUpSelectionType"] == "assignRights")
            {
                return RedirectToAction("AssignRights");
            }
            else if ((string)Session["popUpSelectionType"] == "linkDealer")
            {
                return RedirectToAction("../CreateDealer/LinkDealer");
            }
            else if ((string)Session["popUpSelectionType"] == "tidenaol")
            {
                return RedirectToAction("EditLoan");
            }
            else if ((string)Session["popUpSelectionType"] == "tcaninaol")
            {
                return RedirectToAction("InactiveLoan");
            }
            else if ((string)Session["popUpSelectionType"] == "aticno")
            {
                return RedirectToAction("RenewLoan", "LoanManagement");
            }
            else
            {
                return RedirectToAction("UserDetails");
            }
            //return RedirectToAction(action);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult RenewLoan()
        {

            Session.Remove("popUpSelectionType");
            Loan loan = new Loan();
            if ((Session["loanDashboardRenewLoan"] != null) && (Session["loanDashboardRenewLoan"].ToString() != ""))
            {

                loan = (Loan)Session["loanDashboardRenewLoan"];

                if (TempData["message"] != null && (string)TempData["message"] != "")
                {
                    string str = (string)TempData["message"];
                    if (str == "success")
                    {
                        ViewBag.SuccessMsg = "success";
                    }
                    else {
                        ViewBag.ErrorMsg = "fail";
                    }
                    Loan loanUpdated = new Loan();
                    loanUpdated = (new LoanManagementAccess()).GetLoanByLoanCode(loan.LoanId,loan.LoanCode);
                    loanUpdated.CreatedDate = loan.CreatedDate;
                    loanUpdated.PartnerName = loan.PartnerName;
                    loanUpdated.BranchName = loan.BranchName;

                    loan.MaturityDate = loanUpdated.MaturityDate;
                    Session["loanDashboardRenewLoan"] = loan;

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

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

                        return View(loan);
                    }
                }
               
                //return View();
            }
            else {
                if (HttpContext.Request.IsAjaxRequest())
                {
                    ViewBag.AjaxRequest = 1;
                    return RedirectToAction("UserDetails","UserManagement");
                }
                else
                {

                    return RedirectToAction("UserDetails", "UserManagement");
                }
            }
        }
        public ActionResult RenewLoan(Loan l) {

            Loan loanPost = new Loan();
            if ((Session["loanDashboardRenewLoan"] != null) && (Session["loanDashboardRenewLoan"].ToString() != ""))
            {
                loanPost = (Loan)Session["loanDashboardRenewLoan"];
                loanPost.RenewalDate = l.RenewalDate;
            }

            if ((new LoanManagementAccess()).LoanRenew(loanPost, userData.UserId)) {
                //Trace the action - create a new record for log table
                Log log = new Log(userData.UserId, userData.Company_Id, loanPost.BranchId, loanPost.LoanId, "Renew Loan", "Renew Loan Number" + loanPost.LoanNumber + " , Renewal Date: " + loanPost.RenewalDate, DateTime.Now);

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

                TempData["message"] = "success";
            }
            else {
                TempData["message"] = "fail";
            }

            return RedirectToAction("RenewLoan");
        }
        /// <summary>
        /// Frontend page: Join Dealer
        /// Title: view of Link Dealer page
        /// Designed: Nadeeka
        /// User story:
        /// Developed: Nadeeka
        /// Date created: 2016/03/30
        /// Edited: Piyumi Perera
        /// </summary>
        /// <returns></returns>
        public ActionResult LinkDealer()
        {
            //Check result of Join Dealer page
            if(TempData["msg"] !=null )
            {
                //Check TempData["msg"] is 1
                if (TempData["msg"].ToString() == "1")
                {
                    ViewBag.SuccessMsg = "User Successfully Created";
                }
                //Check TempData["msg"] is 2
                else if (TempData["msg"].ToString() == "2")
                {
                    ViewBag.Error = "Error";
                }
            }
            CompanyAccess ca = new CompanyAccess();
            BranchAccess ba = new BranchAccess();
            Loan loan = new Loan();
            //Check Session["oneLoanDashboard"] is not null
            if (Session["oneLoanDashboard"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["oneLoanDashboard"];
            }
            //Check Session["loanDashboardJoinDealer"] is not null
            if (Session["loanDashboardJoinDealer"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["loanDashboardJoinDealer"];
            }
            //remove Session["popUpSelectionType"]
            Session.Remove("popUpSelectionType");
           //return non registered branch details by non registered branch id
            NonRegBranch nonRegBranches = ba.getNonRegBranchByNonRegBranchId(loan.NonRegBranchId);
            ViewBag.nonRegBranches = nonRegBranches.BranchName;
            ViewBag.nonRegCompany = nonRegBranches.CompanyNameBranchName;
            List<User> userList = new List<User>();
            //return all users of given company id
            userList = (new UserAccess()).GetUserListByCompany(userData.Company_Id);
            //filter user list who has authorization for selected loan
            userList = userList.FindAll(t => t.BranchId == loan.BranchId || (t.BranchId ==0 && t.RoleId==1));
            ViewBag.UserIdForSendReq = new SelectList(userList, "UserId", "UserName");

            //get report list for dealer user
            List<Right> ReportRightsList = new List<Right>();
            User us = new User();
            us.ReportRightsList = new List<Right>();
            ReportRightsList = (new UserRightsAccess()).getReportRights();
            if(ReportRightsList!=null && ReportRightsList.Count > 0)
            {
                foreach (Right rgt in ReportRightsList)
                {
                    //Check dealer user can view the report
                    if(!rgt.DealerView)
                    {
                        continue;
                    }
                    else
                    {
                        //check title need not to be tracked for selected loan and report right for Title Status
                        if ((loan.IsTitleTrack == 0) && (rgt.rightId=="R04"))
                        {
                            //if title need not to be tracked report right for Title Status is not added to right list
                            continue;
                        }
                        //check there is no advance fee for selected loan and report right for advance fee invoice and advance fee receipt
                        if ((loan.AdvanceFee == 0) && ((rgt.rightId == "R07")||(rgt.rightId == "R08")))
                        {
                            //if there is no advance fee, report right for advance fee invoice and advance fee receipt are not added to right list
                            continue;
                        }
                        //check there is no monthly loan fee for selected loan and report right for monthly loan fee invoice and monthly loan fee receipt
                        if ((loan.MonthlyLoanFee == 0) && ((rgt.rightId == "R09") || (rgt.rightId == "R10")))
                        {
                            //if there is no monthly loan fee, report right for monthly loan fee invoice and monthly loan fee receipt are not added to right list
                            continue;
                        }
                        //check there is no lot inspection fee for selected loan and report right for lot inspection fee invoice and lot inspection fee receipt
                        if ((loan.LotInspectionFee == 0) && ((rgt.rightId == "R11") || (rgt.rightId == "R12")))
                        {
                            //if there is no lot inspection fee, report right for lot inspection fee invoice and lot inspection fee receipt are not added to right list
                            continue;
                        }
                    }
                    us.ReportRightsList.Add(rgt);
                }
            }
            //Check user is super admin
            if (userData.RoleId == 1)
            {
                //convert user list to session object
                Session["UserReqList"] = userList;
            }
            //Check user is admin
            else if (userData.RoleId == 2)
            {
                //convert user list to session object
                Session["UserReqList"] = userList;
            }
            else
            {
                //return to dashboard
                return RedirectToAction("UserDetails", "UserManagement");
            }
            return View(us);
        }
        public ActionResult LinkDealer(DealerUserModel user)
        {
            //initialize properties of user object
            user.PhoneNumber = user.PhoneNumber2;
            user.CreatedBy = userData.UserId;
            user.IsDelete = false;
            user.Status = true;
            user.Company_Id = userData.Company_Id;
            user.BranchId = userData.BranchId;
            user.RoleId = 4;
            user.Email = user.NewEmail;

            BranchAccess ba = new BranchAccess();
            Loan loan = new Loan();
            //Check Session["oneLoanDashboard"] is not null
            if (Session["oneLoanDashboard"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["oneLoanDashboard"];
                
            }
            //Check Session["loanDashboardJoinDealer"] is not null
            if (Session["loanDashboardJoinDealer"] != null)
            {
                //convert session object to loan object
                loan = (Loan)Session["loanDashboardJoinDealer"];
            }
            //initialize non registered branch id
            user.NonRegBranchId = loan.NonRegBranchId;
            //initialize loan id
            user.LoanId = loan.LoanId;
            //encrypt given password
            string passwordTemp = user.Password;

            UserAccess ua = new UserAccess();

            string newSalt = PasswordEncryption.RandomString();
            user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt);
            user.ActivationCode = Guid.NewGuid().ToString();
            //report rights
            string[] arrList = new string[user.ReportRightsList.Count];
            int k = 0;
            foreach (var y in user.ReportRightsList)
            {
         
                //Check whether a particular report right is given to user
                if (y.active)
                {
                   
                    arrList[k] = y.rightId;
                    k++;
                }
            }
            arrList = arrList.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            user.ReportRights = string.Join(",", arrList);
            //Insert dealer user details and retrieve user id of inserted user
            int newUserId = ua.InsertDealerUser(user);
           //Check user id is not 0
            if (newUserId != 0)
            {
                //Generate email to send username and password to created dealer user                                        
                string body = "Hi " + user.FirstName + "! <br /><br /> Your account has been successfully created. Below in your account detail." +
                              "<br /><br /> User name: " + user.UserName +
                                    "<br /> Password : <b>" + passwordTemp +
                              "<br />Click <a href='www.dfpso.com'>here</a> to activate your account." +
                              "<br /><br/> Thanks,<br /> Admin.";

                Email email = new Email(user.Email);

                Session["abcRol"] = user.RoleId;
                Session["abcBrnc"] = user.BranchId;
                email.SendMail(body, "Account details");
                //insert log record after user is created
                Log log = new Log(userData.UserId, userData.Company_Id, user.BranchId, user.LoanId, "Create Dealer Account", "Inserted Dealer : " + user.UserName, DateTime.Now);

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

                TempData["msg"] = 1;
                return RedirectToAction("LinkDealer");               

            }
            else
            {
                TempData["msg"] = 2;
                return RedirectToAction("LinkDealer");                
            }
        }
        /*

  Frontend page: DashBoard Page
  Title: Get a inactive loan by loan code
  Designed: Irfan Mam
  User story: DFP-484
  Developed: Irfan MAM
  Date created: 7/3/2016

*/

        public Loan GetAInActiveLoanDetailsbyLoanCode(string loancode, int role)
        {
            DataHandler dataHandler = new DataHandler();
            List<object[]> paramertList = new List<object[]>();
            // add a parameters to a list
            paramertList.Add(new object[] { "@role", role });
            paramertList.Add(new object[] { "@loan_code", loancode });
            try
            {

                // excecute sp and return the datas
                DataSet dataSet = dataHandler.GetDataSet("spGetAInActiveLoanByLoanCode", paramertList);

                // if data exists bind it to loan object
                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    Loan loanObj = new Loan();
                    loanObj.LoanNumber = dataSet.Tables[0].Rows[0]["loan_number"].ToString();
                    loanObj.PartnerName = dataSet.Tables[0].Rows[0]["non_reg_branch_name"].ToString();
                    loanObj.LoanCode = dataSet.Tables[0].Rows[0]["loan_code"].ToString();
                    loanObj.PartnerType = int.Parse(dataSet.Tables[0].Rows[0]["company_type"].ToString());
                    loanObj.BranchName = dataSet.Tables[0].Rows[0]["branch_name"].ToString();
                    // if is_title_tracked has a value
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["is_title_tracked"].ToString()))
                    {
                        // check that value
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["is_title_tracked"].ToString()))
                        {
                            loanObj.IsTitleTrack = 1;
                        }
                        else
                        {
                            loanObj.IsTitleTrack = 0;
                        }
                    }
                    //  if is_title_tracked has not a value
                    else
                    {
                        loanObj.IsTitleTrack = 0;
                    }

                    // if has_lot_inspection_fee has a value
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["has_lot_inspection_fee"].ToString()))
                    {
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["has_lot_inspection_fee"].ToString()))
                        {
                            loanObj.LotInspectionFee = 1;
                        }
                        else
                        {
                            loanObj.LotInspectionFee = 0;
                        }
                    }

                    // if has_lot_inspection_fee has not a value
                    else
                    {
                        loanObj.LotInspectionFee = 0;
                    }

                    // if has_monthly_loan_fee has a value
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["has_monthly_loan_fee"].ToString()))
                    {
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["has_monthly_loan_fee"].ToString()))
                        {
                            loanObj.MonthlyLoanFee = 1;
                        }
                        else
                        {
                            loanObj.MonthlyLoanFee = 0;
                        }
                    }
                    // if has_monthly_loan_fee  not a value
                    else
                    {
                        loanObj.MonthlyLoanFee = 0;
                    }

                    // if has_advance_fee has a value
                    if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["has_advance_fee"].ToString()))
                    {
                        if (bool.Parse(dataSet.Tables[0].Rows[0]["has_advance_fee"].ToString()))
                        {
                            loanObj.AdvanceFee = 1;
                        }
                        else
                        {
                            loanObj.AdvanceFee = 0;
                        }
                        if (!string.IsNullOrEmpty(dataSet.Tables[0].Rows[0]["payment_due_method"].ToString()))
                        {
                            if (dataSet.Tables[0].Rows[0]["payment_due_method"].ToString().Contains("Vehicle Payoff"))
                            {
                                loanObj.AdvanceFeePayAtPayoff = true;
                            }
                            else
                            {
                                loanObj.AdvanceFeePayAtPayoff = false;
                            }

                        }
                    }
                    // if has_advance_fee has not a value
                    else
                    {
                        loanObj.AdvanceFee = 0;
                    }


                    loanObj.StartDate = Convert.ToDateTime(dataSet.Tables[0].Rows[0]["start_date"].ToString());
                    loanObj.LoanAmount = Convert.ToDecimal(dataSet.Tables[0].Rows[0]["loan_amount"].ToString());
                    loanObj.MaturityDate = Convert.ToDateTime(dataSet.Tables[0].Rows[0]["maturity_date"].ToString());
                    loanObj.NonRegBranchId = int.Parse(dataSet.Tables[0].Rows[0]["non_reg_branch_id"].ToString());
                    loanObj.LoanId = int.Parse(dataSet.Tables[0].Rows[0]["loan_id"].ToString());

                    // return the loan object
                    return loanObj;

                }

                // if there is no data return null
                return null;
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// CreatedBy : Irfan
        /// CreatedDate: 2016/01/13
        /// 
        /// Showing details of selected user
        /// EditedBy: Piyumi
        /// EditedDate:2016/03/30
        /// Edited for new dashboard
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult UserDetails()
        {
            Session["rowId"] = userData.UserId;
            Session["loanStep"] = null;
            Loan loan = new Loan();

            if (Session["loanDashboardJoinDealer"] != null)
            {
                Session.Remove("loanDashboardJoinDealer");
            }
            if (Session["loanDashboardAssignUser"] != null)
            {
                Session.Remove("loanDashboardAssignUser");
            }

            if (Session["AuthenticatedUser"] != null)
            {
                DashBoardAccess da = new DashBoardAccess();
                ViewBag.Username = userData.UserName;
                ViewBag.Userid = userData.UserId;
                ViewBag.Company = userData.CompanyName;
                ViewBag.roleId = userData.RoleId;
                if (Session["loanDashboard"] != null)
                {
                    ViewBag.LoanCount = 1;
                    ViewBag.loanSelected = 1;
                    Loan loanSelected = (Loan)Session["loanDashboard"];

                    if (loanSelected != null)
                    {
                        if (userData.RoleId == 1)
                        {
                            ViewBag.PartnerType = 2;
                        }
                        else if (userData.RoleId == 2)
                        {
                            ViewBag.PartnerType = 1;
                        }
                        else {
                            ViewBag.PartnerType = 0;
                        }
                        ViewBag.PartnerName = loanSelected.PartnerName;

                        ViewBag.Branch = loanSelected.BranchName;
                        ViewBag.LoanNum = loanSelected.LoanNumber;
                        ViewBag.LoanCode = loanSelected.LoanCode;
                        ViewBag.IsTitleTrack = loanSelected.IsTitleTrack;

                        Session["IsTitleTrack"] = loanSelected.IsTitleTrack;
                        if ((loanSelected.AdvanceFee == 1) || (loanSelected.LotInspectionFee == 1) || (loanSelected.MonthlyLoanFee == 1))
                        {
                            ViewBag.Fee = 1;
                        }
                        else
                        {
                            ViewBag.Fee = 0;
                        }
                        Session["loanCode"] = loanSelected.LoanCode;

                        if (userData.RoleId == 3)
                        {
                            if ((string)Session["CurrentLoanRights"] != "")
                            {
                                //string[] charactors = loanSelected.Rights.Split(',');

                                string rgts = (string)(Session["CurrentLoanRights"]);
                                string[] rightsStringList = rgts.Split(',');

                                List<string> rightList = new List<string>();
                                for (int i = 0; i < rightsStringList.Length; i++) {
                                    rightList.Add(rightsStringList[i]);
                                }

                                //List<string> rightList = new List<string>(charactors);
                                ViewBag.RightList = rightList;
                            }

                        }
                        else
                        {
                            ViewBag.AdvanceUnits = 1;
                            ViewBag.AddUnits = 1;
                            ViewBag.ViewReports = 1;
                            ViewBag.PayoffUnits = 1;
                            ViewBag.Curtailment = 1;
                            ViewBag.TitleAdd = 1;
                            ViewBag.PayFees = 1;
                        }


                        
                        return View();
                    }
                    else
                    {
                        return View();
                    }

                }

                if (userData.RoleId == 2)
                {
                    //ViewBag.Branch = (ba.getBranchByBranchId(user.BranchId)).BranchName;
                    ViewBag.LoanCount = da.GetLoanCount(userData.BranchId, 2);
                    ViewBag.Branch = userData.BranchName;
                    ViewBag.Position = "Admin";

                }
                else if (userData.RoleId == 1)
                {
                    ViewBag.LoanCount = da.GetLoanCount(userData.Company_Id, 1);
                    ViewBag.Branch = "";
                    ViewBag.Position = "Super Admin";

                }
                else if (userData.RoleId == 3 || userData.RoleId == 4)
                {
                    ViewBag.LoanCount = da.GetLoanCount(userData.UserId, 3);
                    ViewBag.Branch = userData.BranchName;
                    ViewBag.Position = "User";

                }

                if (ViewBag.LoanCount == 1)
                {

                    if (userData.RoleId == 2)
                    {
                        loan = da.GetLoanDetails(userData.BranchId, 2);

                    }
                    else if (userData.RoleId == 1)
                    {
                        loan = da.GetLoanDetails(userData.Company_Id, 1);

                    }
                    else if (userData.RoleId == 3)
                    {
                        loan = da.GetLoanDetails(userData.UserId, 3);

                    }
                    else if (userData.RoleId == 4)
                    {
                        loan = da.GetLoanDetails(userData.UserId, 4);

                    }
                    if (loan != null)
                    {
                        Session["LoanOne"] = loan;
                        if (userData.RoleId == 3)
                        {
                            Session["CurrentLoanRights"] = loan.Rights;
                        }
                        ViewBag.PartnerName = ((Loan)Session["LoanOne"]).PartnerName;
                        ViewBag.PartnerType = loan.PartnerType;
                        ViewBag.Branch = ((Loan)Session["LoanOne"]).BranchName;
                        ViewBag.LoanNum = loan.LoanNumber;
                        ViewBag.LoanCode = loan.LoanCode;
                        ViewBag.IsTitleTrack = loan.IsTitleTrack;
                        Session["IsTitleTrack"] = loan.IsTitleTrack;
                        if ((loan.AdvanceFee == 1) || (loan.LotInspectionFee == 1) || (loan.MonthlyLoanFee == 1))
                        {
                            ViewBag.Fee = 1;
                        }
                        else
                        {
                            ViewBag.Fee = 0;
                        }

                        // 
                        Session["loanCode"] = loan.LoanCode;
                        if (userData.RoleId == 3)
                        {

                            if ((loan.Rights.Length > 0) && (loan.Rights != null))
                            {
                                string[] charactors = { };
                                if (loan.Rights != "")
                                {
                                    charactors = loan.Rights.Split(',');
                                }
                                List<string> rightLst = new List<string>(charactors);

                                ViewBag.RightList = rightLst;

                            }


                        }
                        else if ((userData.RoleId == 1) || (userData.RoleId == 2))
                        {
                            ViewBag.AdvanceUnits = 1;
                            ViewBag.AddUnits = 1;
                            ViewBag.ViewReports = 1;
                            ViewBag.PayoffUnits = 1;
                            ViewBag.Curtailment = 1;
                            ViewBag.TitleAdd = 1;
                            ViewBag.PayFees = 1;
                        }


                        //ViewBag.CompType = (new BranchAccess()).getCompanyTypeByUserId(userData.UserId);
                        //ViewBag.CompType
                        Session["oneLoanDashboard"] = loan;
                        return View();
                    }
                    else
                    {
                        return View();
                    }

                }
                else
                {
                    ViewBag.PartnerType = (userData.CompanyType == 1) ? 2 : 1;
                    return View();
                }


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



        }
        /*

   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();
        }
        public ActionResult AddUnitPost(Models.Unit unit, List<HttpPostedFileBase> fileUpload)
        {

           int userId = userData.UserId;
            // check this is an advance or add unit
            switch (unit.AdvanceNow)
            {
                case "No":
                    unit.IsAdvanced = false;
                    unit.AddAndAdvance = false;
                    break;
                case "Yes":
                    unit.IsAdvanced = true;
                    unit.AddAndAdvance = true;
                    break;
            }

            if (Session["loanCode"] == null) {
                return RedirectToAction("UserLogin", "Login", null);
            }
            string loanCode = Session["loanCode"].ToString();
            
            //check this posted vin unique in database

            int num = 0;
            // vehile ID number
            if (unit.UnitTypeId == 1)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.vehicle.IdentificationNumber, unit.LoanId);
            }
            // rv ID number
            else if (unit.UnitTypeId == 2)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.rv.IdentificationNumber , unit.LoanId);

            }
            // camper ID number
            else if (unit.UnitTypeId == 3)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.camper.IdentificationNumber, unit.LoanId);
            }
            // atv ID number
            else if (unit.UnitTypeId == 4)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.atv.IdentificationNumber, unit.LoanId);
            }
            // boat ID number
            else if (unit.UnitTypeId == 5)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.boat.IdentificationNumber, unit.LoanId);
            }
            // motorcycle ID number 
            else if (unit.UnitTypeId == 6)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.motorcycle.IdentificationNumber, unit.LoanId);
            }
            // snowmobile ID number 
            else if (unit.UnitTypeId == 7)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.snowmobile.IdentificationNumber, unit.LoanId);
            }
            // heavyequipment ID number 
            else if (unit.UnitTypeId == 8)
            {
                num = (new UnitAccess()).IsUniqueVinForaLoan(unit.heavyequipment.SerialNumber, unit.LoanId);
            }

            //only allow to add if and only if vin already not existing in this loan
            if (num != 0 && num != 1)
            {

                string IDNumber;
                UnitAccess ua = new UnitAccess();
                //inserting the unit to the database
                string res = ua.InsertUnit(unit, userId, loanCode, out IDNumber);

                //if mention advance fee, then insert in to fee table
                if (!string.IsNullOrEmpty(res) && unit.AddAndAdvance)
                {


                    if ((Session["loanDashboard"] != null) || (Session["oneLoanDashboard"] != null))
                    {
                        Loan loanObj = new Loan();
                        if (Session["loanDashboard"] != null)
                        {
                            loanObj = (Loan)Session["loanDashboard"];
                        }
                        else
                        {
                            loanObj = (Loan)Session["oneLoanDashboard"];
                        }
                        if (loanObj.AdvanceFee == 1)
                        {
                            //check advance amount and other details

                            ua.insertFreeDetails(unit);
                        }
                    }
                }
                
                if (!string.IsNullOrEmpty(res))
                {
                    if (Session["addUnitloan"] == null)
                    {
                        return RedirectToAction("UserLogin", "Login", new { lbl = "Failed find loan" });
                    }
                    LoanSetupStep1 loan = (LoanSetupStep1)Session["addUnitloan"];
                    //insert to log 
                    Log log = new Log(userData.UserId, userData.Company_Id, userData.BranchId, unit.LoanId, "Add Unit", (unit.AddAndAdvance ? "Added and advanced" : "Added") + " unit : " + IDNumber + ", Cost Amount : " + unit.Cost + (unit.Cost * loan.advancePercentage / 100 != unit.AdvanceAmount ? ", Edited Advance amount " + unit.AdvanceAmount : ", Advance amount : " + unit.AdvanceAmount), DateTime.Now);

                    int islog = (new LogAccess()).InsertLog(log);
                    //Handling file attachments

                    //Check directory is already exists, if not create new
                    string mapPath = "~/Uploads/" + loan.RegisteredCompanyCode + "/" + loan.RegisteredBranchCode + "/";
                    if (!Directory.Exists(Server.MapPath(mapPath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(mapPath));
                    }

                    List<TitleUpload> titleList = new List<TitleUpload>();

                    int imageNo = 1;
                    // if unit successfully updated then upload files
                    if (unit.FileName != null && fileUpload != null)
                    {
                        foreach (var file in fileUpload)
                        {
                            if (file != null && Array.Exists(unit.FileName.Split(','), s => s.Equals(file.FileName)))
                            {
                                if (file.ContentLength > 3 * 1024 * 1024)
                                {
                                    break;
                                }
                                unit.UnitId = res;
                                string extension = Path.GetExtension(file.FileName);

                                string filename = unit.UnitId + "_" + imageNo.ToString("00") + extension;

                                file.SaveAs(Server.MapPath(mapPath + filename));
                                string filepathtosave = mapPath + filename;

                                //add file information to list
                                TitleUpload title = new TitleUpload();
                                title.UploadId = imageNo;
                                title.FilePath = filepathtosave;
                                title.UnitId = unit.UnitId;
                                title.OriginalFileName = file.FileName;

                                titleList.Add(title);

                                imageNo++;
                            }
                        }

                        try
                        {
                            XElement xEle = new XElement("Titles",
                                from title in titleList
                                select new XElement("Title",
                                    new XElement("FilePath", title.FilePath),
                                    new XElement("UnitId", title.UnitId),
                                    new XElement("OriginalFileName", title.OriginalFileName)
                                    ));
                            string xmlDoc = xEle.ToString();

                            bool res1 = ua.InsertTitleDocumentUploadInfo(xmlDoc, unit.UnitId);

                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    TempData["Msg"] = 1;

                    return RedirectToAction("AddUnit");
                }
            }
            TempData["Msg"] = 2;
            return RedirectToAction("AddUnit", unit);
        }