public ActionResult _GetFirstCategoryProducts(int shopID, bool favorite = false, bool allOrderedProducts = false, bool deals = false)
        {
            List <ProductOverviewModel>     data           = new List <ProductOverviewModel>();
            List <SpecificationOptionModel> specifications = null;

            if (favorite)
            {
                data.AddRange(LS.SearchProducts(shopID, out specifications, limit: int.MaxValue, favorite: true));
            }
            if (allOrderedProducts)
            {
                data.AddRange(LS.SearchProducts(shopID, out specifications, limit: int.MaxValue, allOrderedProducts: true));
            }
            if (deals)
            {
                data.AddRange(LS.SearchProducts(shopID, out specifications, limit: 100, discountedProducts: true, showDiscounts: true));
            }
            return(PartialView("_ProductsGallery", data));
        }
        public static IEnumerable <ProductOverviewModel> GetFeaturedProducts(int ShopID = 0)
        {
            List <SpecificationOptionModel> specifications = null;

            return(LS.SearchProducts(ShopID, out specifications, featuredLeft: true, limit: 5));
        }
        public ActionResult _GetProductsForEndlessScrolling([DataSourceRequest] DataSourceRequest request,
                                                            int shopID, int?categoryID, int[] filtersArray = null, bool isBestSelling = false, string productName = "", bool refreshFilters = false,
                                                            bool favorite = false, bool allOrderedProducts = false, bool deals = false, string keywords = null)
        {
            bool firstBatch = request.Page == 1 ? true : false;

            if (request.PageSize == 0)
            {
                request.PageSize = 20;
            }
            var page = request.Page;
            List <SpecificationOptionModel> specifications = null;
            string tempString = null;
            List <ProductOverviewModel> list = new List <ProductOverviewModel>();

            if (favorite || allOrderedProducts || deals)
            {
                if (favorite)
                {
                    list.AddRange(LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, favorite: true, loadSpecifications: firstBatch, showDiscounts: true));
                }
                if (allOrderedProducts)
                {
                    list.AddRange(LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, allOrderedProducts: true, loadSpecifications: firstBatch, showDiscounts: true));
                }
                if (deals)
                {
                    //list.AddRange(LS.SearchProducts(shopID, out specifications, limit: int.MaxValue, discountedProducts: true, showDiscounts: true));
                    list.AddRange(LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, discountedProducts: true, showDiscounts: true));
                }
            }
            else
            {
                if (string.IsNullOrEmpty(productName))
                {
                    bool FeautureTop = false;
                    if (!categoryID.HasValue &&
                        (filtersArray == null || filtersArray.Length == 0) &&
                        string.IsNullOrEmpty(keywords) &&
                        !isBestSelling
                        )
                    {
                        var sc = LS.Get <ShopCategoryMenu>().FirstOrDefault(x => x.ShopID == shopID && x.Published == true && x.Level == 0);


                        if (sc != null)
                        {
                            categoryID = sc.CategoryID;
                        }
                    }
                    list = LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, categoryID: categoryID, filters: filtersArray, loadSpecifications: firstBatch,
                                             favorite: favorite, allOrderedProducts: allOrderedProducts, featuredTop: FeautureTop, showDiscounts: true, keywords: keywords).ToList();
                }
                else
                {
                    list = LS.GetProductByName(shopID, productName).Skip(--page * request.PageSize).Take(request.PageSize).ToList(); //search by single name
                }
            }

            int total = request.PageSize * request.Page + 1;

            if (list.Count() < request.PageSize)
            {
                total = request.PageSize * (request.Page - 1) + list.Count();
            }
            var viewList = new List <JsonKeyValue>();

            foreach (var item in list)
            {
                viewList.Add(new JsonKeyValue()
                {
                    Name  = item.ProductShopID.ToString(),
                    Value = RenderPartialViewToString("_ProductGalleryItem", item),
                });
            }
            return(Json(new
            {
                Data = viewList,
                Total = total,
                Errors = tempString,
                AggregateResults = tempString,
            }));
        }
        public ActionResult _GetProductByCategoryAndFilters(int shopID, int?categoryID, int[] filters, string viewIn = "gallery", int skip = 0, int take = 20,
                                                            string keywords        = null,
                                                            bool showFirstCategory = false,
                                                            bool isBestSelling     = false, string productName = "", bool refreshFilters = true, bool isForSpider = false)
        {
            List <SpecificationOptionModel>    specifications = null;
            IEnumerable <ProductOverviewModel> data;
            var profiler = MiniProfiler.Current;

            using (profiler.Step("Step Controller _ByCategoryAndFilters"))
            {
                if (string.IsNullOrEmpty(productName))
                {
                    if (showFirstCategory)
                    {
                        //var sc = LS.Get<ShopCategory>().OrderBy(x => x.DisplayOrder).Where(x => x.Published).FirstOrDefault();
                        //var category1 = LS.Get<Category>().ToList();

                        var sc = LS.Get <ShopCategoryMenu>().FirstOrDefault(x => x.ShopID == shopID && x.Published == true && x.Level == 0);


                        if (sc != null)
                        {
                            categoryID = sc.CategoryID;
                        }
                        else
                        {
                            var shopCatMap = LS.Get <ShopCategory>().Where(x => x.Published);

                            var shc = shopCatMap.OrderBy(x => x.DisplayOrder).FirstOrDefault();
                            if (shc != null)
                            {
                                categoryID = shc.CategoryID;
                            }
                        }
                    }
                    bool FeautureTop = false;
                    if (!categoryID.HasValue &&
                        (filters == null || filters.Length == 0) &&
                        string.IsNullOrEmpty(keywords) &&
                        !isBestSelling
                        )
                    {
                        FeautureTop = true;
                    }
                    data = LS.SearchProducts(
                        shopID: shopID,
                        options: out specifications,
                        page: isForSpider ? 1 : (skip / take) + 1,
                        limit: isForSpider ? -1 : take,
                        categoryID: categoryID,
                        filters: filters,
                        loadSpecifications: skip == 0,
                        keywords: keywords,
                        isBestSelling: isBestSelling,
                        featuredTop: FeautureTop,
                        showDiscounts: true);

                    foreach (var d in data)
                    {
                        //d.ProductNoteText = ShoppingService.GetUserNoteForProduct(d.ProductID, LS.CurrentUser.ID);
                    }
                }
                else
                {
                    data = LS.SearchProducts(shopID, out specifications, (skip / take) + 1, take
                                             // , categoryID: categoryID
                                             // , filters: filters
                                             //, loadSpecifications: skip == 0,
                                             , productName: productName
                                             //, isBestSelling: isBestSelling
                                             // , featuredTop: FeautureTop
                                             , showDiscounts: true
                                             );
                }


                ViewBag.LastProductNum = skip + take; //data.Count();
                ViewBag.Specifications = specifications;
                ViewBag.RefreshFilters = refreshFilters;
                ViewBag.CategoryID     = categoryID;
                if (categoryID.HasValue)
                {
                    var cat = LS.Get <Category>().FirstOrDefault(x => x.ID == categoryID.Value);
                    if (cat != null)
                    {
                        ViewBag.Category = cat;
                    }
                }
                if (!string.IsNullOrEmpty(productName) && data.Count() == 0 || !string.IsNullOrEmpty(keywords) && data.Count() == 0)
                {
                    return(Json(new
                    {
                        status = "productNotFound",
                        localizationMessage = RP.T("ShopController.SearchMessage.ProductNotFound").ToString(),
                        localizationTextComponent = RP.Text("ShopController.SearchMessage.ProductNotFoundComponent").ToString()
                    }, JsonRequestBehavior.AllowGet));
                }
            }

            if (data.Count() == 0)
            {
                return(Content(string.Empty));
            }
            var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == shopID);

            if (shop != null)
            {
                if (!string.IsNullOrEmpty(shop.Theme))
                {
                    this.HttpContext.Items["ShopTheme"] = shop.Theme;
                }
                ViewBag.Shop = shop;
            }
            switch (viewIn)
            {
            case "gallery":
                return(PartialView("_ProductsGallery", data));

            case "table":
                return(PartialView("_ProductsTable", data));

            case "tableItemPartial":
                return(PartialView("_ProductTableItem", data));
            }
            return(Content(string.Empty));
        }
        public ShoppingCartOverviewModel GetShoppingCartModel(int ShopID
                                                              , bool loadattributes = true
                                                              , bool withship       = false
                                                              , bool withdiscount   = true
                                                              , bool feutured       = false
                                                              , bool loadworktimes  = false
                                                              , bool nocache        = false
                                                              , bool checkQuantity  = false
                                                              , bool loadComments   = false
                                                              , Guid UserID         = new Guid())
        {
            if (UserID == Guid.Empty && LS.isHaveID())
            {
                UserID = LS.CurrentUser.ID;
            }
            var model = new ShoppingCartOverviewModel();
            List <SpecificationOptionModel> specifications = null;

            model.ShopID = ShopID;
            var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == ShopID);

            if (shop == null)
            {
                return(model);
            }
            model.Shop                 = shop;
            model.IsShipEnabled        = shop.IsShipEnabled;
            model.InStorePickUpEnabled = shop.InStorePickUpEnabled;
            if (LS.isHaveID())
            {
                model.Items = this.GetShoppingCartItems(ShopID, loadattributes, withdiscount: withdiscount, checkQuantity: checkQuantity, UserID: UserID);

                model.IsLogined = true;
                if (withdiscount)
                {
                    // process discounts

                    var discountService = new DiscountService(_db, nocache);
                    discountService.ProcessItems(model, LS.CurrentUser);
                }
                //fix and format prices
                foreach (var item in model.Items)
                {
                    item.UnitPrice = item.Price * item.Quantity - item.TotalDiscountAmount;
                    if (item.UnitPrice < 0)
                    {
                        item.UnitPrice = 0;
                    }
                    string ustep = "1";
                    if (item.MeasureUnitStep.HasValue)
                    {
                        //item.UnitPrice = item.UnitPrice / item.MeasureUnitStep.Value;
                        // ustep = item.MeasureUnitStep.Value.ToString();
                    }

                    item.PriceStr     = ShoppingService.FormatPrice(item.Price) + (item.MeasureUnit != null ? " / " + item.MeasureUnit : "");
                    item.UnitPriceStr = ShoppingService.FormatPrice(item.UnitPrice);
                    //+ ( item.TotalDiscountAmount > 0
                    //   ? " (-" + ShoppingService.FormatPrice(item.TotalDiscountAmount) + ")"
                    // : "");
                    if (false && loadComments)
                    {
                        item.Comments = ShoppingService.GetUserNoteForProduct(item.ProductID, LS.CurrentUser.ID);
                    }
                }

                model.FreeShipFrom = shop.FreeShipFrom;
                model.ShopShipCost = shop.ShipCost;

                var deliveryZones = LS.Get <ShopDeliveryZone>().Where(x => x.ShopID == ShopID && x.Active).ToList();
                if (deliveryZones.Count > 0)
                {
                    //searching by couples zones
                    var     checkoutData = ShoppingCartService.GetCheckoutData(UserID);
                    var     address      = "";
                    decimal longitude    = 0;
                    decimal latitude     = 0;
                    if (LS.CurrentUser.Latitude != 0)
                    {
                        latitude = LS.CurrentUser.Latitude;
                    }
                    if (LS.CurrentUser.Longitude != 0)
                    {
                        longitude = LS.CurrentUser.Longitude;
                    }
                    if (LS.CurrentHttpContext != null)
                    {
                        //if not regognized
                        if (longitude == 0)
                        {
                            if (LS.CurrentHttpContext.Session["longitude"] != null)
                            {
                                longitude = (decimal)LS.CurrentHttpContext.Session["longitude"];
                            }
                        }
                        if (latitude == 0)
                        {
                            if (LS.CurrentHttpContext.Session["latitude"] != null)
                            {
                                latitude = (decimal)LS.CurrentHttpContext.Session["latitude"];
                            }
                        }
                    }
                    if (LS.CurrentHttpContext != null && LS.CurrentHttpContext.Session["address"] != null)
                    {
                        address = (string)LS.CurrentHttpContext.Session["address"];
                    }
                    else
                    {
                        address = checkoutData.Address;
                    }
                    if (address == null)
                    {
                        address = "";
                    }
                    // find by address



                    var lowerCaseAddress = address.ToLower();

                    List <DeliveryZoneSmall> allPossible = new List <DeliveryZoneSmall>();
                    //add default shop zone
                    var clientDefaultradius = ShoppingService.distance((double)shop.RadiusLatitude, (double)shop.RadiusLongitude
                                                                       , (double)latitude, (double)longitude, 'K');
                    if (clientDefaultradius <= (double)shop.ShipRadius)
                    {
                        allPossible.Add(new DeliveryZoneSmall()
                        {
                            ShipCost = shop.ShipCost
                            ,
                            FreeShipFrom = shop.FreeShipFrom,
                            Distance     = clientDefaultradius
                        });
                    }
                    foreach (var dz in deliveryZones)
                    {
                        if (dz.DeliveryFroAllCity && !string.IsNullOrEmpty(dz.City) &&
                            (
                                lowerCaseAddress.Contains(", " + dz.City.ToLower() + ", ") ||
                                lowerCaseAddress.StartsWith(dz.City.ToLower() + ", ")
                                // || lowerCaseAddress.EndsWith(", " + s.City.ToLower())
                                // || lowerCaseAddress.StartsWith(s.City.ToLower() + " ")
                                || lowerCaseAddress.EndsWith(", " + dz.City.ToLower())
                            )
                            )
                        {
                            allPossible.Add(new DeliveryZoneSmall()
                            {
                                ShipCost = dz.ShipCost, FreeShipFrom = dz.FreeShipFrom, Distance = 1
                            });
                        }
                        else if (!dz.DeliveryFroAllCity)
                        {
                            var clientradius = ShoppingService.distance((double)dz.RadiusLatitude, (double)dz.RadiusLongitude, (double)latitude, (double)longitude, 'K');
                            if (clientradius <= (double)dz.ShipRadius)
                            {
                                allPossible.Add(new DeliveryZoneSmall()
                                {
                                    ShipCost = dz.ShipCost
                                    ,
                                    FreeShipFrom = dz.FreeShipFrom,
                                    Distance     = clientradius
                                });
                            }
                        }
                    }
                    if (allPossible.Count > 0)
                    {
                        var firstBetter = allPossible.OrderBy(x => x.Distance).FirstOrDefault();
                        model.FreeShipFrom = firstBetter.FreeShipFrom;
                        model.ShopShipCost = firstBetter.ShipCost;
                    }
                }

                if (model.Items.Count > 0)
                {
                    model.SubTotal         = model.Items.Count > 0 ? model.Items.Sum(x => x.UnitPrice) : 0;
                    model.TotalWithoutShip = model.SubTotal;
                    if (withship && model.SubTotal < model.FreeShipFrom)
                    {
                        model.ShippingCost = model.ShopShipCost;
                    }
                    model.Total = model.SubTotal + model.ShippingCost + model.Fee;
                    model.Count = model.Items.Count;
                }
            }



            if (withdiscount)
            {
                // process total discounts

                var discountService = new DiscountService(_db, nocache);
                discountService.ProcessTotals(model, LS.CurrentUser);
            }
            //if (LS.isLogined())
            //{
            //    if (model.Items.Count > 0)
            //    {
            //        model.TotalWithoutShip = model.SubTotal;
            //        if (withship && model.SubTotal < shop.FreeShipFrom)
            //        {
            //            if (model.ShippingCost > 0)
            //            {
            //                model.ShippingCost = shop.ShipCost;
            //            }
            //        }


            //    }
            //}
            model.SubTotalStr         = ShoppingService.FormatPrice(model.SubTotal);
            model.ShippingCostStr     = ShoppingService.FormatPrice(model.ShippingCost);
            model.TotalWithoutShipStr = ShoppingService.FormatPrice(model.TotalWithoutShip);

            model.FeeStr           = ShoppingService.FormatPrice(model.Fee);
            model.TotalStr         = ShoppingService.FormatPrice(model.Total);
            model.TotalDiscountStr = ShoppingService.FormatPrice(model.TotalDiscount);
            //work and ship times
            if (loadworktimes)
            {
                var curdate  = DateTime.Now.Date;
                var lastdate = curdate.AddDays(7);
                model.ShipTimes = _db.ShopShipTimes.Where(x => x.ShopID == ShopID && x.Active &&
                                                          (!x.IsSpecial || (x.Date >= curdate && x.Date <= lastdate)
                                                          )
                                                          )
                                  .OrderBy(x => x.IsSpecial).ThenBy(x => x.Day).ThenBy(x => x.Date)
                                  .Select(x => new ShipTimeModel()
                {
                    Date        = x.Date,
                    Day         = x.Day,
                    TimeFromInt = x.TimeFrom,
                    TimeToInt   = x.TimeTo,
                    IsSpecial   = x.IsSpecial
                })
                                  .ToList();
                var culture = new System.Globalization.CultureInfo("he-IL");
                foreach (var t in model.ShipTimes)
                {
                    t.DayStr       = t.DayStr = culture.DateTimeFormat.GetDayName(t.Day);
                    t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm");
                    t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                }

                model.WorkTimes = _db.ShopWorkTimes.Where(x => x.ShopID == ShopID && x.Active &&
                                                          (!x.IsSpecial || (x.Date >= curdate && x.Date <= lastdate))
                                                          ).OrderBy(x => x.IsSpecial).ThenBy(x => x.Day).ThenBy(x => x.Date)
                                  .Select(x => new ShipTimeModel()
                {
                    Date        = x.Date,
                    Day         = x.Day,
                    TimeFromInt = x.TimeFrom,
                    TimeToInt   = x.TimeTo,
                    IsSpecial   = x.IsSpecial,
                })
                                  .ToList();
                foreach (var t in model.WorkTimes)
                {
                    //t.DayStr = t.Day.ToString();
                    //t.TimeFromeStr = IntToTime(t.TimeFromInt);
                    //t.TimeToStr = IntToTime(t.TimeToInt);
                    //t.DateStr = t.Date.ToString("dd/MM");
                    t.DayStr       = culture.DateTimeFormat.GetDayName(t.Day);
                    t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm");
                    t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                    t.DateStr      = t.Date.ToString("dd/MM");
                }
            }

            if (feutured)
            {
                var exceptProductShopIds = model.Items.Select(x => x.ProductShopID).ToList();
                model.FeaturedProducts = LS.SearchProducts(ShopID, out specifications, featuredLeft: true, excludeProductShopList: exceptProductShopIds, limit: 10).ToList();
                if (model.FeaturedProducts.Count < 10)
                {
                    int limitLeft = 10 - model.FeaturedProducts.Count;
                    var ordered   = LS.SearchProducts(ShopID, out specifications, allOrderedProducts: true, excludeProductShopList: exceptProductShopIds, limit: limitLeft).ToList();
                    foreach (var p in ordered)
                    {
                        if (!model.FeaturedProducts.Any(x => x.ProductShopID == p.ProductShopID))
                        {
                            model.FeaturedProducts.Add(p);
                        }
                    }
                }
                if (model.FeaturedProducts.Count < 10)
                {
                    int limitLeft = 10 - model.FeaturedProducts.Count;
                    var catId     = model.Items.Select(x => x.CategoryID).ToList();
                    if (catId.Count > 0)
                    {
                        var ordered = LS.SearchProducts(ShopID, out specifications, inCategories: catId, excludeProductShopList: exceptProductShopIds, limit: limitLeft).ToList();
                        foreach (var p in ordered)
                        {
                            if (!model.FeaturedProducts.Any(x => x.ProductShopID == p.ProductShopID))
                            {
                                model.FeaturedProducts.Add(p);
                            }
                        }
                    }
                }
            }
            return(model);
        }