public ActionResult ForgotPassword(string username, string email)
        {
            //handle login
            using (var dbContext = new CocBookEntities())
            {
                Customer chkCus = (from c in dbContext.Customers
                                   where c.Username == username && c.Email == email
                                   select c).SingleOrDefault();
                if (chkCus == null || email == "")
                {
                    return Json(new { Success = false });
                }
                else
                {
                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
                    mail.From = new MailAddress("*****@*****.**");
                    mail.To.Add(chkCus.Email);
                    mail.Subject = "Password recovery";
                    mail.Body = "Password : "******"*****@*****.**", "P@ssword1992");
                    SmtpServer.Send(mail);

                    return Json(new { Success = true });
                }
            }
        }
        public ActionResult UpdateCart(int bookID, int quantity)
        {
            // sua hang trong gio
            Cart cart = GetCart();
            // tim hang
            V_Book b;
            using (var dbContext = new CocBookEntities())
            {
                b = (from c in dbContext.V_Book
                     where c.BookID == bookID
                     select c).SingleOrDefault();

            }
            if (b == null)
            {
                return Json(new { Success = false, BName = bookID });
            }
            // co hang thi sua so luong
            cart.UpdateQuantity(b, quantity);

            // tinh lai tong cong
            var sum = cart.GetTotal();
            var tempSum = b.Price * quantity;

            return Json(new { Success = true, Sum = sum, Temp = tempSum });
        }
        public ActionResult Profile()
        {
            using (var dbContext = new CocBookEntities())
            {
                string username = (string)HttpContext.Session["username"];
                if (username == null)
                {
                    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (authCookie != null)
                    {
                        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                        username = ticket.Name;
                        HttpContext.Session.Add("username", username);
                    }
                }
                Customer cus = (from c in dbContext.Customers
                                where c.Username == username
                                select c).SingleOrDefault();
                if (cus == null)
                {
                    //return View("Error");
                    cus = new Customer();
                }
                UserProfile ups = new UserProfile();
                ups.CusInfo = cus;
                if (TempData["InfoMess"] != null)
                {
                    ViewBag.InfoMess = TempData["InfoMess"];
                }
                return View(ups);

            }
        }
        public ActionResult CateFilter(int id, int page = 1)
        {
            bool blnValidCate = false;
            string strCateName = "";
            PagingDisplay pagingView = new PagingDisplay();
            using (var DbContext = new CocBookEntities())
            {
                // list Category
                pagingView.CateList = (from c in DbContext.Categories
                                       where c.Active == true
                                       orderby c.Position
                                       select c).ToList();
                // know Category
                foreach (var item in pagingView.CateList)
                {
                    if (item.CateID == id)
                    {
                        blnValidCate = true;
                        strCateName = item.Name;
                    }
                }

                // if invalid URL
                if (!blnValidCate)
                {
                    return RedirectToAction("Index", "Home");
                }
                // load books
                var books = (from b in DbContext.V_Book
                             join c in DbContext.BookInCategories on b.BookID equals c.BookID
                             where c.CateID == id
                             orderby b.CreatedDate descending
                             select b).ToList();

                pagingView.TotalItem = books.Count;
                pagingView.ItemsPerPage = PageSize;
                pagingView.CurrentPage = page;
                pagingView.TotalPage = (int)Math.Ceiling((decimal)pagingView.TotalItem / pagingView.ItemsPerPage);
                pagingView.BookList = books.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            }
            ViewBag.SelectedID = id;
            ViewBag.Category = strCateName;

            ViewBag.PageCategory = id + "/" + ChangeToUrlString(strCateName);
            return View(pagingView);
        }
        public ActionResult AddToCart(int bookID, int quantity)
        {
            Cart cart = GetCart();
            V_Book b;
            using (var dbContext = new CocBookEntities())
            {
                b = (from c in dbContext.V_Book
                     where c.BookID == bookID
                     select c).SingleOrDefault();

            }
            if (b == null)
            {
                return Json(new { Success = false });
            }
            cart.AddBook(b, quantity);
            return Json(new { Success = true });
        }
 public ActionResult Invoice(int id)
 {
     Invoice invoice = new Invoice();
     using (var dbContext = new CocBookEntities())
     {
         var order = (from c in dbContext.Orders
                      where c.OrderID == id
                      select c).Single();
         var orderlines = (from c in dbContext.OrderDetails.Include("Book")
                           where c.OrderID == id
                           select c).ToList();
         if (order.Username != getUser()|| order.Username =="guest")
         {
             TempData["mess"] = "xử lý";
             return RedirectToAction("Index", "Home");
         }
         invoice.Order = order;
         invoice.OrderLine = orderlines;
     }
     return View(invoice);
 }
        public ActionResult NewBooks(int page=1)
        {
            PagingDisplay pagingView = new PagingDisplay();
            using (var DbContext = new CocBookEntities())
            {
                pagingView.CateList = (from c in DbContext.Categories
                                          where c.Active == true
                                          orderby c.Position
                                          select c).ToList();
                var books = (from c in DbContext.V_Book
                             where c.Active == true
                             orderby c.CreatedDate descending
                             select c).ToList();

                pagingView.TotalItem = books.Count;
                pagingView.ItemsPerPage = PageSize;
                pagingView.CurrentPage = page;
                pagingView.TotalPage = (int)Math.Ceiling((decimal) pagingView.TotalItem/ pagingView.ItemsPerPage);
                pagingView.BookList = books.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            }
            return View(pagingView);
        }
        public ActionResult Order()
        {
            Cart cart = (Cart)Session["Cart"];
            if (cart == null || cart.lineCollection.Count ==0)
            {
                return RedirectToAction("Index", "Home");
            }
            string username = (string)Session["username"];
            Customer cus;

            if (username == null)
            {
                HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie != null)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                    username = ticket.Name;
                }
            }
            if (username == null)
            {
                cus = new Customer();
            }
            else
            {
                using (var dbContext = new CocBookEntities())
                {
                    cus = (from c in dbContext.Customers
                           where c.Username == username
                           select c).Single();
                }
            }

            Payment payment = new Payment();
            payment.Cus = cus;
            payment.Cart = cart;
            return View(payment);
        }
        public ActionResult RemoveFromCart(int bookID)
        {
            // xoa hang khoi gio
            Cart cart = GetCart();
            // tim hang
            V_Book b;
            using (var dbContext = new CocBookEntities())
            {
                b = (from c in dbContext.V_Book
                     where c.BookID == bookID
                     select c).SingleOrDefault();

            }
            if (b == null)
            {
                return Json(new { Success = false, BName = bookID });
            }
            // co hang thi xoa
            cart.UpdateQuantity(b, 0);
            // tinh lai tong cong
            var sum = cart.GetTotal();

            return Json(new { Success = true ,BName = b.Name, Sum = sum, End = cart.IsEmpty()});
        }
        public ActionResult Order(FormCollection form)
        {
            #region GetInfo
            Cart cart = (Cart)Session["Cart"];
            if (cart == null)
            {
                return RedirectToAction("Index", "Home");
            }
            string username = getUser();
            Customer cus;

            if (username == null)
            {
                cus = new Customer();
                cus.Username = "******";
            }
            else
            {
                using (var dbContext = new CocBookEntities())
                {
                    cus = (from c in dbContext.Customers
                           where c.Username == username
                           select c).Single();
                }
            }
            string fullname = form["full-name"];
            string phone = form["phone"];
            string district = form["district"];
            string address = form["address"];
            string payMethod = form["optPaymentMethod"];
            string speed = form["optSpeed"];
            string comment = form["comment"];
            #endregion
            int oid;
            #region process order
            using (var dbContext = new CocBookEntities())
            {
                Order order = new Order();
                order.Username = cus.Username;
                order.RequestDate = DateTime.Now;
                order.Notes = comment;
                order.Total = cart.GetTotal();
                order.Fullname = fullname;
                order.Phone = phone;
                order.District = district;
                order.Street = address;
                order.City = "HCM";
                order.Elog = "";
                order.GiftCode = "";
                // luu order
                dbContext.Orders.Add(order);
                dbContext.SaveChanges();
                for (int i = 0; i < cart.lineCollection.Count; i++)
                {
                    OrderDetail od = new OrderDetail();
                    od.BookID = cart.lineCollection[i].Book.BookID;
                    od.OrderID = order.OrderID;
                    od.Quantity = cart.lineCollection[i].Quantity;
                    od.Price = cart.lineCollection[i].Book.Price;
                    dbContext.OrderDetails.Add(od);
                }
                dbContext.SaveChanges();
                oid= order.OrderID;
            }

            #endregion
            // xoa gio hang
            cart.Clear();
            Session["cart"] = cart;

            TempData["mess"] = "Xử lý";

            return RedirectToAction("Invoice", "Order", new { id = oid});
        }
        public ActionResult Index()
        {
            // View model
            Home homeViewModel = new Home();

            // Binding data home page
            using (var DbContext = new CocBookEntities())
            {

                homeViewModel.CateList = (from c in DbContext.Categories
                                          where c.Active == true
                                          orderby c.Position
                                          select c).ToList();
                var books = (from c in DbContext.V_Book
                             where c.Active == true
                             select c).ToList();

                homeViewModel.NewList = (from c in books
                                         orderby c.CreatedDate descending
                                         select c).Take(12).ToList();

                homeViewModel.HighRatingList = (from c in books
                                                orderby c.AveScore descending
                                                select c).Take(12).ToList();

                homeViewModel.DealList = (from c in books
                                          orderby c.DealPercentage descending
                                          select c).Take(12).ToList();
            }
            if(TempData["mess"]!=null)
            {
                ViewBag.BuyMess ="xử lý";
            }
            return View(homeViewModel);
        }
        public ActionResult UpdateInfo(FormCollection form)
        {
            string fullname = form["full-name"];
            string email = form["user-email"];
            string phone = form["phone"];
            string address = form["address"];
            string district = form["district"];

            if (HttpContext.Session["username"] == null)
            {
                return View("Error");
            }
            using (var dbContext = new CocBookEntities())
            {
                string username = (string)HttpContext.Session["username"];

                Customer cus = (from c in dbContext.Customers
                                where c.Username == username
                                select c).Single();
                cus.Fullname = fullname;
                cus.Phone = phone;
                cus.Email = email;
                cus.District = district;
                cus.Street = address;
                cus.City = "HCM";
                dbContext.SaveChanges();

                UserProfile ups = new UserProfile();
                ups.CusInfo = cus;
                TempData["InfoMess"] = "Thông tin tài khoản đã được cập nhật...";

                return RedirectToAction("Profile", "Customer");

            }
        }
        public ActionResult Search(string str, int type = 1, int page = 1)
        {
            PagingDisplay pagingView = new PagingDisplay();
            using (var DbContext = new CocBookEntities())
            {
                pagingView.CateList = (from c in DbContext.Categories
                                       where c.Active == true
                                       orderby c.Position
                                       select c).ToList();
                List<V_Book> books = null;

                if (type == 1)
                {
                    books = (from c in DbContext.V_Book
                             where c.Active == true && c.Name.Contains(str)
                             orderby c.CreatedDate descending
                             select c).ToList();

                }
                else
                {
                    books = (from c in DbContext.V_Book
                             where c.Active == true && c.AuthorName.Contains(str)
                             orderby c.CreatedDate descending
                             select c).ToList();
                }
                pagingView.TotalItem = books.Count;
                pagingView.ItemsPerPage = PageSize;
                pagingView.CurrentPage = page;
                pagingView.TotalPage = (int)Math.Ceiling((decimal)pagingView.TotalItem / pagingView.ItemsPerPage);
                pagingView.BookList = books.Skip((page - 1) * PageSize).Take(PageSize).ToList();
                ViewBag.SearchKey = str;
                ViewBag.SearchType = type + "";
                ViewBag.eid = 0;
            }
            return View(pagingView);
        }
        public ActionResult Search(FormCollection form)
        {
            int page = 1;
            string str = form["searchkey"];
            if (str.Trim() == "")
            {
                return RedirectToAction("Index");
            }
            string type = form["searchtype"] == "" ? "1" : form["searchtype"];
            PagingDisplay pagingView = new PagingDisplay();
            using (var DbContext = new CocBookEntities())
            {
                SearchHistory history = new SearchHistory();
                history.SearchValue = str + ";"+type ;
                history.Username = getUser();

                pagingView.CateList = (from c in DbContext.Categories
                                       where c.Active == true
                                       orderby c.Position
                                       select c).ToList();
                List<V_Book> books = null;

                if (type.Equals("1"))
                {
                    books = (from c in DbContext.V_Book
                             where c.Active == true && c.Name.Contains(str)
                             orderby c.CreatedDate descending
                             select c).ToList();
                }
                else
                {
                    books = (from c in DbContext.V_Book
                             where c.Active == true && c.AuthorName.Contains(str)
                             orderby c.CreatedDate descending
                             select c).ToList();

                }
                // store history of search
                history.HitCount = books.Count;
                history.CreatedDate = DateTime.Now;
                DbContext.SearchHistories.Add(history);
                DbContext.SaveChanges();

                // data mining search history
                string strS = str + ";" + type ;
                var extend = (from c in DbContext.SearchHistories
                              where c.SearchValue.Contains(str) && c.SearchValue.Contains(type) &&c.SearchValue!= strS && c.HitCount < books.Count
                              orderby c.HitCount descending
                              select c).Take(1).SingleOrDefault();
                int eid = 0;
                string extendSearch="";
                string extendType = "";
                if (extend != null)
                {
                    eid = extend.AutoID;
                    extendSearch = extend.SearchValue.ToString().Split(';')[0];
                    extendType = extend.SearchValue.ToString().Split(';')[1];
                }

                // display
                pagingView.TotalItem = books.Count;
                pagingView.ItemsPerPage = PageSize;
                pagingView.CurrentPage = page;
                pagingView.TotalPage = (int)Math.Ceiling((decimal)pagingView.TotalItem / pagingView.ItemsPerPage);
                pagingView.BookList = books.Skip((page - 1) * PageSize).Take(PageSize).ToList();
                ViewBag.SearchKey = str;
                ViewBag.SearchType = type;
                ViewBag.ExtendSearch = extendSearch;
                ViewBag.ExtendType = extendType;
                ViewBag.eid = eid;
            }
            return View(pagingView);
        }
 public ActionResult Login(string username, string password)
 {
     //handle login
     using (var dbContext = new CocBookEntities())
     {
         Account chkAcc = (from c in dbContext.Accounts
                           where c.Username == username
                           select c).SingleOrDefault();
         if (chkAcc == null)
         {
             return Json(new { Success = false, Message = "Tên đăng nhập không đúng" });
         }
         if (chkAcc.Password.Equals(password))
         {
             if (chkAcc.Active == true)
             {
                 if (chkAcc.RoleID != 1)
                 {
                     return Json(new { Success = false, Message = "Tài khoản quản lý không thể mua sách" });
                 }
                 else
                 {
                     FormsAuthentication.SetAuthCookie(username, false);
                     HttpContext.Session.Add("username", username);
                     if (Request.UrlReferrer.ToString().Contains("Order/Order"))
                     {
                         return Json(new { Success = true, Reload = true });
                     }
                     else if (Request.UrlReferrer.ToString().Contains("Book/Details"))
                     {
                         return Json(new { Success = true, Reload = true });
                     }
                     return Json(new { Success = true });
                 }
             }
             else
             {
                 return Json(new { Success = false, Message = "Tài khoản đã bị block" });
             }
         }
         else
         {
             return Json(new { Success = false, Message = "Mật khẩu không đúng" });
         }
     }
 }
        // GET: /Book/Detail/id/name
        public ActionResult Details(int id)
        {
            using (var dbContext = new CocBookEntities())
            {
                var music = (from m in dbContext.V_Music
                            where m.Active == true && m.MusicId == id
                            select m).FirstOrDefault();
                if (music == null)
                {
                    ViewBag.Message = "Đã có lỗi xảy ra trong quá trình xử lý thông tin. Xin bạn thử lại sau";
                    return View("Error.cshtml");
                }
                ViewBag.Title = music.Name;
                string username = getUser();
                bool blnRate = true;
                string strRateMess = "Hãy cho điểm sách";
                if (username.Equals("guest"))
                {
                    blnRate = false;
                    strRateMess = "Đăng nhập để cho điểm sách";
                }
                else
                {

                    var rated = (from c in dbContext.Ratings
                                 where c.BookID == id && c.Username == username
                                 select c).SingleOrDefault();
                    if (rated != null)
                    {
                        blnRate = false;
                        strRateMess = "Bạn đã chấm " + rated.Score + " điểm";
                    }
                }
                ViewBag.Rate = blnRate;
                ViewBag.RateMess = strRateMess;
                return View(music);
            }

            //using (var dbContext = new CocBookEntities())
            //{
            //    var book = (from c in dbContext.V_Book
            //                where c.Active == true && c.BookID == id
            //                select c).SingleOrDefault();
            //    if (book == null)
            //    {
            //        ViewBag.Message = "Đã có lỗi xảy ra trong quá trình xử lý thông tin. Xin bạn thử lại sau";
            //        return View("Error.cshtml");
            //    }
            //    ViewBag.Title = book.Name;
            //    string username = getUser();
            //    bool blnRate = true;
            //    string strRateMess = "Hãy cho điểm sách";
            //    if (username.Equals("guest"))
            //    {
            //        blnRate = false;
            //        strRateMess = "Đăng nhập để cho điểm sách";
            //    }
            //    else
            //    {

            //        var rated = (from c in dbContext.Ratings
            //                     where c.BookID == id && c.Username == username
            //                     select c).SingleOrDefault();
            //        if (rated != null)
            //        {
            //            blnRate = false;
            //            strRateMess = "Bạn đã chấm " + rated.Score + " điểm";
            //        }
            //    }
            //    ViewBag.Rate = blnRate;
            //    ViewBag.RateMess = strRateMess;
            //    return View(book);
            //}
        }
        public ActionResult Rating(int bookID, double score)
        {
            string username = getUser();
            if (username == null)
            {
                return Json(new { Success = false, Message = "Bạn chưa đăng nhập" });
            }
            using (var dbContext = new CocBookEntities())
            {
                var rating = new Rating();
                rating.RateDate = DateTime.Now;
                rating.BookID = bookID;
                rating.Username = username;
                rating.Score = score;
                dbContext.Ratings.Add(rating);
                dbContext.SaveChanges();
            }

            return Json(new { Success = true , Message="Bạn đã chấm " +score+ " điểm"});
        }
        public ActionResult Register(FormCollection form)
        {
            string username = form["user-name"];
            string password = form["pass-word"];
            string fullname = form["full-name"];
            string email = form["user-email"];
            string phone = form["phone"];
            string address = form["address"];
            string district = form["district"];

            Account newAcc = new Account();
            newAcc.Active = true;
            newAcc.Username = username;
            newAcc.Password = password;
            newAcc.RoleID = 1;

            Customer newCus = new Customer();
            newCus.Username = username;
            newCus.Fullname = fullname;
            newCus.Phone = phone;
            newCus.Email = email;
            newCus.District = district;
            newCus.Street = address;
            newCus.City = "HCM";
            newCus.Point = 0;

            using (var dbContext = new CocBookEntities())
            {
                dbContext.Accounts.Add(newAcc);
                dbContext.Customers.Add(newCus);
                dbContext.SaveChanges();
            }

            FormsAuthentication.SetAuthCookie(username, false);
            HttpContext.Session.Add("username", username);

            return RedirectToAction("Profile");
        }