//Update/ammend Book Info
        private static void UpdateBook(string title, string author, string isbn, decimal price, int stock)
        {
            Bookshop context = new Bookshop();

            var b = (from x in context.Book where x.ISBN == isbn select x).First();

            b.Title  = title;
            b.ISBN   = isbn;
            b.Author = author;
            b.Stock  = stock;
            b.Price  = price;
            context.SaveChanges();
        }
 //Create promo code
 public static void CreatePromoCode(string promoCode, short discount, DateTime validStart, int promoDuration)
 {
     using (Bookshop context = new Bookshop())
     {
         CartPromo cartPromo = new CartPromo
         {
             PromoCode     = promoCode,
             Discount      = discount,
             ValidStart    = validStart,
             PromoDuration = promoDuration
         };
         context.CartPromo.Add(cartPromo);
         context.SaveChanges();
     }
 }
        //Create discount based on category
        public static void CreateCategoryDiscount(string discountId, short discountAmt, DateTime validStart, int discountDuration, int categoryId)
        {
            using (Bookshop context = new Bookshop())
            {
                CategoryDiscount promoPeriod = new CategoryDiscount
                {
                    DiscountID       = discountId,
                    DiscountAmt      = discountAmt,
                    ValidStart       = validStart,
                    DiscountDuration = discountDuration,
                    //CategoryID = categoryId,
                    Category = context.Category.Single(x => x.CategoryID == categoryId)
                };

                context.CategoryDiscount.Add(promoPeriod);
                context.SaveChanges();
            }
        }
 //Update category discount
 public static bool UpdateCategoryDiscount(string discountId, short discountAmt, DateTime validStart, int discountDuration, int categoryId)
 {
     using (Bookshop context = new Bookshop())
     {
         CategoryDiscount promoPeriod = context.CategoryDiscount.Single(x => x.DiscountID == discountId);
         if (promoPeriod != null)
         {
             promoPeriod.DiscountAmt      = discountAmt;
             promoPeriod.ValidStart       = validStart;
             promoPeriod.DiscountDuration = discountDuration;
             promoPeriod.Category         = context.Category.Single(x => x.CategoryID == categoryId);
             context.SaveChanges();
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
 //Update promo code
 public static bool UpdatePromoCode(string promoCode, short discount, DateTime validStart, int promoDuration)
 {
     using (Bookshop context = new Bookshop())
     {
         CartPromo cartPromo = context.CartPromo.Single(x => x.PromoCode == promoCode);
         if (cartPromo != null)
         {
             //cartPromo.PromoCode = promoCode;
             cartPromo.Discount      = discount;
             cartPromo.ValidStart    = validStart;
             cartPromo.PromoDuration = promoDuration;
             context.SaveChanges();
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
 public static void CreateBook(string title, int categoryId, string isbn, string author, int stock, decimal price, string imageUrl)
 {
     using (Bookshop context = new Bookshop())
     {
         Book book = new Book
         {
             BookID = context.Book.Count() + 1,
             Title  = title,
             //CategoryID = categoryId,
             Category = context.Category.First(x => x.CategoryID == categoryId),
             ISBN     = isbn,
             Author   = author,
             Stock    = stock,
             Price    = price,
             Image    = imageUrl
         };
         context.Book.Add(book);
         context.SaveChanges();
     }
 }
 //Update Book entry
 public static bool UpdateBook(int bookId, string title, int categoryId, string isbn, string author, int stock, decimal price, string imageUrl)
 {
     using (Bookshop context = new Bookshop())
     {
         Book book = context.Book.Single(x => x.BookID == bookId);
         if (book != null)
         {
             book.Title = title;
             //book.CategoryID = categoryId;
             book.Category = context.Category.First(x => x.CategoryID == categoryId);
             book.ISBN     = isbn;
             book.Author   = author;
             book.Stock    = stock;
             book.Price    = price;
             book.Image    = imageUrl;
             context.SaveChanges();
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
        //Checkout button
        public static bool CheckOut(List <CartItem> listCart, string customerId, string promoCode)
        {
            //List<InvoiceDetails> listInvoiceFromCart = new List<InvoiceDetails>();
            Invoice invoice         = new Invoice();
            bool    checkOutSuccess = true; //will iterate through all books in cart, if books are not found or insufficient stock it will change to false
            decimal total           = 0;

            using (Bookshop context = new Bookshop())
            {
                string invoiceId = string.Format($"INV{(context.Invoice.Count() + 1).ToString().PadLeft(5, '0')}");
                foreach (CartItem item in listCart)
                {
                    bool bookFound = context.Book.Any(x => x.ISBN == item.Isbn);
                    if (bookFound)
                    {
                        bool enoughStock = context.Book.Single(x => x.ISBN == item.Isbn).Stock >= item.Quantity;
                        if (enoughStock)
                        {
                            Book book = context.Book.First(x => x.ISBN == item.Isbn);
                            book.Stock -= 1;
                            InvoiceDetails invoiceDetail = new InvoiceDetails();
                            invoiceDetail.InvoiceID   = invoiceId;
                            invoiceDetail.BookID      = book.BookID;
                            invoiceDetail.Unit        = item.Quantity;
                            invoiceDetail.UnitPrice   = GetPrice(book.BookID);
                            invoiceDetail.DiscountAmt = GetPrice(book.BookID) - GetDiscountedPrice(book.BookID);
                            invoice.InvoiceDetails.Add(invoiceDetail);
                            context.InvoiceDetails.Add(invoiceDetail);
                            checkOutSuccess = true;
                        }
                        else
                        {
                            checkOutSuccess = false;
                            break;
                        }
                    }
                    else
                    {
                        checkOutSuccess = false;
                        break;
                    }
                }

                if (checkOutSuccess)
                {
                    invoice.InvoiceID   = invoiceId;
                    invoice.InvoiceDate = DateTime.Today.Date;
                    invoice.CustomerID  = customerId;
                    total = GetTotalPriceFromCart(listCart);
                    bool validCode = CheckPromoCode(promoCode);
                    if (validCode)
                    {
                        invoice.CartPromo  = context.CartPromo.First(x => x.PromoCode == promoCode); //to be checked
                        invoice.PromoCode  = promoCode;
                        invoice.PromoAmt   = total * GetPromoPercentage(promoCode) / 100;
                        invoice.InvoiceAmt = total * (100 - GetPromoPercentage(promoCode)) / 100;
                    }
                    else
                    {
                        invoice.CartPromo  = context.CartPromo.Single(x => x.PromoCode == "None");
                        invoice.PromoCode  = "None";
                        invoice.PromoAmt   = 0;
                        invoice.InvoiceAmt = total;
                    }

                    invoice.PaymentStatus = "Paid";
                    //context.InvoiceDetails.Add(invoiceDetail);
                    context.Invoice.Add(invoice);
                    context.SaveChanges();
                }
                return(checkOutSuccess);
            }
        }
        //Add new book to data base together with photo.
        protected void saveButton_Click(object sender, EventArgs e)
        {
            Bookshop context = new Bookshop();
            //For uploading image
            HttpPostedFile postedFile    = FileUpload1.PostedFile;
            string         filename      = Path.GetFileName(postedFile.FileName);
            string         fileExtension = Path.GetExtension(filename);



            if (titleTextBox.Text != "" && isbnTextBox.Text != "" && authorTextBox.Text != "" &&
                stockTextBox.Text != "" && priceTextBox.Text != "")

            {
                if (stockTextBox.Text.Any(char.IsDigit))
                {
                    if (priceTextBox.Text.Any(char.IsDigit))
                    {
                        if (FileUpload1.HasFile)
                        {
                            if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".gif" ||
                                fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".bmp")
                            {
                                var q = from x in context.Category where x.Name == catDropDownList.Text select x.CategoryID;
                                var r = from y in context.Book where y.ISBN == isbnTextBox.Text select y;


                                if ((from y in context.Book where y.ISBN == isbnTextBox.Text select y).Count() > 0)
                                {
                                    MessageBox.Show(this, "The Book alredy exists!");
                                }

                                else
                                {
                                    Book b = new Book();
                                    b.Title      = titleTextBox.Text;
                                    b.CategoryID = q.First();
                                    b.ISBN       = isbnTextBox.Text;
                                    b.Author     = authorTextBox.Text;
                                    b.Stock      = int.Parse(stockTextBox.Text);
                                    b.Price      = decimal.Parse(priceTextBox.Text);
                                    b.Image      = isbnTextBox.Text + fileExtension;

                                    context.Book.Add(b);
                                    context.SaveChanges();

                                    FileUpload1.SaveAs(Server.MapPath("images\\" + isbnTextBox.Text + fileExtension));
                                    uploadLabel.Visible = true;
                                    uploadLabel.Text    = "A new book entry has been created successfully!";
                                    Image1.ImageUrl     = "images\\" + isbnTextBox.Text + fileExtension;
                                }
                            }
                            else
                            {
                                MessageBox.Show(this, "The image must be in one of the following formats:" +
                                                ".jpp,.gif,.png or.bmp");
                            }
                        }
                        else
                        {
                            MessageBox.Show(this, "Please select an image file!");
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "Price must be digits!");
                    }
                }
                else
                {
                    MessageBox.Show(this, "Stock quantity must be digits!");
                }
            }

            else
            {
                MessageBox.Show(this, "Please fill up all the fields!");
            }
        }