public async Task<ActionResult> Sales_Update([DataSourceRequest] DataSourceRequest request, SalesViewModel salesViewModel)
        {
            if (salesViewModel != null && ModelState.IsValid)
            {
                SalesTransaction data = db.SalesTransactions.Find(salesViewModel.ID);

                data.LastName = salesViewModel.LastName;
                data.FirstName = salesViewModel.FirstName;
                data.MobileNumber = salesViewModel.MobileNumber;
                data.Pin = salesViewModel.Pin;
                data.OrderNumber = salesViewModel.OrderNumber;
                data.PortinNumber = salesViewModel.PortinNumber;
                data.PlanId = salesViewModel.PlanId;
                data.UserId = salesViewModel.UserId;
                data.DealerId = salesViewModel.DealerId;

                if (data.InventoryId != salesViewModel.InventoryId)
                {
                    if (data.InventoryId.HasValue)
                    {
                        Inventory oldInventory = await db.Inventories.FindAsync(data.InventoryId);

                        if (oldInventory != null)
                        {
                            oldInventory.Status = InventoryOperationType.In;
                            oldInventory.StockOutById = null;
                            oldInventory.StockOutDate = null;

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

                            //add change record to history
                            InvetoryChangeHistory changeHistory = new InvetoryChangeHistory();
                            changeHistory.IMEI = oldInventory.IMEI;
                            changeHistory.ChangeDate = DateTime.Now;
                            changeHistory.OldOperationType = InventoryOperationType.Out;
                            changeHistory.NewOperationType = InventoryOperationType.In;
                            changeHistory.OperatedByEmployeeID = salesViewModel.UserId;
                            changeHistory.Sales = null;
                            db.InvetoryChangeHistories.Add(changeHistory);
                        }
                    }

                    if (salesViewModel.InventoryId.HasValue)
                    {
                        int id = salesViewModel.InventoryId.Value;

                        Inventory inventory = await db.Inventories.FindAsync(id);
                        if (inventory != null)
                        {
                            InventoryOperationType oldType = inventory.Status;
                            inventory.Status = InventoryOperationType.Out;
                            inventory.StockOutById = data.UserId;
                            inventory.StockOutDate = DateTime.Now;
                            salesViewModel.IMEI = inventory.IMEI;

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

                data.InventoryId = salesViewModel.InventoryId;
                data.CreateDateTime = salesViewModel.CreateDateTime;
                data.RefferA = salesViewModel.RefferA;
                data.RefferB = salesViewModel.RefferB;
                data.Audit = salesViewModel.Audit;
                data.Note = salesViewModel.Note;
                data.ProductId = salesViewModel.ProductId;


                if (!User.IsInRole("Admin"))
                {
                    data.IsChanged = true;
                    salesViewModel.IsChanged = true;
                }

                db.Entry(data).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }

            return Json(new[] { salesViewModel }.ToDataSourceResult(request, ModelState));
        }
         //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> Sales_Create([DataSourceRequest] DataSourceRequest request, SalesViewModel salesViewModel)
        {
            if (salesViewModel != null && ModelState.IsValid)
            {
                salesViewModel.UserId = User.Identity.GetUserId();
                if(HelperMethods.GetDealerId().HasValue)
                    salesViewModel.DealerId = HelperMethods.GetDealerId().GetValueOrDefault();
                else
                {
                    return HttpNotFound("No Current Dealer Found");
                }

                salesViewModel.CreateDateTime = DateTime.Now;

                SalesTransaction data = new SalesTransaction
                {
                    LastName = salesViewModel.LastName,
                    FirstName = salesViewModel.FirstName,
                    MobileNumber = salesViewModel.MobileNumber,
                    Pin = salesViewModel.Pin,
                    OrderNumber = salesViewModel.OrderNumber,
                    PortinNumber = salesViewModel.PortinNumber,
                    PlanId = salesViewModel.PlanId,
                    UserId = salesViewModel.UserId,
                    DealerId = salesViewModel.DealerId,
                    InventoryId = salesViewModel.InventoryId,
                    CreateDateTime = salesViewModel.CreateDateTime,
                    RefferA = salesViewModel.RefferA,
                    RefferB = salesViewModel.RefferB,
                    Audit = salesViewModel.Audit,
                    Note = salesViewModel.Note,
                    ProductId = salesViewModel.ProductId
                };

                db.SalesTransactions.Add(data);

                if (data.InventoryId.HasValue)
                {
                    int id = data.InventoryId.Value;

                    Inventory inventory = await db.Inventories.FindAsync(id);
                    if (inventory != null)
                    {
                        InventoryOperationType oldType = inventory.Status;
                        inventory.Status = InventoryOperationType.Out;
                        inventory.StockOutById = data.UserId;
                        inventory.StockOutDate = DateTime.Now;
                        salesViewModel.IMEI = inventory.IMEI;

                        //add change record to history
                        InvetoryChangeHistory changeHistory = new InvetoryChangeHistory();
                        changeHistory.IMEI = inventory.IMEI;
                        changeHistory.ChangeDate = inventory.StockOutDate.Value;
                        changeHistory.OldOperationType = oldType;
                        changeHistory.NewOperationType = InventoryOperationType.Out;
                        changeHistory.OperatedByEmployeeID = inventory.StockOutById;
                        changeHistory.Sales = data;
                        db.InvetoryChangeHistories.Add(changeHistory);
                    }
                }
                await db.SaveChangesAsync();
                salesViewModel.ID = data.ID;

                //return RedirectToAction("StockOut", "Inventory", salesViewModel.InventoryId);
            }
            //salesTransaction.LinkedPlan = db.Plans.FirstOrDefault(p => p.PlanId == salesTransaction.PlanId);
            //await db.SaveChangesAsync();
            return Json(new[] { salesViewModel }.ToDataSourceResult(request, ModelState));
            
        }
        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));
        }