// GET: Orders
        public ActionResult Index(string searchOrderNumber, string currentFilterOrderNumber, string searchCustomer, string currentFilterCustomer, string searchDelivery, string currentFilterDelivery, bool? searchNonActive, bool? currentFilterNonActive, int? page, string sortOrder)
        {
            // viewmodel aanmaken + vullen tijdelijke lijst
            if (searchNonActive == null) { searchNonActive = false; }
            if (currentFilterNonActive == null) { currentFilterNonActive = false; }
            OrderIndexViewModel oivm = new OrderIndexViewModel();
            var orders = from o in db.Orders select o;
            Order order = new Order();

            ViewBag.OrderSortParm = String.IsNullOrEmpty(sortOrder) ? "order_asc" : "";
            ViewBag.CustomerSortParm = sortOrder == "cust" ? "cust_desc" : "cust";

            if (searchCustomer != null || searchOrderNumber != null)
            {
                page = 1;
            }
            else
            {
                searchOrderNumber = currentFilterOrderNumber;
                searchCustomer = currentFilterCustomer;
                searchDelivery = currentFilterDelivery;
                searchNonActive = currentFilterNonActive;
            }
            ViewBag.CurrentFilterQuotation = searchOrderNumber;
            ViewBag.CurrentFilterCustomer = searchCustomer;
            ViewBag.CurrentFilterDelivery = searchDelivery;
            ViewBag.CurrentFilterNonActive = searchNonActive;

            if (!String.IsNullOrEmpty(searchOrderNumber))
            {
                orders = orders.Where(o => o.OrderNumber.ToString().Contains(searchOrderNumber));
            }
            if (!String.IsNullOrEmpty(searchCustomer))
            {
                orders = orders.Where(o => o.LastName.ToUpper().Contains(searchCustomer.ToUpper()) || o.FirstName.ToUpper().Contains(searchCustomer.ToUpper()));
            }
            if (!string.IsNullOrEmpty(searchDelivery))
            {
                orders = orders.Where(o => o.customerDeliveryAddress.DeliveryAddressInfo.ToUpper().Contains(searchDelivery.ToUpper()) || o.customerDeliveryAddress.StreetName.ToUpper().Contains(searchDelivery.ToUpper()) || o.customerDeliveryAddress.Town.ToUpper().Contains(searchDelivery.ToUpper()));
            }

            switch (sortOrder)
            {
                case "order_asc":
                    orders = orders.OrderBy(o => o.OrderNumber);
                    break;
                case "cust_desc":
                    orders = orders.OrderByDescending(o => o.LastName);
                    break;
                case "cust":
                    orders = orders.OrderBy(o => o.LastName);
                    break;
                default:
                    orders = orders.OrderByDescending(o => o.OrderNumber);
                    break;
            }

            var userDefinedInfo = db.UserDefinedSettings.Find(1);
            int pageSize = userDefinedInfo.IndexResultLength;
            int pageNumber = (page ?? 1);

            if (searchNonActive == false || searchNonActive == null)
            {
                orders = orders.Where(o => o.Active.Equals(true));
            }

            //ViewBag.Quotations = quotations.ToPagedList(pageNumber, pageSize);
            oivm.orders = orders.ToPagedList(pageNumber, pageSize);

            return View(oivm);
        }
        private Order DefaultOrderInfo(Order order)
        {
            //basis info invullen in order
            //ophalen van lijst orders voor vinden van laatste ordernummer en dan +1
            var listOrders = new List<Order>();
            listOrders = db.Orders.ToList();
            var userSettings = db.UserDefinedSettings.Find(1);

            int maxOrdernumber = 1;
            order.OrderNumber = maxOrdernumber;
            if (listOrders.Count != 0)
            {
                maxOrdernumber = listOrders.Max(o => o.OrderNumber);
                order.OrderNumber = maxOrdernumber + 1;
            }
            order.Active = true;
            order.Date = DateTime.Now;

            return order;
        }
        public ActionResult AddProducts(int? id, int? page, string searchString, string currentFilterSearchString, string categoryId, string currentFilterCategoryId, string sortOrder)
        {
            if (id == null)
            {
                id = (int)TempData["id"];
            }

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Order order = new Order();
            OrderAddProductsViewModel oapvm = new OrderAddProductsViewModel();
            var productList = from p in db.Products select p;
            productList = productList.Where(p => p.Active.Equals(true));

            ViewBag.ProductSortParm = string.IsNullOrEmpty(sortOrder) ? "prod_desc" : "";

            //aanmaken product list + filtering

            //paging
            if (searchString != null || categoryId != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilterSearchString;
                categoryId = currentFilterCategoryId;
            }
            ViewBag.CurrentFilterSearchString = searchString;
            ViewBag.CurrentFilterCategoryId = categoryId;

            // Zoekfunctie
            if (!String.IsNullOrEmpty(searchString))
            {
                productList = productList.Where(x => x.ProductName.ToUpper().Contains(searchString.ToUpper()) || x.ProductCode.ToUpper().Contains(searchString.ToUpper()));
            }
            if (!String.IsNullOrEmpty(categoryId))
            {
                int catId = int.Parse(categoryId);
                productList = productList.Where(x => x.CategoryId == catId);
            }

            switch (sortOrder)
            {
                case "prod_dec":
                    productList = productList.OrderByDescending(p => p.ProductName);
                    break;
                default:
                    productList = productList.OrderBy(p => p.ProductName);
                    break;
            }

            var userDefinedInfo = db.UserDefinedSettings.Find(1);
            int pageSize = userDefinedInfo.DetailsResultLength;
            int pageNumber = (page ?? 1);
            oapvm.products = productList.ToPagedList(pageNumber, pageSize);

            ViewBag.CategoryId = new SelectList(db.Categories, "CategoryID", "CategoryName", categoryId);

            order = db.Orders.Find(id);
            if (order == null)
            {
                return HttpNotFound();
            }
            oapvm.order = order;
            CalculateTotalPriceinc(id);

            return View("AddProducts", oapvm);
        }
        public ActionResult CreateInvoice(int? Id)
        {
            Order order = new Order();
            Invoice invoice = new Invoice();
            order = db.Orders.Find(Id);

            invoice.Annotation = order.Annotation + " - Factuur van order " + order.OrderNumber;
            invoice.Box = order.Box;
            invoice.CellPhone = order.CellPhone;
            invoice.CustomerId = order.CustomerId;
            invoice.Date = order.Date;
            invoice.Email = order.Email;
            invoice.FirstName = order.FirstName;
            invoice.LastName = order.LastName;
            invoice.PostalCodeNumber = order.PostalCodeNumber;
            invoice.StreetName = order.StreetName;
            invoice.StreetNumber = order.StreetNumber;
            invoice.TotalPrice = order.TotalPrice;
            invoice.Town = order.Town;
            invoice.Active = true;
            order.Active = false;

            db.Invoices.Add(invoice);
            db.SaveChanges();

            invoice.customerDeliveryAddress = order.customerDeliveryAddress;

            //find highest order number
            int maxInvoiceNumber = 1;
            invoice.InvoiceNumber = maxInvoiceNumber;
            var listInvoices = db.Invoices.ToList();

            if (listInvoices.Count > 1)
            {
                maxInvoiceNumber = listInvoices.Max(i => i.InvoiceNumber);
                invoice.InvoiceNumber = maxInvoiceNumber + 1;
            }

            foreach (var item in order.OrderDetail)
            {
                var id = new InvoiceDetail();
                id.InvoiceId = invoice.InvoiceId;
                id.Quantity = item.Quantity;
                id.PriceExVAT = item.PriceExVAT;
                id.TotalExVat = item.TotalExVat;
                id.TotalIncVat = item.TotalIncVat;
                id.Auvibel = item.Auvibel;
                id.Bebat = item.Bebat;
                id.Brand = item.Brand;
                id.CategoryId = item.CategoryId;
                id.Description = item.Description;
                id.ProductCode = item.ProductCode;
                id.ProductName = item.ProductName;
                id.Recupel = item.Recupel;
                id.Reprobel = item.Reprobel;
                id.VATPercId = item.VATPercId;
                id.ProductId = item.ProductId;
                id.VAT = item.VAT;
                db.InvoiceDetails.Add(id);
            }

            db.SaveChanges();
            return RedirectToAction("Index", "Invoices");
        }
        public ActionResult CreateAndAddProducts([ModelBinder(typeof(OrderBinderCreate))]  OrderCreateViewModel ocvm, string[] DeliveryID)
        {
            if (ModelState.IsValid)
            {
                //aanmaken van quotation / customerdeliveryaddress en customer
                Order order = new Order();
                CustomerDeliveryAddress cda = new CustomerDeliveryAddress();
                Customer cus = new Customer();

                //ophalen van customerDeliveryAddressID vanuit de array
                // eventueel nog test inbouwen voor lengte van array (check dat ze niet meer als 1 veld selecteren)
                int DeliveryId = 1;
                if (DeliveryID.Length == 1)
                {
                    DeliveryId = Int32.Parse(DeliveryID.First());
                }
                else
                {
                    return RedirectToAction("Create");
                }

                // ophalen delivery info en van daaruit customer info
                cda = db.CustomerDeliveryAddresses.Find(DeliveryId);
                cus = db.Customers.Find(cda.CustomerId);

                // invullen van de klant info in de quotation
                DefaultOrderInfo(order);
                order.FirstName = cus.FirstName;
                order.LastName = cus.LastName;
                order.Box = cus.Address.Box;
                order.CellPhone = cus.CellPhone;
                order.CustomerId = cus.CustomerId;
                order.Email = cus.Email;
                order.PostalCodeNumber = cus.Address.PostalCodeNumber;
                order.StreetName = cus.Address.StreetName;
                order.StreetNumber = cus.Address.StreetNumber;
                order.Town = cus.Address.Town;
                order.Annotation = ocvm.order.Annotation;
                order.customerDeliveryAddress = db.CustomerDeliveryAddresses.Find(DeliveryId);

                //toevoegen en saven
                db.Orders.Add(order);
                db.SaveChanges();

                int id = order.OrderId;
                TempData["id"] = id;
                return RedirectToAction("AddProducts");

            }
            return View(ocvm);
        }
        // GET: Orders/Create
        public ActionResult Create(string sortOrder, string searchStringName, string searchStringTown, string currentFilterName, string currentFilterTown, int? page)
        {
            // quotation viewmodel + ipaged list users aanmaken + nieuwe quotation voor default stuff
            OrderCreateViewModel ocvm = new OrderCreateViewModel();
            var customerList = from a in db.Customers select a;
            Order order = new Order();

            DefaultOrderInfo(order);

            ocvm.order = order;

            //zoeken / sorteren / paging
            //sorteren  default op "name_desc"
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.TownSortParm = sortOrder == "town" ? "town_desc" : "town";

            // als zoeken leeg is pagina 1 anders
            if (searchStringTown != null || searchStringName != null)
            {
                page = 1;
            }
            else
            {
                searchStringName = currentFilterName;
                searchStringTown = currentFilterTown;
            }
            ViewBag.CurrentFilterName = searchStringName;
            ViewBag.CurrentFilterTown = searchStringTown;

            // zoekvelden toepassen op klantenlijst
            //zoeken op naam (voor of achter en/of gemeente)
            if (!String.IsNullOrEmpty(searchStringTown))
            {
                customerList = customerList.Where(s => s.Address.Town.ToUpper().Contains(searchStringTown.ToUpper()));
            }

            // zoeken op postalcode
            if (!String.IsNullOrEmpty(searchStringName))
            {
                customerList = customerList.Where(s => s.LastName.ToUpper().Contains(searchStringName.ToUpper()) ||
                s.FirstName.ToUpper().Contains(searchStringName.ToUpper()));
            }

            switch (sortOrder)
            {
                case "name_desc":
                    customerList = customerList.OrderByDescending(s => s.LastName);
                    break;
                case "town":
                    customerList = customerList.OrderBy(s => s.Address.Town);
                    break;
                case "town_desc":
                    customerList = customerList.OrderByDescending(s => s.Address.Town);
                    break;
                default:
                    customerList = customerList.OrderBy(s => s.LastName);
                    break;
            }

            var userDefinedInfo = db.UserDefinedSettings.Find(1);
            int pageSize = userDefinedInfo.DetailsResultLength;
            int pageNumber = (page ?? 1);

            ocvm.customers = customerList.ToPagedList(pageNumber, pageSize);

            return View(ocvm);
        }
        public ActionResult CreateOrder(int? Id)
        {
            Order order = new Order();
            Quotation quot = new Quotation();
            quot = db.Quotations.Find(Id);

            order.Annotation = quot.Annotation + " - Order van Offerte " + quot.QuotationNumber;
            order.Box = quot.Box;
            order.CellPhone = quot.CellPhone;
            order.CustomerId = quot.CustomerId;
            order.Date = quot.Date;
            order.Email = quot.Email;
            order.FirstName = quot.FirstName;
            order.LastName = quot.LastName;
            order.PostalCodeNumber = quot.PostalCodeNumber;
            order.StreetName = quot.StreetName;
            order.StreetNumber = quot.StreetNumber;
            order.TotalPrice = quot.TotalPrice;
            order.Town = quot.Town;
            order.Active = true;
            quot.Active = false;

            db.Orders.Add(order);
            db.SaveChanges();

            order.customerDeliveryAddress = quot.customerDeliveryAddress;

            //find highest order number
            int maxOrderNumber = 1;
            order.OrderNumber = maxOrderNumber;
            var listOrders = db.Orders.ToList();

            if (listOrders.Count > 1)
            {
                maxOrderNumber = listOrders.Max(o => o.OrderNumber);
                order.OrderNumber = maxOrderNumber + 1;
            }

            foreach (var item in quot.QuotationDetail)
            {
                var od = new OrderDetail();
                od.OrderId = order.OrderId;
                od.Quantity = item.Quantity;
                od.PriceExVAT = item.PriceExVAT;
                od.TotalExVat = item.TotalExVat;
                od.TotalIncVat = item.TotalIncVat;
                od.Auvibel = item.Auvibel;
                od.Bebat = item.Bebat;
                od.Brand = item.Brand;
                od.CategoryId = item.CategoryId;
                od.Description = item.Description;
                od.ProductCode = item.ProductCode;
                od.ProductName = item.ProductName;
                od.Recupel = item.Recupel;
                od.Reprobel = item.Reprobel;
                od.VATPercId = item.VATPercId;
                od.ProductId = item.ProductId;
                od.VAT = item.VAT;
                db.OrderDetails.Add(od);
            }

            db.SaveChanges();
            return RedirectToAction("Index", "Orders");
        }