/// <summary>
        /// CreatedBy:kasun
        /// CreatedDate:2016/4/22
        /// 
        /// Get all titles for a loan
        /// </summary>
        /// <param name="loanId"></param>
        /// <returns></returns>
        public List<TitleUpload> GetUploadTitlesByLoanId(string unitId)
        {

            DataHandler dataHandler = new DataHandler();
            List<object[]> parameterList = new List<object[]>();
            List<TitleUpload> titleList = new List<TitleUpload>();

            parameterList.Add(new object[] { "@unit_id", unitId });
            try
            {
                DataSet dataSet = dataHandler.GetDataSet("spGetUploadTitlesByUnitId", parameterList);

                if (dataSet != null && dataSet.Tables.Count != 0 && dataSet.Tables[0].Rows.Count != 0)
                {
                    foreach (DataRow reader in dataSet.Tables[0].Rows)
                    {
                        TitleUpload title = new TitleUpload();

                        title.FilePath = reader["file_path"].ToString();
                        title.UnitId = reader["unit_id"].ToString();
                        title.OriginalFileName = reader["original_file_name"].ToString();

                        titleList.Add(title);
                    }
                    return titleList;
                }
                else {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        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);
        }