//public async Task<ActionResult> StockOut(int? id)
         //{
         //    if (id == null)
         //    {
         //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         //    }
         //    Inventory inventory = await db.Inventories.FindAsync(id);
         //    if (inventory == null)
         //    {
         //        return HttpNotFound();
         //    }
         //    return View(inventory);
         //}

         // POST: Dealers/Edit/5
         // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
         //[HttpPost]
         //[ValidateAntiForgeryToken]
         //public async Task<ActionResult> StockOut(Inventory inventory)
         //{
         //    if (ModelState.IsValid)
         //    {
         //        InventoryOperationType oldvType = inventory.Status;

         //        inventory.Status = InventoryOperationType.Out;
         //        inventory.StockOutById = User.Identity.GetUserId();
         //        inventory.StockOutDate = DateTime.Now;
         //        db.Entry(inventory).State = EntityState.Modified;

         //        //add change record to history
         //        InvetoryChangeHistory changeHistory = new InvetoryChangeHistory();
         //        changeHistory.IMEI = inventory.IMEI;
         //        changeHistory.ChangeDate = inventory.StockOutDate.Value;
         //        changeHistory.OldOperationType = oldvType;
         //        changeHistory.NewOperationType = InventoryOperationType.Out;
         //        changeHistory.OperatedByEmployeeID = inventory.StockOutById;
         //        db.InvetoryChangeHistories.Add(changeHistory);

         //        await db.SaveChangesAsync();
         //        return RedirectToAction("Index","Sales");
         //    }
         //    return RedirectToAction("Index", "Sales");
         //}

        public async Task<ActionResult> TransferTo(int? dealerId)
        {
            if (TempData.ContainsKey("InventoryId") && dealerId != null)
            {
                int? id = (int?)TempData["InventoryId"];
                if (id != null)
                {
                    var userId = User.Identity.GetUserId();
                    Dealer destDealer = await db.Dealers.FindAsync(dealerId);

                    Dealer currentDealer = await HelperMethods.GetCurrentDealer();
                    
                    Inventory inventory =  await db.Inventories.FindAsync(id);

                    string note = inventory.Note;
                    InventoryOperationType oldStatus = inventory.Status;
                    inventory.Note = " To " + destDealer.DealerName;
                    inventory.Status = InventoryOperationType.TransferOut;
                    inventory.StockOutById = userId;
                    inventory.StockOutDate = DateTime.Now;

                    db.Entry(inventory).State = EntityState.Modified;

                    //add change record to history
                    InvetoryChangeHistory changeHistory = new InvetoryChangeHistory();
                    changeHistory.IMEI = inventory.IMEI;
                    changeHistory.ChangeDate = inventory.StockOutDate.Value;
                    changeHistory.OldOperationType = oldStatus;
                    changeHistory.NewOperationType = InventoryOperationType.TransferOut;
                    changeHistory.OperatedByEmployeeID = inventory.StockOutById;
                    changeHistory.ToDealer = destDealer.DealerName;
                    db.InvetoryChangeHistories.Add(changeHistory);

                    Inventory destInventory = new Inventory
                    {
                        StockInById = userId,
                        StockInDate = inventory.StockInDate,
                        DealerId = dealerId.Value,
                        ProductId = inventory.ProductId,
                        IMEI = inventory.IMEI,
                        Status = InventoryOperationType.TransferIn,
                        Type = inventory.Type,
                        Note = " From " + currentDealer.DealerName,
                        PurchasedFrom = inventory.PurchasedFrom,
                        PurchasedById = inventory.PurchasedById,
                        DefferCode = inventory.DefferCode,
                        DefferName = inventory.DefferName,
                        DefferOrderNo = inventory.DefferOrderNo,
                        StockOutById = null,
                        StockOutDate = null
                    };
                    db.Inventories.Add(destInventory);

                    //add change record to history
                    InvetoryChangeHistory changeHistory2 = new InvetoryChangeHistory();
                    changeHistory2.IMEI = inventory.IMEI;
                    changeHistory2.ChangeDate = destInventory.StockInDate;
                    changeHistory2.OldOperationType = null;
                    changeHistory2.NewOperationType = InventoryOperationType.TransferIn;
                    changeHistory2.OperatedByEmployeeID = inventory.StockOutById;
                    changeHistory2.FromDealer = currentDealer.DealerName;
                    db.InvetoryChangeHistories.Add(changeHistory2);

                    await db.SaveChangesAsync();
                }
            }
 
            //db.Inventories.Find(dealerId)
            return RedirectToAction("Index");
        }
        public async Task<ActionResult> Inventory_Create([DataSourceRequest] DataSourceRequest request, InventoryViewModel inventoryViewModel)
        {
            //if (inventory != null && ModelState.IsValid)
            //{
            //    db.Inventories.Add(inventory);
            //    //await db.SaveChangesAsync();
            //}

            ////var invetoryChangeHistory = new InvetoryChangeHistory
            ////{
            ////    ChangeDate = DateTime.Now,
            ////    Inventory = inventory,
            ////    OperatedByEmployeeID = User.Identity.GetUserId(),
            ////    OperationType = InventoryOperationType.In
            ////};

            ////db.InvetoryChangeHistories.Add(invetoryChangeHistory);
            //await db.SaveChangesAsync();

            //return Json(new[] { inventory }.ToDataSourceResult(request, ModelState));




            if (inventoryViewModel != null && ModelState.IsValid)
            {
                inventoryViewModel.StockInUserId = User.Identity.GetUserId();
                if (HelperMethods.GetDealerId().HasValue)
                    inventoryViewModel.DealerId = HelperMethods.GetDealerId().GetValueOrDefault();
                else
                {
                    //return HttpNotFound("No Current Dealer Found");
                }

                inventoryViewModel.StockInDate = DateTime.Now;

                Inventory data = new Inventory
                {
                    StockInById = inventoryViewModel.StockInUserId,
                    StockInDate = inventoryViewModel.StockInDate,
                    DealerId = inventoryViewModel.DealerId,
                    ProductId = inventoryViewModel.ProductId,
                    IMEI = inventoryViewModel.IMEI,
                    Type = inventoryViewModel.Type,
                    Note = inventoryViewModel.Note,
                    PurchasedFrom = string.IsNullOrEmpty(inventoryViewModel.PurchasedFrom) ? null:inventoryViewModel.PurchasedFrom,
                    PurchasedById = inventoryViewModel.PurchasedById,
                    DefferCode = string.IsNullOrEmpty(inventoryViewModel.DefferCode) ? null : inventoryViewModel.DefferCode,
                    DefferName = string.IsNullOrEmpty(inventoryViewModel.DefferName) ? null : inventoryViewModel.DefferName,
                    DefferOrderNo = string.IsNullOrEmpty(inventoryViewModel.DefferOrderNo) ? null : inventoryViewModel.DefferOrderNo
                };

                db.Inventories.Add(data);


                //add change record to history
                InvetoryChangeHistory changeHistory2 = new InvetoryChangeHistory();
                changeHistory2.IMEI = data.IMEI;
                changeHistory2.ChangeDate = data.StockInDate;
                changeHistory2.OldOperationType = null;
                changeHistory2.NewOperationType = InventoryOperationType.In;
                changeHistory2.OperatedByEmployeeID = data.StockInById;
                var result = await HelperMethods.GetCurrentDealer();
                changeHistory2.ToDealer = result.DealerName;
                db.InvetoryChangeHistories.Add(changeHistory2);

                await db.SaveChangesAsync();
                //db.SaveChanges();
                //inventoryViewModel.ID = data.InventoryId;
                await db.SaveChangesAsync();
                inventoryViewModel.ID = data.InventoryId;
            }
            //salesTransaction.LinkedPlan = db.Plans.FirstOrDefault(p => p.PlanId == salesTransaction.PlanId);
            //await db.SaveChangesAsync();
            return Json(new[] { inventoryViewModel }.ToDataSourceResult(request, ModelState));
        }