// GET: Quotations
        public ActionResult Index(string searchQuotationNumber, string currentFilterQuotationNumber ,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; }
            QuotationIndexViewModel qivm = new QuotationIndexViewModel();
            var quotations = from q in db.Quotations select q;
            Quotation quot = new Quotation();

            ViewBag.Error =  TempData["error"];
            //ViewBag.CurrentSort = sortOrder;

            ViewBag.QuotationSortParm = String.IsNullOrEmpty(sortOrder) ? "quot_asc" : "";
            ViewBag.CustomerSortParm = sortOrder=="cust" ? "cust_desc" : "cust";

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

            if (!String.IsNullOrEmpty(searchQuotationNumber))
            {
                quotations = quotations.Where(q => q.QuotationNumber.ToString().Contains(searchQuotationNumber));
            }
            if (!String.IsNullOrEmpty(searchCustomer))
            {
                quotations = quotations.Where(q => q.LastName.ToUpper().Contains(searchCustomer.ToUpper()) || q.FirstName.ToUpper().Contains(searchCustomer.ToUpper()));
            }
            if (!string.IsNullOrEmpty(searchDelivery))
            {
                quotations = quotations.Where(q => q.customerDeliveryAddress.DeliveryAddressInfo.ToUpper().Contains(searchDelivery.ToUpper()) || q.customerDeliveryAddress.StreetName.ToUpper().Contains(searchDelivery.ToUpper()) || q.customerDeliveryAddress.Town.ToUpper().Contains(searchDelivery.ToUpper()));
            }

            switch(sortOrder)
            {
                case "quot_asc":
                    quotations = quotations.OrderBy(s => s.QuotationNumber);
                    break;
                case "cust_desc":
                    quotations = quotations.OrderByDescending(s => s.LastName);
                    break;
                case "cust":
                    quotations = quotations.OrderBy(s => s.LastName);
                    break;
                default:
                    quotations = quotations.OrderByDescending(s => s.QuotationNumber);
                    break;
            }

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

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

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

            return View(qivm);
        }
        private Quotation DefaultQuotationInfo(Quotation quotation)
        {
            //basis info invullen in quotation
            //ophalen van lijst quotations voor vinden van laatste quotationnummer en dan +1
            var listquotations = new List<Quotation>();
            listquotations = db.Quotations.ToList();
            var userSettings = db.UserDefinedSettings.Find(1);
            int expirationDateLengt = userSettings.ExpirationDateLength;

            int maxQuotationnumber = 1;
            quotation.QuotationNumber = maxQuotationnumber;
            if (listquotations.Count != 0)
            {
                maxQuotationnumber = listquotations.Max(r => r.QuotationNumber);
                quotation.QuotationNumber = maxQuotationnumber + 1;
            }
            quotation.Active = true;
            quotation.Date = DateTime.Now;
            quotation.ExpirationDate = quotation.Date.AddMonths(expirationDateLengt);

            return quotation;
        }
        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");
        }
        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);
            }
            Quotation quotation = new Quotation();
            QuotationAddProductsViewModel qapvm = new QuotationAddProductsViewModel();
            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);
            qapvm.products = productList.ToPagedList(pageNumber, pageSize);

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

            quotation = db.Quotations.Find(id);
            if (quotation == null)
            {
                return HttpNotFound();
            }
            qapvm.quotation = quotation;
            CalculateTotalPriceinc(id);

            return View("AddProducts", qapvm);
        }
        public ActionResult CreateAndAddProducts([ModelBinder(typeof(QuotationBinderCreate))]  QuotationCreateViewModel qcvm, string[] DeliveryID)
        {
            if (ModelState.IsValid)
            {
                //aanmaken van quotation / customerdeliveryaddress en customer
                Quotation quotation = new Quotation();
                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
                DefaultQuotationInfo(quotation);
                quotation.FirstName = cus.FirstName;
                quotation.LastName = cus.LastName;
                quotation.Box = cus.Address.Box;
                quotation.CellPhone = cus.CellPhone;
                quotation.CustomerId = cus.CustomerId;
                quotation.Email = cus.Email;
                quotation.PostalCodeNumber = cus.Address.PostalCodeNumber;
                quotation.StreetName = cus.Address.StreetName;
                quotation.StreetNumber = cus.Address.StreetNumber;
                quotation.Town = cus.Address.Town;
                quotation.Annotation = qcvm.quotation.Annotation;
                quotation.customerDeliveryAddress = db.CustomerDeliveryAddresses.Find(DeliveryId);

                //toevoegen en saven
                db.Quotations.Add(quotation);
                db.SaveChanges();

                int id = quotation.QuotationId;
                TempData["id"] = id;
                return RedirectToAction("AddProducts");

            }
            return View(qcvm);
        }
        // GET: Quotations/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
            QuotationCreateViewModel qcvm = new QuotationCreateViewModel();
            var customerList = from a in db.Customers select a;
            Quotation quotation = new Quotation();

            DefaultQuotationInfo(quotation);

            qcvm.quotation = quotation;

            //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);

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

            return View(qcvm);
        }
        public ActionResult CopyQuotation(int? Id)
        {
            Quotation quotNew = new Quotation();
            Quotation quotOld = new Quotation();
            quotOld = db.Quotations.Find(Id);

            //check of er al een copy is
            List<Quotation> quotlist = db.Quotations.ToList();
            var checkQuotNumber  = quotlist.Where(q => q.QuotationNumber == quotOld.QuotationNumber);

            if (checkQuotNumber.Count() == 1)
            {
                quotNew.Annotation = quotOld.Annotation + " - Copy";
                quotNew.Active = quotOld.Active;
                quotNew.Box = quotOld.Box;
                quotNew.CellPhone = quotOld.CellPhone;
                quotNew.CustomerId = quotOld.CustomerId;
                quotNew.Date = quotOld.Date;
                quotNew.Email = quotOld.Email;
                quotNew.ExpirationDate = quotOld.ExpirationDate;
                quotNew.FirstName = quotOld.FirstName;
                quotNew.LastName = quotOld.LastName;
                quotNew.PostalCodeNumber = quotOld.PostalCodeNumber;
                quotNew.QuotationNumber = quotOld.QuotationNumber;
                quotNew.StreetName = quotOld.StreetName;
                quotNew.StreetNumber = quotOld.StreetNumber;
                quotNew.TotalPrice = 0;
                quotNew.Town = quotOld.Town;

                db.Quotations.Add(quotNew);
                db.SaveChanges();

                var delivery = db.CustomerDeliveryAddresses.Find(quotOld.customerDeliveryAddress.CustomerDeliveryAddressId);
                quotNew.customerDeliveryAddress = delivery;

                foreach (var item in quotOld.QuotationDetail)
                {

                    var qd = new QuotationDetail();
                    qd.Quantity = 1;
                    qd.PriceExVAT = 0;
                    qd.TotalExVat = 0;
                    qd.TotalIncVat = 0;
                    qd.Auvibel = item.Auvibel;
                    qd.Bebat = item.Bebat;
                    qd.Brand = item.Brand;
                    qd.CategoryId = item.CategoryId;
                    qd.Description = item.Description;
                    qd.ProductCode = item.ProductCode;
                    qd.ProductName = item.ProductName;
                    qd.Recupel = item.Recupel;
                    qd.Reprobel = item.Reprobel;
                    qd.VATPercId = item.VATPercId;
                    qd.ProductId = item.ProductId;
                    qd.QuotationId = quotNew.QuotationId;
                    qd.VAT = item.VAT;
                    db.QuotationDetails.Add(qd);

                }

                db.SaveChanges();
            }
            else
            {
                TempData["error"] = "Er is reeds een copy van deze offerte";
            }
            return RedirectToAction("index");
        }