public List<CorporateCustomer> GetListOfCorporateCustomers()
        {
            var db = new IstokDoorsDBContext();

            var model =
                db.Customers.Where(i => i.CustomerType == "Corporate Customer")
                    .OrderBy(i => i.ContactPersonName)
                    .ThenBy(i => i.ContactPersonMiddleName)
                    .ThenBy(i => i.ContactPersonSurname)
                    .ToList();

            return model.Select(item => new CorporateCustomer
            {   
                CustomerId = item.CustomerId,
                CompanyName = item.CompanyName,
                ContactPersonName = item.ContactPersonName,
                ContactPersonMiddleName = item.ContactPersonMiddleName,
                ContactPersonSurname = item.ContactPersonSurname,
                ConcactPersonEmail = item.ConcactPersonEmail,
                ContactPersonPhone2 = item.ContactPersonPhone2,
                ContactPersonPhone1 = item.ContactPersonPhone1,
                CustomerAddress = item.CustomerAddress,
                PostCode = item.PostCode,
                City = item.City,
                Country = item.Country,
                CompanyPhoneNumber = item.CompanyPhoneNumber,
                MarkedForDeletion = item.MarkedForDeletion
            }).ToList();


        }
        public static void MarkOrdersForAllocation(List<OrderHeaderViewModel> orders)
        {
            var db = new IstokDoorsDBContext();
            var ordersForAllocation =
                db.OrderHeaders.Include(o => o.Customer)
                    .Include(o => o.Factory)
                    .Include(o => o.OrderFulfillmentSchedule)
                    .Include(o => o.OrderStatu)
                    .Include(o => o.PaymentTerm)
                    .Where(o => o.OrderStatu.OrderStatusId == 0 && o.IsSelectedForAllocation == false && o.IsCancelled == false);

            foreach (var orderToAllocate in ordersForAllocation)
            {
                for (int i = 0; i < orders.Count; i++)
                {
                    if (orderToAllocate.OrderId == orders[i].OrderId && orders[i].IsSelectedForAllocation == true)
                    {
                        orderToAllocate.IsSelectedForAllocation = true;
                        orderToAllocate.OrderStatusId = 2;
                    }

                }

            }

            db.SaveChanges();

        }
        public static IEnumerable<SelectListItem> GetCustomerDropDownList()
        {
            var db = new IstokDoorsDBContext();

            var customerList = db.Customers.ToList();
            var dropDownCustomerList = new List<SelectListItem>();

            foreach (var customer in customerList)
            {
                var customerId = customer.CustomerId;
                string customerName = customer.CompanyName;

                if (String.IsNullOrEmpty(customerName))
                {
                    customerName = customer.ContactPersonName + "  " + customer.ContactPersonSurname;
                }


                dropDownCustomerList.Add(new SelectListItem
                {
                    Text = customerName,
                    Value = customerId.ToString(CultureInfo.InvariantCulture)
                });


            }

            return dropDownCustomerList;
        }
        public static IEnumerable<SelectListItem> GetDropDownListFactories()
        {
             
           var db = new IstokDoorsDBContext();

            var facotries = db.Factories.ToList();

            var dropDownListFactories = (from t in facotries
                let factroyId = t.FactoryId
                let doorData = t.FactoryName
                select new SelectListItem
                {
                    Text = doorData,
                    Value = factroyId.ToString(CultureInfo.InvariantCulture),
                }).ToList().OrderBy(x => x.Text);

            return dropDownListFactories;
        }
        public static List<OrderHeaderViewModel> ConvertListsForOrdersToAllocate()
        {
            var db = new IstokDoorsDBContext();
            var ordersForAllocation =
                db.OrderHeaders.Include(o => o.Customer)
                    .Include(o => o.Factory)
                    .Include(o => o.OrderFulfillmentSchedule)
                    .Include(o => o.OrderStatu)
                    .Include(o => o.PaymentTerm)
                    .Where(
                        o =>
                            o.OrderStatu.OrderStatusId == 0 && o.IsSelectedForAllocation == false &&
                            o.IsCancelled == false);

            var myOrderHeaders = new List<OrderHeaderViewModel>();
            foreach (var item in ordersForAllocation)
            {
                var myOrderHeaderViewModel = new OrderHeaderViewModel();
                myOrderHeaderViewModel.OrderId = item.OrderId;
                myOrderHeaderViewModel.DateOfCreation = item.DateOfCreation;
                myOrderHeaderViewModel.OrderStatus = item.OrderStatu.OrderStatusDescription;
                myOrderHeaderViewModel.IsSelectedForAllocation = item.IsSelectedForAllocation;
                if (!String.IsNullOrEmpty(item.Customer.CompanyName))
                {
                    myOrderHeaderViewModel.Customer = item.Customer.CompanyName;
                }
                else
                {
                    myOrderHeaderViewModel.Customer = item.Customer.ContactPersonName + " " +
                                                      item.Customer.ContactPersonSurname;
                }

                myOrderHeaders.Add(myOrderHeaderViewModel);
            }

            return myOrderHeaders;
        }
        public static IEnumerable<SelectListItem> GetPaymentTermsDropDownList()
        {
            var db = new IstokDoorsDBContext();
            
            var paymentTermsList = db.PaymentTerms.ToList();

            var dropDownPaymentTermList = new List<SelectListItem>();

            foreach (var paymentTerm in paymentTermsList)
            {
                var paymentTermId = paymentTerm.PaymentTermId;
                var paymentTermName = paymentTerm.PaymentTermName;

                dropDownPaymentTermList.Add(new SelectListItem
                {
                    Text = paymentTermName,
                    Value = paymentTermId.ToString(CultureInfo.InvariantCulture)
                });


            }

            return dropDownPaymentTermList;
        }
        //================================== PLAN QUANTITIES FOR PRODUCTION ===========================
        public static void PlanQuantitiesForProduction(List<ViewPlanningJournal> myPlanJrnlList)
        {
            var db = new IstokDoorsDBContext();

            for (int i = 0; i < myPlanJrnlList.Count; i++)
            {
                db.usp_PlanQuantitiesForProduction(myPlanJrnlList[i].OrderId, myPlanJrnlList[i].OrderItemId,
                    myPlanJrnlList[i].FactoryId, myPlanJrnlList[i].AllocateFromInventory);


            }

            db.SaveChanges();

        }
 //========================== CHECK ORDER IS COMPLETE AFTER ALLOCATION FROM INVENTORY==========================
 public static void CheckOrderCompletionAfterAllocationFromInventory(List<ViewPlanningJournal> myPlanJrnlList)     
 {
      var db = new IstokDoorsDBContext();
     for (int i = 0; i < myPlanJrnlList.Count; i++)
     {
         db.usp_CheckOrderForCompletionStatus4(myPlanJrnlList[i].OrderId);
     }
 
 
 
 
 }
        public static OrderScheduleViewModel GetOrderSchedulebyId(int? id)
        {
            var db = new IstokDoorsDBContext();
            var myOrderSchedule = db.usp_GetOrderScheduleById(id).Single();
            //TODO: Don't forget to add Single method to materialize the object!!!

            var myOrderScheduleViewModel = new OrderScheduleViewModel();

            myOrderScheduleViewModel.OrderId = myOrderSchedule.OrderId;
            myOrderScheduleViewModel.FactoryName = myOrderSchedule.FactoryName;
            myOrderScheduleViewModel.FactoryId = myOrderSchedule.FactoryId??1;
            myOrderScheduleViewModel.DateOfCreation = myOrderSchedule.DateOfCreation;
            myOrderScheduleViewModel.DateEntryToFactory = myOrderSchedule.DateEntryToFactory;
            myOrderScheduleViewModel.PlannedDateOfManufacture = myOrderSchedule.PlannedDateOfManufactoring;
            myOrderScheduleViewModel.PlannedDateOfShipping = myOrderSchedule.PlannedDateOfShipping;
            myOrderScheduleViewModel.ActualDateOfManufacture = myOrderSchedule.ActualDateOfManufactoring;
            myOrderScheduleViewModel.ActualDateOfShipping = myOrderSchedule.ActualDateOfShipping;

            return myOrderScheduleViewModel;

        }
        public static void SaveOrderItems(IEnumerable<OrderItem> orderItems)
        {
            var db = new IstokDoorsDBContext();

            foreach (var item in orderItems)
            {
                item.OrderId = LastOrderId.OrderId;

                {
                    db.usp_CreateOrderItem(item.OrderId, item.DoorId, item.Quantity, item.Discount);
                    //db.OrderItems.Add(item);
                    db.SaveChanges();
                }

            }

        }
        public static List<SelectListItem> GetValuesForOrderCompletionJournalDdL(int allocValueForDDList,
            int isManufacturedForOrder)
        {
            var db = new IstokDoorsDBContext();

            var dropDownListItems = new List<SelectListItem>();
            for (int i = 0; i < allocValueForDDList + 1; i++)
            {
                dropDownListItems.Add(new SelectListItem
                {
                    Text = i.ToString(CultureInfo.InvariantCulture),
                    Value = i.ToString(CultureInfo.InvariantCulture),
                });
            }

            var selectedItem = dropDownListItems.First(x => x.Value == isManufacturedForOrder.ToString());
            selectedItem.Selected = true;

            return dropDownListItems;
        }
        public static void UpdateDateOfBatchCompletion(List<ProductionJournal> myProductionJournal)
        {
            var db = new IstokDoorsDBContext();

            var dbProdJrnlList = db.ProductionJournals.ToList();

            foreach (var item in dbProdJrnlList)
            {
                for (int i = 0; i < myProductionJournal.Count; i++)
                {


                    if (myProductionJournal[i].IsManufacturedForBatch == item.ToBeManufacturedForBatch &&
                        item.DateOfBatchCompletion == null && myProductionJournal[i].FactoryId == item.FactoryId && myProductionJournal[i].DoorId == item.DoorId)
                    {
                        item.DateOfBatchCompletion = DateTime.Now;
                    }
                }

            }

            db.SaveChanges();
        }
        public static void UpdateAwaitingAllocQuantityForPlnJrnl(List<ProductionJournal> myProductionJournal)
        {
            var db = new IstokDoorsDBContext();

            


            for (int i = 0; i < myProductionJournal.Count; i++)
            {

                db.usp_UpdateAwaitingAllocQuantityForPlanningJournal(myProductionJournal[i].IsManufacturedForBatch,
                    myProductionJournal[i].FactoryId, myProductionJournal[i].BatchId, myProductionJournal[i].DoorId);

            }

        }
        public static void AllocateOrdersToFactories(List<AllocationJournal> myAllJournalList)
        {
            var db = new IstokDoorsDBContext();


            for (int i = 0; i < myAllJournalList.Count; i++)
            {
                db.usp_CalculateQuantityInProduction(myAllJournalList[i].FactoryId);
                AllocationJournal allocationjournal = db.AllocationJournals.Find(myAllJournalList[i].OrderId);
                allocationjournal.FactoryId = myAllJournalList[i].FactoryId;

                db.SaveChanges();
            }


        }
        public static IEnumerable<AllocAnalysisDoorsInProduction> GetProductionNumbersForFactories()
        {
            var db = new IstokDoorsDBContext();


            var factories = db.usp_GetValidFactoriesFromAllocJournal();

            db.usp_FindHowManyDoorsInProductionPerFactory();

            foreach (var factory in factories)
            {
                db.usp_CalculateQuantityInProduction(factory);
            }

            var productionNumbers = db.AllocAnalysisDoorsInProductions.ToList();



            return productionNumbers;
        }
        public static List<SelectListItem> GetValuesForAllocJournFactoriesDdl(int? factoryId)
        {
            var db = new IstokDoorsDBContext();
            var factories = db.Factories.ToList();

            var myFactories = new List<SelectListItem>();


            foreach (var item in factories)
            {
                SelectListItem otherOne = new SelectListItem();
                otherOne.Text = item.FactoryName;
                otherOne.Value = item.FactoryId.ToString();
                myFactories.Add(otherOne);

            }



            var selectedItem = myFactories.FirstOrDefault(x => x.Value == factoryId.ToString());
            if (selectedItem != null)
            {
                selectedItem.Selected = true;
            }
            else
            {
                selectedItem = myFactories[0];
                selectedItem.Selected = true;
            }


            return myFactories;
        }
        public static List<AllocationJournalViewModel> GetAllocationJournal()
        {
            var db = new IstokDoorsDBContext();
            db.usp_FillInAllocationJournalBySystem();

            var myAllocationJournal = db.AllocationJournals.Include(o=>o.OrderHeader).
                Where(o => o.OrderHeader.IsCancelled == false).ToList();

            var myAllocJournList = new List<AllocationJournalViewModel>();

            foreach (var item in myAllocationJournal)
            {
                var myModel = new AllocationJournalViewModel();

                myModel.OrderId = item.OrderId;
                myModel.FactoryId = item.FactoryId ?? 0;
                myModel.OrderedQuantity = item.OrderedQuantity ?? 0;
                myModel.IsSelectedForPlanning = false;
                myModel.Customer = item.Customer;
                myModel.FactoriesForAllocJournal = GetValuesForAllocJournFactoriesDdl(item.FactoryId);

                myAllocJournList.Add(myModel);
            }


            return myAllocJournList;


        }
        public static void SaveOrder(OrderHeader orderHeader)
        {
            var db = new IstokDoorsDBContext();


            var myOrderHeader = new OrderHeader();
            myOrderHeader.OrderId = orderHeader.OrderId;
            myOrderHeader.CustomerId = orderHeader.CustomerId;
            myOrderHeader.PaymentTermId = orderHeader.PaymentTermId;
            myOrderHeader.DateOfCreation = orderHeader.DateOfCreation;
            myOrderHeader.Memo = orderHeader.Memo;
            myOrderHeader.OrderStatusId = 0;


            db.OrderHeaders.Add(myOrderHeader);


            var myOrderSchedule = new OrderFulfillmentSchedule();
            myOrderSchedule.OrderId = orderHeader.OrderId;
            myOrderSchedule.PlannedDateOfManufactoring = orderHeader.OrderFulfillmentSchedule.PlannedDateOfManufactoring;
            myOrderSchedule.PlannedDateOfShipping = orderHeader.OrderFulfillmentSchedule.PlannedDateOfShipping;


            db.OrderFulfillmentSchedules.Add(myOrderSchedule);

            db.SaveChanges();

            var lastOrderId = db.OrderHeaders.OrderByDescending(o => o.OrderId).FirstOrDefault();
            LastOrderId.OrderId = lastOrderId.OrderId;
        }
        public static void SaveOrderSchedule(OrderScheduleViewModel myOrderScheduleViewModel)
        {
            var db = new IstokDoorsDBContext();

            var myOrderScheduleMvc = db.OrderFulfillmentSchedules.Find(myOrderScheduleViewModel.OrderId);


            myOrderScheduleMvc.DateEntryToFactory = myOrderScheduleViewModel.DateEntryToFactory;
            myOrderScheduleMvc.PlannedDateOfManufactoring = myOrderScheduleViewModel.PlannedDateOfManufacture;
            myOrderScheduleMvc.PlannedDateOfShipping = myOrderScheduleViewModel.PlannedDateOfShipping;
            myOrderScheduleMvc.ActualDateOfManufactoring = myOrderScheduleViewModel.ActualDateOfManufacture;
            myOrderScheduleMvc.ActualDateOfShipping = myOrderScheduleViewModel.ActualDateOfShipping;

            db.SaveChanges();

        }
        //================================== GET PRODUCTION JOURNAL FOR FACTROY ID ===========================
        public static List<ProductionJournal> GetProductionJournalForFactId(int factoryId)
        {
            var db = new IstokDoorsDBContext();
            var dbProdJrnlList =
                db.ProductionJournals.Include(f => f.Factory).Where(f => f.FactoryId == factoryId).ToList();

            var myProductionJournalLsit = new List<ProductionJournal>();

            foreach (var item in dbProdJrnlList)
            {
                ProductionJournal myPrdJrnl = new ProductionJournal();
                myPrdJrnl.BatchId = item.BatchId;
                myPrdJrnl.FactoryName = item.Factory.FactoryName;
                myPrdJrnl.FactoryId = factoryId;
                myPrdJrnl.DoorId = item.DoorId;
                myPrdJrnl.DoorName = item.Door.Model + " "  + item.Door.CanvasSize + " " + item.Door.Color;   
                myPrdJrnl.ToBeManufacturedForBatch = item.ToBeManufacturedForBatch;
                myPrdJrnl.IsManufacturedForBatch = item.IsManufacturedForBatch;
                myPrdJrnl.LeftToBeManufacturedForBatch = item.LeftToBeManufacturedForBatch;
                myPrdJrnl.DateOfBatchCompletion = item.DateOfBatchCompletion;
                //myPrdJrnl.DropDownListItems =
                //    ProjectMethods.ValuesForIsManufacturedForBatchDdl(item.ToBeManufacturedForBatch ?? 0,
                //        item.IsManufacturedForBatch ?? 0);
                myPrdJrnl.DropDownListItems =
    ProjectMethods.ValuesForIsManufacturedForBatchDdl(item.ToBeManufacturedForBatch  ,
        item.IsManufacturedForBatch );

                myProductionJournalLsit.Add(myPrdJrnl);
            }


            return myProductionJournalLsit;
        }
        //================================== GET VALUES FOR DDL LIST PLANNING JOURNAL ===========================
        public static List<SelectListItem> ValuesForIsManufacturedForBatchDdl(int ToBeManufacturedForBatch,
            int IsManufacturedForBatch)
        {
            var db = new IstokDoorsDBContext();

            var dropDownListItems = new List<SelectListItem>();
            for (int i = IsManufacturedForBatch; i < ToBeManufacturedForBatch + 1; i++)
            {
                dropDownListItems.Add(new SelectListItem
                {
                    Text = i.ToString(CultureInfo.InvariantCulture),
                    Value = i.ToString(CultureInfo.InvariantCulture),
                });
            }

            var selectedItem = dropDownListItems.First(x => x.Value == IsManufacturedForBatch.ToString());
            selectedItem.Selected = true;

            return dropDownListItems;
        }
        public static void MoveOrdersFromAllJournlToPlanJournl(List<AllocationJournal> myAllJournalList)
        {
            var db = new IstokDoorsDBContext();


            var orderHeaders = db.OrderHeaders.ToList();
            var allocOrders = db.AllocationJournals.ToList();

            //db.usp_FindHowManyDoorsInProductionPerFactory();

            foreach (var orderHeader in orderHeaders)
            {
                for (int i = 0; i < myAllJournalList.Count; i++)
                {
                    if (myAllJournalList[i].FactoryId > 0 && myAllJournalList[i].OrderId == orderHeader.OrderId)
                    {
                        orderHeader.OrderStatusId = 2;
                        orderHeader.FactoryId = myAllJournalList[i].FactoryId;

                        //Remove Allocated Order from Allocation Journal
                        AllocationJournal allocatedJournal = db.AllocationJournals.Find(myAllJournalList[i].OrderId);
                        db.AllocationJournals.Remove(allocatedJournal);


                    }

                }
            }


            db.SaveChanges();




        }
        public static void SaveProductionJournalUpdate(List<ProductionJournal> myProductionJournal)
        {
            var db = new IstokDoorsDBContext();

            //var  dbProdJrnlList = db.ProductionJournals.ToList();

            for (int i = 0; i < myProductionJournal.Count; i++)
            {

                var linqBatchId = myProductionJournal[i].BatchId;
                var linqFactoryId = myProductionJournal[i].FactoryId;
                var linqDoorId = myProductionJournal[i].DoorId;
                var dbItem = db.ProductionJournals.SingleOrDefault(b=>b.BatchId == linqBatchId && b.DoorId == linqDoorId && b.FactoryId == linqFactoryId);


                int? manufacturedDifference = myProductionJournal[i].IsManufacturedForBatch - dbItem.IsManufacturedForBatch;

                db.usp_UpdateAwaitingAllocQuantityForPlanningJournal(manufacturedDifference,
               dbItem.FactoryId, dbItem.BatchId, dbItem.DoorId);
               
                //Update InventoryJournal and InventoryBalance with Manufactured Quantities
                db.usp_UpdateInvenotriesWithManufacturedQuantities(dbItem.FactoryId, dbItem.DoorId, manufacturedDifference);

                //int quantityManufacuturedForBatch =  myProductionJournal[i].IsManufacturedForBatch;

                //dbItem.IsManufacturedForBatch = 2; // quantityManufacuturedForBatch;
                db.SaveChanges();



            }

            for (int i = 0; i < myProductionJournal.Count; i++)
            {

                var linqBatchId = myProductionJournal[i].BatchId;
                var linqFactoryId = myProductionJournal[i].FactoryId;
                var linqDoorId = myProductionJournal[i].DoorId;
                var dbItem = db.ProductionJournals.SingleOrDefault(b => b.BatchId == linqBatchId && b.DoorId == linqDoorId && b.FactoryId == linqFactoryId);


               
                int quantityManufacuturedForBatch =  myProductionJournal[i].IsManufacturedForBatch;

                dbItem.IsManufacturedForBatch = quantityManufacuturedForBatch;
               



            }
            db.SaveChanges();
            //for (int i = 0; i < myProductionJournal.Count; i++)
            //{
            //    foreach (var item in dbProdJrnlList)

            //    {
            //        if (myProductionJournal[i].BatchId == item.BatchId && myProductionJournal[i].DoorId == item.DoorId && myProductionJournal[i].IsManufacturedForBatch > item.IsManufacturedForBatch && myProductionJournal[i].FactoryId == item.FactoryId && myProductionJournal[i].DateOfBatchCompletion == null)
            //        {
            //            int? manufacturedDifference = myProductionJournal[i].IsManufacturedForBatch - item.IsManufacturedForBatch;

            //            db.usp_UpdateAwaitingAllocQuantityForPlanningJournal(manufacturedDifference,
            //           item.FactoryId, item.BatchId, item.DoorId);

            //            //Update InventoryJournal and InventoryBalance with Manufactured Quantities
            //            db.usp_UpdateInvenotriesWithManufacturedQuantities(item.FactoryId, item.DoorId, manufacturedDifference);


            //            item.IsManufacturedForBatch = myProductionJournal[i].IsManufacturedForBatch;

            //            //db.SaveChanges();

            //        }

            //    }

            //}

            //for (int i = 0; i < myProductionJournal.Count; i++)
            //{
            //    for (int j = 0; j < dbProdJrnlList.Count; j++)

            //    {
            //        if (myProductionJournal[i].BatchId == dbProdJrnlList[j].BatchId && myProductionJournal[i].DoorId == dbProdJrnlList[j].DoorId && myProductionJournal[i].IsManufacturedForBatch > dbProdJrnlList[j].IsManufacturedForBatch && myProductionJournal[i].FactoryId == dbProdJrnlList[j].FactoryId && myProductionJournal[i].DateOfBatchCompletion == null)
            //        {
            //            int? manufacturedDifference = myProductionJournal[i].IsManufacturedForBatch - dbProdJrnlList[j].IsManufacturedForBatch;

            //            db.usp_UpdateAwaitingAllocQuantityForPlanningJournal(manufacturedDifference,
            //            myProductionJournal[i].FactoryId, myProductionJournal[i].BatchId, myProductionJournal[i].DoorId);

            //            //Update InventoryJournal and InventoryBalance with Manufactured Quantities
            //            db.usp_UpdateInvenotriesWithManufacturedQuantities(myProductionJournal[i].FactoryId, myProductionJournal[i].DoorId, manufacturedDifference);


            //            //dbProdJrnlList[j].IsManufacturedForBatch = myProductionJournal[i].IsManufacturedForBatch;
            //            var linqFactoryId = myProductionJournal[i].FactoryId;
            //            var linqBatchId = myProductionJournal[i].BatchId;
            //            var iinqDoorId = myProductionJournal[i].DoorId;

            //            var batchToUpdate = db.ProductionJournals.SingleOrDefault(b => b.FactoryId == linqFactoryId && b.DoorId == iinqDoorId && b.BatchId == linqBatchId);

            //            batchToUpdate.IsManufacturedForBatch = myProductionJournal[i].IsManufacturedForBatch;

            //            db.SaveChanges();

            //        }
            //    }



        }
        //==========================================GET FACTORIES NAMES FOR PLANNING JOURNAL'S DDL================================



        public static List<string> GetFactoriesNamesForPlanningJournalList()
        {
            var db = new IstokDoorsDBContext();
            var factories = db.Factories.ToList().Where(f => f.FactoryId > 0);

            var factoriesNames = new List<string>();

            foreach (var factory in factories)
            {
                string fctrName = factory.FactoryName;

                factoriesNames.Add(fctrName);

            }

            return factoriesNames;

        }
        //========================== GET ORDER COMPLETION JOURNAL FOR FACTORY ID ===========================================
        public static List<ViewPlanningJournal> GetOrderCompletionJournalForFactId(int factoryId)
        {

            var db = new IstokDoorsDBContext();

            db.usp_FillInValuesForOrderCompletionDropDownList();

            var dbOrderCompletionJournal = db.usp_FillInOrderCompletionJournalByFactoryId(factoryId);
             


            var myOrderCompletionJournalList = new List<ViewPlanningJournal>();

            foreach (var item in dbOrderCompletionJournal)
            {

                ViewPlanningJournal myViewPlnJrnl = new ViewPlanningJournal();

                myViewPlnJrnl.OrderId = item.OrderId;
                myViewPlnJrnl.FactoryId = item.FactoryId;
                myViewPlnJrnl.FactoryName = item.FactoryName;
                myViewPlnJrnl.OrderItemId = item.OrderItemId;
                myViewPlnJrnl.DoorId = item.DoorId;
                myViewPlnJrnl.Model = item.Model;
                myViewPlnJrnl.Color = item.Color;
                myViewPlnJrnl.CanvasSize = item.CanvasSize;
                myViewPlnJrnl.OrderedQuantity = item.OrderedQuantity;
                myViewPlnJrnl.FreetoAllocate = item.FreetoAllocate;
                myViewPlnJrnl.AllocateFromInventory = item.AllocateFromInventory??0;
                myViewPlnJrnl.ToBeManufacturedForOrder = item.ToBeManufacturedForOrder;
                myViewPlnJrnl.IsManufacturedForOrder = item.IsManufacturedForOrder; //needed for Order Completion DDL
                myViewPlnJrnl.LeftToBeManufacturedForOrder = item.LeftToBeManufacturedForOrder;
                myViewPlnJrnl.OrderItemIsDone = item.OrderItemIsDone;
                myViewPlnJrnl.AwaitingAllocationToOrders = item.AwaitingAllocationToOrders;
                myViewPlnJrnl.IsSelectedForProduction = item.IsSelectedForProduction;
                myViewPlnJrnl.AllocValueForDDList = item.AllocValueForDDList ?? 0; //needed for max Order Completion DDL
                myViewPlnJrnl.DropDownListItems =
                    ProjectMethods.GetValuesForOrderCompletionJournalDdL(item.AllocValueForDDList ?? 0,
                        item.IsManufacturedForOrder ?? 0);

                myOrderCompletionJournalList.Add(myViewPlnJrnl);

            }



            return myOrderCompletionJournalList;
        }
        //================================== GET VALUES FOR DDL =============================================================
        public static List<SelectListItem> ValuesForPlanJournalDdL(int allocValueForDdList, int allocFromInventory)
        {
            var db = new IstokDoorsDBContext();

            var dropDownListItems = new List<SelectListItem>();
            for (int i = 0; i < allocValueForDdList + 1; i++)
            {
                dropDownListItems.Add(new SelectListItem
                {
                    Text = i.ToString(CultureInfo.InvariantCulture),
                    Value = i.ToString(CultureInfo.InvariantCulture),
                });
            }

            var selectedItem = dropDownListItems.First(x => x.Value == allocFromInventory.ToString());
            selectedItem.Selected = true;

            return dropDownListItems;
        }
        public static void PlanQuantitiesForOrderCompletion(List<ViewPlanningJournal> myOrderCompletionJrnl)
        {
            var db = new IstokDoorsDBContext();

            var dbOrderCompletionJrnl = db.PlanningJournals.ToList();

            //Save IsManufacturedForOrder to PlanningJournal
            foreach (var item in dbOrderCompletionJrnl)
            {
                for (int i = 0; i < myOrderCompletionJrnl.Count; i++)
                {

                    if (item.OrderId == myOrderCompletionJrnl[i].OrderId &&
                        item.OrderItemId == myOrderCompletionJrnl[i].OrderItemId)
                    {

                        if (item.IsManufacturedForOrder != myOrderCompletionJrnl[i].IsManufacturedForOrder)
                        {
                            //Calculate the difference between present and former IsManufacturedForOrder quantity
                            int calculatedManufacturedForOrder = myOrderCompletionJrnl[i].IsManufacturedForOrder -
                                                         item.IsManufacturedForOrder??0;

                            db.usp_PlanQuantitiesForOrderCompletion(myOrderCompletionJrnl[i].FactoryId,
                                myOrderCompletionJrnl[i].OrderId, myOrderCompletionJrnl[i].OrderItemId,
                                myOrderCompletionJrnl[i].DoorId, calculatedManufacturedForOrder);

                            item.IsManufacturedForOrder = myOrderCompletionJrnl[i].IsManufacturedForOrder;
                        }

                        //Check wether Order is Done (OrderStatus 4)

                      
                    }

                }
            }

          
            db.SaveChanges();

        }
        //================================== MOVE ORDERS FROM PLANNING JOURNAL TO PRODUCTION JOURNAL ===========================


        public static void SetTrueIsSelectedForProductionPlanJrnl(List<ViewPlanningJournal> myPlanJrnlList)
        {
            var db = new IstokDoorsDBContext();

            var dbPlanningJrnl = db.PlanningJournals.Include(oh => oh.OrderHeader).ToList();

            foreach (var item in dbPlanningJrnl)
            {
                for (int i = 0; i < myPlanJrnlList.Count; i++)
                {
                    if (item.OrderId == myPlanJrnlList[i].OrderId)
                    {
                        item.IsSelectedForProduction = true;
                       

                    }

                }

            }

            db.SaveChanges();


        }
        public static void CheckOrderIsCompleteOrderStatus4(List<ViewPlanningJournal> myOrderCompletionJrnl)
        {


            for (int i = 0; i < myOrderCompletionJrnl.Count; i++)
            {

                var db = new IstokDoorsDBContext();

                db.usp_CheckOrderForCompletionStatus4(myOrderCompletionJrnl[i].OrderId);



            }


        }
        public static List<OrderScheduleViewModel> ConvertListsForOrdersScheduleStatus4_5()
        {
            var db = new IstokDoorsDBContext();
            var myOrders = db.usp_GetOrdersSchedule().ToList();
            var myList = new List<OrderScheduleViewModel>();

            foreach (var item in myOrders)
            {

                var myOrder = new OrderScheduleViewModel();
                if (item.OrderStatusId > 3)
                {
                    myOrder.OrderId = item.OrderId;
                    myOrder.FactoryName = item.FactoryName;
                    myOrder.DateEntryToFactory = item.DateEntryToFactory;
                    myOrder.ActualDateOfManufacture = item.ActualDateOfManufactoring;
                    myOrder.PlannedDateOfManufacture = item.PlannedDateOfShipping;
                    myOrder.PlannedDateOfShipping = item.PlannedDateOfShipping;
                    myOrder.ActualDateOfShipping = item.ActualDateOfShipping;
                    myOrder.DateOfCreation = item.DateOfCreation;


                    myList.Add(myOrder);
                }

            }


            return myList;
        }