Advertisement
X1ucifer

Untitled

Nov 17th, 2022
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 70.77 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Repositories\Admin\Product;
  4.  
  5. use App\Models\Campaign;
  6. use App\Models\CampaignProduct;
  7. use App\Models\Category;
  8. use App\Models\CompareProduct;
  9. use App\Models\Product;
  10. use App\Models\ProductLanguage;
  11. use App\Models\ProductStock;
  12. use App\Models\ProductView;
  13. use App\Models\Search;
  14. use App\Repositories\Interfaces\Admin\Product\ProductInterface;
  15. use App\Repositories\Interfaces\Admin\Product\ProductLanguageInterface;
  16. use App\Repositories\Interfaces\Admin\SellerInterface;
  17. use App\Traits\ImageTrait;
  18. use App\Traits\RandomStringTrait;
  19. use App\Traits\SlugTrait;
  20. use Carbon\Carbon;
  21. use Illuminate\Support\Facades\DB;
  22. use Illuminate\Support\Str;
  23. use Sentinel;
  24. use Illuminate\Support\Facades\Log;
  25.  
  26.  
  27. class ProductRepository implements ProductInterface
  28. {
  29.     use SlugTrait, ImageTrait, RandomStringTrait;
  30.  
  31.     protected $productLang;
  32.     protected $seller;
  33.  
  34.     public function __construct(ProductLanguageInterface $productLang, SellerInterface $seller)
  35.     {
  36.         $this->productLang  = $productLang;
  37.         $this->seller       = $seller;
  38.     }
  39.  
  40.     public function get($id)
  41.     {
  42.         return Product::CheckSellerSystem()->find($id);
  43.     }
  44.  
  45.     public function productFilter($request)
  46.     {
  47.  
  48.  
  49.         // $data = Product::with('productLanguages', 'createdBy')
  50.         // ->get();
  51.  
  52.         // $name = $data->getTranslation('name',apiLanguage($request->lang));
  53.         // if(!empty($request["category_id"]) ){
  54.         //     $products = Product::with('stock','productLanguages')->where('category_id',$request["category_id"])->get();
  55.         // }
  56.  
  57.  
  58.             if($request["filterByname"] == 1){
  59.  
  60.                 if(!empty($request["category_id"]) ){
  61.                     $products = Product::with('stock','productLanguages')->where('slug', 'like', '%' . $request["title"] . '%')->where('category_id',$request["category_id"])->get();
  62.                 }else{
  63.                     $products = Product::with('stock','productLanguages')->where('slug', 'like', '%' . $request["title"] . '%')->get();
  64.                 }
  65.  
  66.  
  67.                 // $products = Product::with('stock','productLanguages')->where('slug', 'like', '%' . $request["title"] . '%')->get();
  68.  
  69.             }elseif($request["filterByname"] == 0){
  70.  
  71.                 if(!empty($request["category_id"]) ){
  72.                     $products = Product::with('stock','productLanguages')->where('category_id',$request["category_id"])->get();
  73.                 }else{
  74.                     $products = Product::with('stock','productLanguages')->get();
  75.                 }
  76.  
  77.             }elseif($request["filterByname"] == 2){
  78.  
  79.                 if(!empty($request["category_id"]) ){
  80.                     $products = Product::with('stock','productLanguages')->where('category_id',$request["category_id"])->get();
  81.                 }else{
  82.                     $products = Product::with('stock','productLanguages')->get();
  83.                 }
  84.             }
  85.  
  86.  
  87.  
  88.  
  89.             // elseif($request["filterByname"] == null){
  90.             //     $dataId = Category::where('parent_id',$request["category_id"])->where('ordering',$request["ordering"])
  91.             //     ->select('id')->get();
  92.             //     $products = Product::withAvg('reviews','rating')->withCount('reviews')->whereIn('category_id',$dataId)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  93.             //     ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  94.             //     ->get();
  95.             // }
  96.  
  97.             // if($request["mainFilter"] == 1){
  98.  
  99.             //     $category_ids = \App\Utility\CategoryUtility::getMyAllChildIds($request["category_id"]);
  100.             //     $category_ids[] = (int)$request["category_id"];
  101.  
  102.  
  103.             //     // $products = Product::withAvg('reviews','rating')->withCount('reviews')->whereIn('category_id',$category_ids)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  104.             //     // ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  105.             //     // ->get();
  106.  
  107.             //     if(empty($request["ordering"])){
  108.  
  109.  
  110.             //         $products = Product::withAvg('reviews','rating')->withCount('reviews')->whereIn('category_id',$category_ids)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  111.             //         ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  112.             //         ->get();
  113.             //     }else{
  114.  
  115.  
  116.             //     }
  117.  
  118.             // }
  119.  
  120.  
  121.  
  122.         // Log::info('Showing the user profile for user: '. json_encode($request["filterByname"] ));
  123.  
  124.         return $products;
  125.     }
  126.  
  127.     public function productBydifference($category_id){
  128.         return Product::where('category_id',$category_id)->get();
  129.     }
  130.  
  131.     public function getByLang($id, $lang)
  132.     {
  133.         if ($lang == null):
  134.             $product_lang = ProductLanguage::with('product')
  135.                 ->where('lang', 'en')
  136.                 ->where('product_id', $id)
  137.                 ->when(settingHelper('seller_system') != 1, function ($q) {
  138.                     $q->whereHas('product', function ($qu) {
  139.                         $qu->where('user_id', 1);
  140.                     });
  141.                 })->first();
  142.         else:
  143.             $product_lang = ProductLanguage::with('product')
  144.                 ->where('lang', $lang)
  145.                 ->where('product_id', $id)
  146.                 ->when(settingHelper('seller_system') != 1, function ($q) {
  147.                     $q->whereHas('product', function ($qu) {
  148.                         $qu->where('user_id', 1);
  149.                     });
  150.                 })->first();
  151.             if (blank($product_lang)):
  152.                 $product_lang = ProductLanguage::with('product')
  153.                     ->where('lang', 'en')
  154.                     ->where('product_id', $id)
  155.                     ->when(settingHelper('seller_system') != 1, function ($q) {
  156.                         $q->whereHas('product', function ($qu) {
  157.                             $qu->where('user_id', 1);
  158.                         });
  159.                     })->first();
  160.                 $product_lang['translation_null'] = 'not-found';
  161.             endif;
  162.         endif;
  163.  
  164.         return $product_lang;
  165.     }
  166.  
  167.     public function all()
  168.     {
  169.         return Product::with('productLanguages', 'createdBy')
  170.             ->when(!addon_is_activated('wholesale'), function ($q) {
  171.                 $q->where('is_wholesale', 0);
  172.             })->CheckSellerSystem()->latest();
  173.     }
  174.  
  175.     public function paginate($request, $status, $limit, $product_for = null)
  176.     {
  177.         $products = Product::with('createdBy', 'productLanguages','user','stock')
  178.             ->where('is_deleted', 0)
  179.             ->CheckSellerSystem()
  180.             ->whereHas('productLanguages', function ($q) use ($request) {
  181.                 $q->where('name', 'like', '%' . $request->q . '%');
  182.                 $q->orWhere('tags', 'like', '%' . $request->q . '%');
  183.                 $q->orwhere('description', 'like', '%' . $request->q . '%');
  184.                 $q->orwhere('short_description', 'like', '%' . $request->q . '%');
  185.                 $q->orwhere('meta_title', 'like', '%' . $request->q . '%');
  186.                 $q->orwhere('meta_description', 'like', '%' . $request->q . '%');
  187.                 $q->orwhere('meta_keywords', 'like', '%' . $request->q . '%');
  188.             })
  189.             ->when($status == 'trash' && $status != null, function ($query) {
  190.                 $query->onlyTrashed();
  191.             })
  192.             ->when($status != 'trash' && $status != 'pending' && $status != null, function ($query) use ($status) {
  193.                 $query->where('status', $status);
  194.             })
  195.             ->when($status == 'pending', function ($query) {
  196.                 $query->where('is_approved', 0);
  197.             })
  198.             ->when($request->sq != null, function ($q) use ($request) {
  199.                 $q->where('user_id', $request->sq);
  200.             })
  201.             ->when(!addon_is_activated('wholesale'), function ($q) {
  202.                 $q->where('is_wholesale', 0);
  203.             })
  204.             ->when($product_for != '', function ($q) use ($product_for) {
  205.                 $q->when($product_for == 'admin', function ($for) {
  206.                     $for->where('user_id', 1);
  207.                 });
  208.                 $q->when($product_for == 'seller', function ($for) {
  209.                     $for->where('user_id', '!=', 1);
  210.                 });
  211.                 $q->when($product_for == 'digital', function ($for) {
  212.                     $for->where('is_digital', 1);
  213.                 });
  214.                 $q->when($product_for == 'catalog', function ($for) {
  215.                     $for->where('is_catalog', 1);
  216.                 });
  217.                 $q->when($product_for == 'classified', function ($for) {
  218.                     $for->where('is_classified', 1);
  219.                 });
  220.                 $q->when($product_for == 'wholesale', function ($for) {
  221.                     $for->where('is_wholesale', 1);
  222.                 });
  223.             })
  224.             ->when($request->sl != null, function ($query) use ($request) {
  225.                 $seller = $this->seller->getSeller($request->sl);
  226.                 $query->where('user_id', $seller->user_id);
  227.             })
  228.             ->when($request->c != null, function ($q) use ($request) {
  229.                 $q->where('category_id', $request->c);
  230.             });
  231.         $sorting = $request->s;
  232.         switch ($sorting) {
  233.             case 'latest_on_top':
  234.                 $products->orderByDesc('id');
  235.                 break;
  236.             case 'oldest_on_top':
  237.                 $products->orderBy('id');
  238.                 break;
  239.             case 'sale_high':
  240.                 $products->orderByDesc('total_sale');
  241.                 break;
  242.             case 'sale_low':
  243.                 $products->orderBy('total_sale');
  244.                 break;
  245.             case 'rating_high':
  246.                 $products->orderByDesc('rating');
  247.                 break;
  248.             case 'rating_low':
  249.                 $products->orderBy('rating');
  250.                 break;
  251.             default:
  252.                 $products->orderBy('id', 'desc');
  253.                 break;
  254.         }
  255.  
  256.         Log::info("demo-->". json_encode( $products->paginate($limit)) );
  257.  
  258.         return $products->paginate($limit);
  259.     }
  260.  
  261.     public function stockProduct($request)
  262.     {
  263.         $stocks = ProductStock::query();
  264.  
  265.         if ($request->p && $request->q) {
  266.             $stocks->whereHas('product.productLanguages', function ($p) use ($request) {
  267.                 $p->where('name', 'like', '%' . $request->p . '%');
  268.                 $p->orWhere('name', 'like', '%' . $request->q . '%');
  269.                 $p->orWhere('barcode', 'like', '%' . $request->p . '%');
  270.                 $p->orWhere('barcode', 'like', '%' . $request->q . '%');
  271.             });
  272.         }
  273.         else{
  274.             if ($request->q) {
  275.                 $stocks->whereHas('product.productLanguages', function ($q) use ($request) {
  276.                     $q->where('name', 'like', '%' . $request->q . '%');
  277.                     $q->orWhere('barcode', 'like', '%' . $request->q . '%');
  278.                 });
  279.             }
  280.             if ($request->p) {
  281.                 $stocks->whereHas('product.productLanguages', function ($p) use ($request) {
  282.                     $p->where('name', 'like', '%' . $request->p . '%');
  283.                     $p->orWhere('barcode', 'like', '%' . $request->p . '%');
  284.                 });
  285.             }
  286.         }
  287.  
  288.         if ($request->category_id) {
  289.             $category_ids = \App\Utility\CategoryUtility::getMyAllChildIds($request->category_id);
  290.             $category_ids[] = (int)$request->category_id;
  291.  
  292.             $stocks->whereHas('product', function ($q) use ($category_ids) {
  293.                 $q->whereIn('category_id', $category_ids);
  294.             });
  295.         }
  296.  
  297.         if ($request->brand_id) {
  298.             $stocks->whereHas('product', function ($q) use ($request) {
  299.                 $q->where('brand_id', $request->brand_id);
  300.             });
  301.         }
  302.         return $stocks->with('product.productLanguages')
  303.             ->whereHas('product',function ($query) use ($request){
  304.             $query->when(Sentinel::getUser()->user_type == 'seller', function ($q){
  305.                 $q->where('user_id',authId())->UserCheck()->IsWholesale()->ProductPublished();
  306.             });
  307.             $query->when(Sentinel::getUser()->user_type == 'admin', function ($q){
  308.                 $q->where('user_id',1)->UserCheck()->IsWholesale()->ProductPublished();
  309.             });
  310.             $query->when(Sentinel::getUser()->user_type == 'staff', function ($q){
  311.                 $q->where('user_id',1)->UserCheck()->IsWholesale()->ProductPublished();
  312.             });
  313.  
  314.         })->where('current_stock', '>', '0')->latest()->paginate(16);
  315.     }
  316.  
  317.     public function store($request)
  318.     {
  319.         DB::BeginTransaction();
  320.         try {
  321.             $product = new Product();
  322.             $product->description_images = $this->saveMultipleImage($request->description_images,$product);
  323.             if ($request->thumbnail):
  324.                 $files     = $this->getImageWithRecommendedSize($request->thumbnail,190,230);
  325.                 if ($files):
  326.                     $product->thumbnail     = $files;
  327.                     $product->thumbnail_id  = $request->thumbnail;
  328.                 else:
  329.                     $product->thumbnail = [];
  330.                 endif;
  331.             else:
  332.                 $product->thumbnail = [];
  333.             endif;
  334.             if ($request->images != ''):
  335.                 $selected_images        = explode(',', $request->images);
  336.                 $images = array();
  337.                 foreach ($selected_images as $key=>$image):
  338.                     $files  = $this->getImage($image);
  339.                     if($files):
  340.                         array_push($images, $files);
  341.                     else:
  342.                         unset($selected_images[$key]);
  343.                     endif;
  344.                 endforeach;
  345.                 $product->images        = $images;
  346.                 $product->image_ids     = implode(',',$selected_images);
  347.             else:
  348.                 $product->images = [];
  349.             endif;
  350.             $product->slug              = $this->getSlug($request->name, $request->slug);
  351.             $product->category_id       = $request->category != '' ? $request->category : null;
  352.             $product->brand_id          = $request->brand != '' ? $request->brand : null;
  353.             $product->created_by        = authUser($request)->id;
  354.             if (authUser($request)->user_type != 'seller'):
  355.                 $product->user_id       = 1;
  356.                 $product->is_approved   = 1;
  357.             else:
  358.                 $product->user_id = authUser($request)->id;
  359.                 if (settingHelper('seller_product_auto_approve') == 1):
  360.                     $product->is_approved = 1;
  361.                 endif;
  362.             endif;
  363.             $product->status = $request->status;
  364.             $product->minimum_order_quantity    = $request->minimum_order_quantity != '' ? $request->minimum_order_quantity : 1;
  365.             $product->barcode                   = $request->barcode != '' ? $request->barcode : $this->generate_random_string(16, 'upper');
  366.  
  367.             if ($request->video_provider != '' && $request->video_url != ''):
  368.                 $product->video_provider    = $request->video_provider;
  369.                 $product->video_url         = $request->video_url;
  370.             endif;
  371.  
  372.             $product->price = priceFormatUpdate($request->price ,settingHelper('default_currency'));
  373.  
  374.             if ($request->special_discount_type != ''):
  375.                 $product->special_discount_type     = $request->special_discount_type;
  376.                 $product->special_discount          = priceFormatUpdate($request->special_discount,settingHelper('default_currency'));
  377.  
  378.                 $dates = explode(" - ", $request->special_discount_period);
  379.  
  380.                 $product->special_discount_start    = Carbon::createFromFormat('m-d-Y g:ia', $dates[0]);
  381.                 $product->special_discount_end      = Carbon::createFromFormat('m-d-Y g:ia', $dates[1]);
  382.             endif;
  383.             if ($request->has_variant == 1):
  384.                 $product->has_variant   = 1;
  385.                 $product->current_stock = 0;
  386.             else:
  387.                 $product->current_stock = $request->current_stock != '' ? $request->current_stock : 0;
  388.             endif;
  389.  
  390.             $product->colors            = $request->colors ?? [];
  391.             $product->attribute_sets    = $request->attribute_sets ?? [];
  392.             if ($request->has('vat_taxes')):
  393.                 $product->vat_taxes     = implode(',', $request->vat_taxes);
  394.             endif;
  395.  
  396.             if ($request->meta_image != ''):
  397.                 $files     = $this->getImageWithRecommendedSize($request->meta_image, 1200, 630);
  398.                 if ($files):
  399.                     $product->meta_image     = $files;
  400.                     $product->meta_image_id  = $request->thumbnail;
  401.                 else:
  402.                     $product->meta_image    = $product->thumbnail;
  403.                     $product->meta_image_id = $product->thumbnail_id;
  404.                 endif;
  405.             else:
  406.                 $product->meta_image    = $product->thumbnail;
  407.                 $product->meta_image_id = $product->thumbnail_id;
  408.             endif;
  409.  
  410.             if ($request->low_stock_to_notify != ''):
  411.                 $product->stock_notification    = 1;
  412.                 $product->low_stock_to_notify   = $request->low_stock_to_notify;
  413.             endif;
  414.             $product->stock_visibility          = $request->stock_visibility ?? 'hide_stock';
  415.             if ($request->has('cash_on_delivery')):
  416.                 $product->cash_on_delivery      = 1;
  417.             endif;
  418.             if ($request->has('is_refundable')):
  419.                 $product->is_refundable         = 1;
  420.             endif;
  421.             if ($request->has('is_catalog')):
  422.                 $product->is_catalog            = 1;
  423.             endif;
  424.             if ($request->has('is_featured')):
  425.                 $product->is_featured           = 1;
  426.             endif;
  427.             //digital product will not get delivered
  428.             if ($request->has('is_digital')):
  429.                 $product->is_digital             = 1;
  430.                 $product->minimum_order_quantity = 1;
  431.                 if ($request->product_file):
  432.                     $file = $this->getFile($request->product_file);
  433.                     if ($file):
  434.                         $product->product_file = $file;
  435.                         $product->product_file_id = $request->product_file;
  436.                     else:
  437.                         $product->product_file = [];
  438.                     endif;
  439.                 else:
  440.                     $product->product_file = [];
  441.                 endif;
  442.             else:
  443.                 $product->estimated_shipping_days = $request->estimated_shipping_days != '' ? $request->estimated_shipping_days : 0;
  444.             endif;
  445.  
  446.             if ($request->has('todays_deal')):
  447.                 $product->todays_deal = $request->todays_deal;
  448.             endif;
  449.  
  450.             //cost
  451.             if ($request->has('shipping_type')) :
  452.                 if ($request->shipping_type == 'free_shipping'):
  453.                     $product->shipping_fee = 0.00;
  454.                 elseif ($request->shipping_type == 'flat_rate'):
  455.                     $product->shipping_fee = $request->shipping_fee != '' ?  priceFormatUpdate($request->shipping_fee,settingHelper('default_currency')) : 0.00;
  456.                 endif;
  457.                 $product->shipping_type = $request->shipping_type;
  458.  
  459.                 if ($request->has('shipping_fee_depend_on_quantity')):
  460.                     $product->shipping_fee_depend_on_quantity = $request->shipping_fee_depend_on_quantity;
  461.                 endif;
  462.             endif;
  463.  
  464.             if ($request->has('is_classified')):
  465.                 $product->is_classified = 1;
  466.  
  467.                 $contact_details['contact_name']    = $request->contact_name;
  468.                 $contact_details['phone_no']        = $request->phone_no;
  469.                 $contact_details['email']           = $request->email;
  470.                 $contact_details['address']         = $request->address;
  471.                 $contact_details['others']          = $request->others;
  472.                 $product->contact_info              = $contact_details;
  473.             endif;
  474.  
  475.             $product->save();
  476.  
  477.             $request['product_id'] = $product->id;
  478.             if (!isset($request->lang)) :
  479.                 $request['lang'] = 'en';
  480.             endif;
  481.  
  482.             $this->productLang->store($request);
  483.  
  484.             if ($request->campaign) :
  485.                 $campaign_product                   = new CampaignProduct();
  486.                 $campaign_product->campaign_id      = $request->campaign;
  487.                 $campaign_product->product_id       = $product->id;
  488.                 $campaign_product->discount         = priceFormatUpdate($request->campaign_discount,settingHelper('default_currency'));
  489.                 $campaign_product->discount_type    = $request->campaign_discount_type;
  490.                 $campaign_product->save();
  491.  
  492.                 $campaign = Campaign::find($request->campaign);
  493.                 $product->special_discount_type     = $request->campaign_discount_type;
  494.                 $product->special_discount          = priceFormatUpdate($request->campaign_discount,settingHelper('default_currency'));
  495.                 $product->special_discount_start    = $campaign->start_date;
  496.                 $product->special_discount_end      = $campaign->end_date;
  497.             endif;
  498.             if ($product->has_variant == 1 && $request->has('variant_name')):
  499.                 $total_stock = 0;
  500.                 foreach ($request->variant_name as $key => $variant):
  501.                     if ($request['variant_name'][$key]):
  502.                         $product_stock                  = new ProductStock();
  503.                         $product_stock->product_id      = $product->id;
  504.                         $product_stock->name            = $request['variant_name'][$key];
  505.                         $product_stock->variant_ids     = $request['variant_ids'][$key];
  506.                         $product_stock->sku             = $request['variant_sku'][$key];
  507.                         $product_stock->current_stock   = $request['variant_stock'][$key];
  508.                         $product_stock->price           = priceFormatUpdate($request['variant_price'][$key],settingHelper('default_currency'));
  509.                         if ($request['variant_image'][$key] != ''):
  510.                             $files  = $this->getImage($request['variant_image'][$key]);
  511.                             if ($files):
  512.                                 $product_stock->image       = $files;
  513.                                 $product_stock->image_id    = $request['variant_image'][$key];
  514.                             else:
  515.                                 $product_stock->image       = [];
  516.                             endif;
  517.                         else:
  518.                             $product_stock->image       = [];
  519.                         endif;
  520.                         $total_stock                    += $product_stock->current_stock;
  521.                         $product_stock->save();
  522.                     endif;
  523.  
  524.                     $selected_variants = array();
  525.                     $selected_variants_ids = array();
  526.  
  527.                     if ($request->has('attribute_sets')):
  528.                         foreach ($request->attribute_sets as $attribute_set):
  529.                             $attribute_values = 'attribute_values_' . $attribute_set;
  530.                             $values = array();
  531.                             if ($request->has($attribute_values)):
  532.                                 foreach ($request[$attribute_values] as $value):
  533.                                     array_push($values, $value);
  534.                                     array_push($selected_variants_ids, $value);
  535.                                 endforeach;
  536.                                 $selected_variants[$attribute_set] = $values;
  537.                             endif;
  538.                         endforeach;
  539.                     endif;
  540.                     $product->selected_variants     = $selected_variants;
  541.                     $product->selected_variants_ids = $selected_variants_ids;
  542.                 endforeach;
  543.  
  544.                 $product->current_stock         = $total_stock;
  545.                 $product->save();
  546.             else:
  547.                 $product_stock                  = new ProductStock();
  548.                 $product_stock->product_id      = $product->id;
  549.                 $product_stock->sku             = $request->sku;
  550.                 $product_stock->name            = '';
  551.                 $product_stock->price           = priceFormatUpdate($product->price,settingHelper('default_currency'));
  552.                 $product_stock->current_stock   = $product->current_stock;
  553.                 $product_stock->save();
  554.             endif;
  555.  
  556.             DB::commit();
  557.             return true;
  558.         } catch (\Exception $e) {
  559.             DB::rollback();
  560.             dd($e);
  561.             return false;
  562.         }
  563.  
  564.     }
  565.  
  566.     public function update($request)
  567.     {
  568.         DB::BeginTransaction();
  569.         try {
  570.             $product = $this->get($request->id);
  571.             $product->description_images = $this->saveMultipleImage($request->description_images,$product);
  572.  
  573.             if ($request->thumbnail):
  574.                 $files = $this->getImageWithRecommendedSize($request->thumbnail, 190, 230);
  575.                 if ($files):
  576.                     $product->thumbnail = $files;
  577.                     $product->thumbnail_id = $request->thumbnail;
  578.                 else:
  579.                     $product->thumbnail = [];
  580.                     $product->thumbnail_id = null;
  581.                 endif;
  582.             else:
  583.                 $product->thumbnail = [];
  584.                 $product->thumbnail_id = null;
  585.             endif;
  586.  
  587.             if ($request->images != ''):
  588.                 $selected_images = explode(',', $request->images);
  589.                 $images = array();
  590.                 foreach ($selected_images as $key => $image):
  591.                     $files = $this->getImage($image);
  592.                     if ($files):
  593.                         array_push($images, $files);
  594.                     else:
  595.                         unset($selected_images[$key]);
  596.                     endif;
  597.                 endforeach;
  598.                 $product->images = $images;
  599.                 $product->image_ids = implode(',', $selected_images);
  600.             else:
  601.                 $product->images = [];
  602.                 $product->image_ids = null;
  603.             endif;
  604.  
  605.             $product->slug = $this->getSlug($request->name, $request->slug);
  606.             $product->category_id = $request->category != '' ? $request->category : null;
  607.             $product->brand_id = $request->brand != '' ? $request->brand : null;
  608. //            $product->created_by                = Sentinel::getUser()->id;
  609.  
  610.             $product->minimum_order_quantity = $request->minimum_order_quantity != '' ? $request->minimum_order_quantity : 1;
  611.             $product->barcode = $request->barcode != '' ? $request->barcode : $this->generate_random_string(16, 'upper');
  612.  
  613.             if ($request->video_provider != '' && $request->video_url != ''):
  614.                 $product->video_provider = $request->video_provider;
  615.                 $product->video_url = $request->video_url;
  616.             else:
  617.                 $product->video_provider    = '';
  618.                 $product->video_url         = '';
  619.             endif;
  620.  
  621.             $product->price = priceFormatUpdate($request->price,settingHelper('default_currency'));
  622.  
  623.             if ($request->special_discount_type != ''):
  624.                 $product->special_discount_type = $request->special_discount_type;
  625.                 $product->special_discount =  priceFormatUpdate($request->special_discount,settingHelper('default_currency'));
  626.  
  627.                 $dates = explode(" - ", $request->special_discount_period);
  628.  
  629.                 $product->special_discount_start = Carbon::createFromFormat('m-d-Y g:ia', $dates[0]);
  630.                 $product->special_discount_end = Carbon::createFromFormat('m-d-Y g:ia', $dates[1]);
  631.             else :
  632.                 $product->special_discount_type = null;
  633.                 $product->special_discount = 0.00;
  634.  
  635.                 $product->special_discount_start = null;
  636.                 $product->special_discount_end = null;
  637.             endif;
  638.             if ($request->has_variant == 1):
  639.                 $product->has_variant = 1;
  640.                 $product->current_stock = 0;
  641.                 $product->colors = $request->colors ?? [];
  642.                 $product->attribute_sets = $request->attribute_sets ?? [];
  643.             else:
  644.                 $product->has_variant = 0;
  645.                 $product->colors = [];
  646.                 $product->attribute_sets = [];
  647.                 $product->current_stock = $request->current_stock != '' ? $request->current_stock : 0;
  648.             endif;
  649.  
  650.  
  651.             if ($request->has('vat_taxes')):
  652.                 $product->vat_taxes = implode(',', $request->vat_taxes);
  653.             else:
  654.                 $product->vat_taxes = '';
  655.             endif;
  656.  
  657.             if ($request->meta_image != ''):
  658.                 $files = $this->getImageWithRecommendedSize($request->meta_image, 1200, 630);
  659.                 if ($files):
  660.                     $product->meta_image    = $files;
  661.                     $product->meta_image_id = $request->thumbnail;
  662.                 else:
  663.                     $product->meta_image    = $product->thumbnail;
  664.                     $product->meta_image_id = $product->thumbnail_id;
  665.                 endif;
  666.             else:
  667.                 $product->meta_image = $product->thumbnail;
  668.                 $product->meta_image_id = $product->thumbnail_id;
  669.             endif;
  670.  
  671.             if ($request->low_stock_to_notify != ''):
  672.                 $product->stock_notification = 1;
  673.                 $product->low_stock_to_notify = $request->low_stock_to_notify;
  674.             endif;
  675.             $product->stock_visibility = $request->stock_visibility ?? 'hide_stock';
  676.             if ($request->has('cash_on_delivery')):
  677.                 $product->cash_on_delivery = 1;
  678.             else:
  679.                 $product->cash_on_delivery = 0;
  680.             endif;
  681.             if ($request->has('is_refundable')):
  682.                 $product->is_refundable = 1;
  683.             else:
  684.                 $product->is_refundable = 0;
  685.             endif;
  686.             if ($request->has('is_catalog')):
  687.                 $product->is_catalog = 1;
  688.                 $product->external_link = $request->external_link;
  689.             else:
  690.                 $product->is_catalog = 0;
  691.             endif;
  692.             if ($request->has('is_featured')):
  693.                 $product->is_featured = 1;
  694.             else:
  695.                 $product->is_featured = 0;
  696.             endif;
  697.             //digital product will not get delivered
  698.             if ($request->has('is_digital')):
  699.                 $product->is_digital = 1;
  700.                 $product->minimum_order_quantity = 1;
  701.                 if ($request->product_file):
  702.                     $file = $this->getFile($request->product_file);
  703.                     if ($file):
  704.                         $product->product_file = $file;
  705.                         $product->product_file_id = $request->product_file;
  706.                     else:
  707.                         $product->product_file = [];
  708.                     endif;
  709.                 else:
  710.                     $product->product_file = [];
  711.                 endif;
  712.             else:
  713.                 $product->is_digital = 0;
  714.                 $product->estimated_shipping_days = $request->estimated_shipping_days != '' ? $request->estimated_shipping_days : 0;
  715.             endif;
  716.  
  717.             if ($request->has('todays_deal')):
  718.                 $product->todays_deal = $request->todays_deal;
  719.             else:
  720.                 $product->todays_deal = 0;
  721.             endif;
  722.  
  723.             //cost
  724.             if ($request->has('shipping_type')) :
  725.                 if ($request->shipping_type == 'free_shipping'):
  726.                     $product->shipping_fee = 0.00;
  727.                 elseif ($request->shipping_type == 'flat_rate'):
  728.                     $product->shipping_fee = $request->shipping_fee != '' ? priceFormatUpdate($request->shipping_fee,settingHelper('default_currency')) : 0.00;
  729.                 endif;
  730.                 $product->shipping_type = $request->shipping_type;
  731.  
  732.                 if ($request->has('shipping_fee_depend_on_quantity')):
  733.                     $product->shipping_fee_depend_on_quantity = $request->shipping_fee_depend_on_quantity;
  734.                 endif;
  735.             endif;
  736.             if ($request->has('is_classified')):
  737.                 $product->is_classified = 1;
  738.  
  739.                 $contact_details['contact_name'] = $request->contact_name;
  740.                 $contact_details['phone_no'] = $request->phone_no;
  741.                 $contact_details['email'] = $request->email;
  742.                 $contact_details['address'] = $request->address;
  743.                 $contact_details['others'] = $request->others;
  744.  
  745.                 $product->contact_info = $contact_details;
  746.             endif;
  747.             $product->save();
  748.  
  749.             $request['product_id'] = $product->id;
  750.             if (!isset($request->lang)) :
  751.                 $request['lang'] = 'en';
  752.             endif;
  753.  
  754.             $this->productLang->store($request);
  755.  
  756.             if ($request->campaign) :
  757.                 if ($product->campaign):
  758.                     $campaign_product = CampaignProduct::find($product->campaign->id);
  759.                 else :
  760.                     $campaign_product = new CampaignProduct();
  761.                 endif;
  762.                 $campaign_product->campaign_id      = $request->campaign;
  763.                 $campaign_product->product_id       = $product->id;
  764.                 $campaign_product->discount         = priceFormatUpdate($request->campaign_discount,settingHelper('default_currency'));
  765.                 $campaign_product->discount_type    = $request->campaign_discount_type;
  766.                 $campaign_product->save();
  767.  
  768.                 $campaign                           = Campaign::find($request->campaign);
  769.                 $product->special_discount_type     = $request->campaign_discount_type;
  770.                 $product->special_discount          = priceFormatUpdate($request->campaign_discount ,settingHelper('default_currency'));
  771.                 $product->special_discount_start    = $campaign->start_date;
  772.                 $product->special_discount_end      = $campaign->end_date;
  773.             endif;
  774.             foreach ($product->stock as $key => $stock):
  775.                 $stock->delete();
  776.             endforeach;
  777.             if ($product->has_variant == 1 && $request->has('variant_name')):
  778.                 $total_stock = 0;
  779.                 foreach ($request->variant_name as $key => $variant):
  780.                     if ($request['variant_name'][$key]):
  781.                         $product_stock = ProductStock::where('product_id', $product->id)->where('name', $request['variant_name'][$key])->first();
  782.                         if ($product_stock == ''):
  783.                             $product_stock = new ProductStock();
  784.                         endif;
  785.                         $product_stock->product_id      = $product->id;
  786.                         $product_stock->variant_ids     = $request['variant_ids'][$key];
  787.                         $product_stock->name            = $request['variant_name'][$key];
  788.                         $product_stock->sku             = $request['variant_sku'][$key];
  789.                         $product_stock->current_stock   = $request['variant_stock'][$key];
  790.                         $product_stock->price           = priceFormatUpdate($request['variant_price'][$key],settingHelper('default_currency'));
  791.                         if ($request['variant_image'][$key] != ''):
  792.                             $files = $this->getImage($request['variant_image'][$key]);
  793.                             if ($files):
  794.                                 $product_stock->image = $files;
  795.                                 $product_stock->image_id = $request['variant_image'][$key];
  796.                             else:
  797.                                 $product_stock->image = [];
  798.                                 $product_stock->image_id = null;
  799.                             endif;
  800.                         else:
  801.                             $product_stock->image = [];
  802.                             $product_stock->image_id = null;
  803.                         endif;
  804.                         $total_stock += $product_stock->current_stock;
  805.                         $product_stock->save();
  806.                     endif;
  807.  
  808.                     $selected_variants      = array();
  809.                     $selected_variants_ids  = array();
  810.  
  811.                     if ($request->has('attribute_sets')):
  812.                         foreach ($request->attribute_sets as $attribute_set):
  813.                             $attribute_values = 'attribute_values_' . $attribute_set;
  814.                             $values = array();
  815.                             if ($request->has($attribute_values)):
  816.                                 foreach ($request[$attribute_values] as $value):
  817.                                     array_push($values, $value);
  818.                                     array_push($selected_variants_ids, $value);
  819.                                 endforeach;
  820.                                 $selected_variants[$attribute_set] = $values;
  821.                             endif;
  822.                         endforeach;
  823.                     endif;
  824.                     $product->selected_variants         = $selected_variants;
  825.                     $product->selected_variants_ids     = $selected_variants_ids;
  826.                 endforeach;
  827.  
  828.                 $product->current_stock                 = $total_stock;
  829.                 $product->save();
  830.             else:
  831.                 $product_stock                          = $product->stock->first();
  832.                 if ($product_stock == ''):
  833.                     $product_stock                      = new ProductStock();
  834.                 endif;
  835.                 $product_stock->product_id              = $product->id;
  836.                 $product_stock->sku                     = $request->sku;
  837.                 $product_stock->name                    = '';
  838.                 $product_stock->price                   = priceFormatUpdate($product->price ,settingHelper('default_currency'));
  839.                 $product_stock->image                   = [];
  840.                 $product_stock->image_id                = null;
  841.                 $product_stock->current_stock           = $product->current_stock;
  842.                 $product_stock->save();
  843.             endif;
  844.  
  845.             DB::commit();
  846.             return true;
  847.         } catch (\Exception $e) {
  848.             DB::rollback();
  849.             return false;
  850.         }
  851.     }
  852.  
  853.     public function productView($request)
  854.     {
  855.         DB::BeginTransaction();
  856.         try {
  857.             $product                = Product::where('slug', $request['product_slug'])->CheckSellerSystem()->first();
  858.  
  859.             $user_id                = authId();
  860.             ProductView::where('product_id', $product->id)->delete();
  861.  
  862.             $view               = new ProductView();
  863.             $view->product_id   = $product->id;
  864.             $view->user_id      = $user_id;
  865.             $view->save();
  866.  
  867.             DB::commit();
  868.             return true;
  869.         } catch (\Exception $e) {
  870.             DB::rollback();
  871.             return false;
  872.         }
  873.     }
  874.  
  875.     public function statusChange($request)
  876.     {
  877.         DB::beginTransaction();
  878.         try {
  879.             $product = $this->get($request['id']);
  880.             if ($request['change_for'] != 'status') :
  881.                 $product[$request['change_for']] = $request['status'];
  882.             else:
  883.                 $product->status = $request['status'] == '1' ? 'published' : 'unpublished';
  884.             endif;
  885.             $product->save();
  886.  
  887.             DB::commit();
  888.             return true;
  889.         } catch (\Exception $e) {
  890.             DB::rollback();
  891.             return false;
  892.         }
  893.     }
  894.  
  895.     public function variantStore($request, $product_id)
  896.     {
  897.  
  898.     }
  899.  
  900.     public function restore($id)
  901.     {
  902.         DB::beginTransaction();
  903.         try {
  904.             $product = Product::withTrashed()->find($id);
  905.             $product->status        = 'unpublished';
  906.             $product->is_deleted    = 0;
  907.             $product->save();
  908.  
  909.             Product::withTrashed()->find($id)->restore();
  910.             DB::commit();
  911.             return true;
  912.         } catch (\Exception $e) {
  913.             DB::rollback();
  914.             return false;
  915.         }
  916.     }
  917.  
  918.     public function productStatusChange($status, $id)
  919.     {
  920.         DB::beginTransaction();
  921.         try {
  922.             $product = $this->get($id);
  923.             if ($status == 'pending'):
  924.                 $product->is_approved = 0;
  925.             elseif ('approve'):
  926.                 $product->is_approved = 1;
  927.             endif;
  928.             $product->save();
  929.  
  930.             DB::commit();
  931.             return true;
  932.         } catch (\Exception $e) {
  933.             DB::rollback();
  934.             return false;
  935.         }
  936.     }
  937.  
  938.     //for api
  939.     public function todayDeals()
  940.     {
  941.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->selectRaw('id,price,special_discount,minimum_order_quantity,current_stock,special_discount_type,special_discount_start,special_discount_end,rating,thumbnail,slug,reward,todays_deal,has_variant')
  942.             ->ProductPublished()->where('todays_deal', 1)
  943.             ->UserCheck()->IsWholesale()->IsStockOut()->latest()->take(16)->get();
  944.     }
  945.  
  946.     public function bestSelling()
  947.     {
  948.         return Product::with('category')->whereIn('category_id', [13, 19, 15, 17, 21, 23, 25 ])->get();
  949.     }
  950.  
  951.     public function offerEndingSoon($limit = null)
  952.     {
  953.         if (!$limit)
  954.         {
  955.             $limit = 8;
  956.         }
  957.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->UserCheck()->IsWholesale()->IsStockOut()->where('is_wholesale',0)
  958.             ->selectRaw('id,price,special_discount,is_wholesale,special_discount_type,minimum_order_quantity,current_stock,special_discount_start,special_discount_end,rating,thumbnail,slug,reward')
  959.             ->where('special_discount', '>', 0)->where('special_discount_end', '!=', null)->ProductPublished()
  960.             ->orderBy(DB::raw('ABS(DATEDIFF(products.special_discount_end, NOW()))'))->latest()->paginate($limit);
  961.     }
  962.  
  963.     public function productByOffer()
  964.     {
  965.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('special_discount', '>', 0)->where('special_discount_end', '!=', null)->ProductPublished()
  966.             ->orderBy(DB::raw('ABS(DATEDIFF(products.special_discount_end, NOW()))'))->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate(16);
  967.     }
  968.  
  969.     public function productByBestSelling($limit = null)
  970.     {
  971.         if (!$limit)
  972.         {
  973.             $limit = 16;
  974.         }
  975.  
  976.         // Product::with('category')->whereIn('category_id', [13, 19, 15, 17, 21, 23, 25 ])->withAvg('reviews','rating')->withCount('reviews')
  977.         //     ->selectRaw('id,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,total_sale,thumbnail,slug,reward,current_stock')
  978.         //     ->ProductPublished()->orderBy('total_sale', 'desc')->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate($limit);
  979.  
  980.     $selling = Product::with('category')->whereIn('category_id', [13, 19, 15, 17, 21, 23, 25 ])->get();
  981.  
  982.         Log::info('data: '. json_encode($selling));
  983.  
  984.         return $selling;
  985.  
  986.     }
  987.  
  988.     public function productByGadget($slug)
  989.     {
  990.         $category = Category::where('slug', $slug)->first();
  991.         return Product::withAvg('reviews','rating')->withCount('reviews')->where('category_id', $category->id)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate(16);
  992.     }
  993.  
  994.     public function viewedProduct()
  995.     {
  996.         $auth_id = authId();
  997.         $viewed_products = Product::withAvg('reviews','rating')->whereHas('viewedProducts', function ($query) use ($auth_id) {
  998.             $query->where('user_id', $auth_id)->groupBy('product_id')->latest();
  999.         })->selectRaw('id,thumbnail,slug,price,rating,current_stock,reward,minimum_order_quantity,special_discount,special_discount_start,special_discount_end')
  1000.             ->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()->take(10)->get();
  1001.  
  1002.         if (count($viewed_products) < 20) {
  1003.             $left_product = 20 - count($viewed_products);
  1004.  
  1005.             $products = Product::withAvg('reviews','rating')->whereHas('viewedProducts', function ($query) {
  1006.                 $query->groupBy('product_id')->latest();
  1007.             })->selectRaw('id,thumbnail,slug,price,rating,current_stock,reward,minimum_order_quantity,special_discount,special_discount_start,special_discount_end')
  1008.                 ->ProductPublished()->whereNotIn('id', $viewed_products->pluck('id')->toArray())->UserCheck()->IsWholesale()->IsStockOut()->latest()->take($left_product)->get();
  1009.  
  1010.             return $viewed_products->merge($products);
  1011.         }
  1012.         return $viewed_products;
  1013.     }
  1014.  
  1015.     public function productDetails($slug)
  1016.     {
  1017.         return Product::with(['brand:id', 'category:id', 'reviews', 'stock', 'userWishlist','userReview'])->withAvg('reviews','rating')
  1018.             ->withCount('monthlyOrders')->withCount('reviews')->where('slug', $slug)->UserCheck()->IsWholesale()->IsStockOut()->first();
  1019.     }
  1020.  
  1021.     public function dailyDeals($paginate)
  1022.     {
  1023.         return Product::withAvg('reviews','rating')->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()
  1024.             ->selectRaw('id,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,thumbnail,slug,reward,current_stock,created_at')
  1025.             ->where('todays_deal', 1)->latest()->paginate($paginate);
  1026.     }
  1027.  
  1028.     public function productByCampaign($campaign_id, $paginate = null): \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1029.     {
  1030.         if (!$paginate) {
  1031.             $paginate = 12;
  1032.         }
  1033.  
  1034.         return Product::withAvg('reviews','rating')->join('campaign_products', 'products.id', 'campaign_products.product_id')
  1035.             ->join('campaigns', 'campaign_products.campaign_id', 'campaigns.id')
  1036.             ->join('users', 'products.user_id', 'users.id')->where('users.status', 1)
  1037.             ->where('campaigns.id', $campaign_id)->where('products.status', 'published')->where('products.is_approved',1)
  1038.             ->where('users.is_user_banned', 0)->IsWholesale()->IsStockOut()
  1039.             ->select('products.id', 'campaigns.id as campaign_id', 'campaigns.slug as campaign_slug', 'current_stock', 'products.price', 'special_discount', 'special_discount_type', 'rating', 'text_color', 'start_date', 'end_date', 'products.special_discount_start', 'products.special_discount', 'products.special_discount_end', 'products.thumbnail', 'products.slug', 'reward')
  1040.             ->orderBy('campaigns.created_at', 'desc')->paginate($paginate);
  1041.     }
  1042.  
  1043.     public function categoryProducts($slug): \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1044.     {
  1045.         $category = Category::where('slug', $slug)->first();
  1046.         return Product::withAvg('reviews','rating')->where('category_id', $category->id)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->paginate(8);
  1047.     }
  1048.  
  1049.     public function filterProduct($data): \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1050.     {
  1051.  
  1052.         DB::connection()->enableQueryLog();
  1053.         $price_range = $this->priceRange();
  1054.         $products = Product::query();
  1055.  
  1056.         if (array_key_exists('key', $data) && !empty($data['key'])) {
  1057.             $products->whereHas('productLanguages', function ($query) use ($data) {
  1058.                 $query->where('name', 'like', '%' . $data['key'] . '%');
  1059.             });
  1060.         } else {
  1061.             if ($data['route'] == 'product.by.brand') {
  1062.                 $products->whereHas('brand', function ($q) use ($data) {
  1063.                     $q->where('slug', $data['slug']);
  1064.                 });
  1065.             }
  1066.             if ($data['route'] == 'product.by.category' || $data['route'] == 'product.by.gadget') {
  1067.  
  1068.                 $category = Category::where('slug', $data['slug'])->first();
  1069.                 $category_ids = \App\Utility\CategoryUtility::getMyAllChildIds($category->id);
  1070.                 $category_ids[] = $category->id;
  1071.                 $all_nested_category = array();
  1072.                 if ($category) {
  1073.                     if (array_key_exists('child_category', $data) && count($data['child_category']) > 0) {
  1074.                         foreach ($data['child_category'] as $child) {
  1075.                             $nested_category = \App\Utility\CategoryUtility::getMyAllChildIds($child);
  1076.                             $nested_category[] = (int)$child;
  1077.                             $all_nested_category[] = $nested_category;
  1078.                         }
  1079.                         $all_nested_category[] = [(int)$category->id];
  1080.                         $products->whereIn('category_id', array_merge(...$all_nested_category));
  1081.                     } else {
  1082.                         $products->whereIn('category_id', $category_ids);
  1083.                     }
  1084.                 }
  1085.             }
  1086.             if ($data['route'] == 'product.by.offer') {
  1087.                 $products->where('special_discount', '>', 0)->where('special_discount_end', '!=', null);
  1088.             }
  1089.  
  1090.             if ($data['route'] == 'shop') {
  1091.  
  1092.                 $products->whereHas('sellerProfile', function ($q) use ($data) {
  1093.                     $q->where('slug', $data['slug']);
  1094.                 });
  1095.             }
  1096.  
  1097.             if (array_key_exists('category', $data) && count($data['category']) > 0) {
  1098.                 $all_nested_category = [];
  1099.                 foreach ($data['category'] as $child) {
  1100.                     $nested_category = \App\Utility\CategoryUtility::getMyAllChildIds($child);
  1101.                     $nested_category[] = (int)$child;
  1102.                     $all_nested_category[] = $nested_category;
  1103.                 }
  1104.                 $products->whereIn('category_id', array_merge(...$all_nested_category));
  1105.             }
  1106.             if (array_key_exists('brand', $data) && count($data['brand']) > 0) {
  1107.                 $products->whereIn('brand_id', $data['brand']);
  1108.             }
  1109.             if (array_key_exists('price', $data)) {
  1110.                 $price = json_decode($data['price']);
  1111.  
  1112.                 if ($price->min == 0 && $price->max == 0)
  1113.                 {
  1114.                     $max = $price_range['max'];
  1115.                     $min = $price_range['min'];
  1116.                 }
  1117.                 else{
  1118.                     $max = $price->max;
  1119.                     $min = $price->min;
  1120.                 }
  1121.                 if (!$min)
  1122.                 {
  1123.                     $min = 0;
  1124.                 }
  1125.                 if (!$max) {
  1126.                     $max = 0;
  1127.                     $products->where('price', '>', $min);
  1128.                 } else {
  1129.                     $products->whereBetween('price', [$min, $max]);
  1130.                 }
  1131.             }
  1132.             if (array_key_exists('color', $data) && count($data['color']) > 0) {
  1133.  
  1134.                 $products->where(function ($query) use ($data) {
  1135.                     foreach ($data['color'] as $color) {
  1136.                         $query->where('colors', 'like', "%\"{$color}\"%");
  1137.                     }
  1138.                 });
  1139.             }
  1140.             $length = array_key_exists('rating', $data) ? count($data['rating']) : 0;
  1141.             if ($length > 0) {
  1142.                 sort($data['rating']);
  1143.  
  1144.                 if ($length > 1) {
  1145.                     $products->whereBetween('rating', [(int)$data['rating'][0], (int)$data['rating'][$length - 1]]);
  1146.                 } else {
  1147.                     $products->whereBetween('rating', [$data['rating'][0] - 0.5, (int)$data['rating'][0]]);
  1148.                 }
  1149.             }
  1150.             if (array_key_exists('attribute_value_id', $data) && count($data['attribute_value_id']) > 0) {
  1151.                 $products->where(function ($query) use ($data) {
  1152.                     foreach ($data['attribute_value_id'] as $attribute_value) {
  1153.                         $query->orWhere('selected_variants_ids', 'like', "%\"{$attribute_value}\"%");
  1154.                     }
  1155.                 });
  1156.             }
  1157.             if ($data['sort'] == 'newest') {
  1158.                 if ($data['route'] == 'product.by.selling') {
  1159.                     $products->orderByRaw("total_sale DESC, id DESC");
  1160.                 } else {
  1161.                     $products->latest();
  1162.                 }
  1163.             } elseif ($data['sort'] == 'oldest') {
  1164.                 $products->oldest();
  1165.             } elseif ($data['sort'] == 'top_rated') {
  1166.                 $products->orderBy('rating', 'desc');
  1167.             } elseif ($data['sort'] == 'top_selling') {
  1168.                 $products->withCount('orders')->orderBy('orders_count', 'desc');
  1169.             }
  1170.         }
  1171.  
  1172.         return  $products->with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')
  1173.             ->when($data['route'] == 'product.by.selling', function($q){
  1174.                 $q->orderByDesc('total_sale');
  1175.             })
  1176.             ->selectRaw('id,category_id,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,reward,current_stock,has_variant,minimum_order_quantity,todays_deal,total_sale')
  1177.             ->ProductPublished()
  1178.             ->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate($data['paginate']);
  1179.  
  1180.     }
  1181.  
  1182.     protected function saveSearchQuery($data){
  1183.         $oldQuery                   = Search::where('query',$data['key'])->first();
  1184.         if(blank($oldQuery) || $oldQuery == null):
  1185.             $searchQ                = new Search();
  1186.             $searchQ->query         = $data['key'];
  1187.             $searchQ->total_search  = 1;
  1188.             $searchQ->save();
  1189.         else:
  1190.             $oldQuery->total_search = $oldQuery->total_search+1;
  1191.             $oldQuery->save();
  1192.         endif;
  1193.  
  1194.     }
  1195.  
  1196.     public function relatedProducts($id, $take, $product_id)
  1197.     {
  1198.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('category_id', $id)->where('id', '!=', $product_id)->ProductPublished()
  1199.             ->UserCheck()->IsWholesale()->IsStockOut()->take($take)->get();
  1200.     }
  1201.  
  1202.     public function compareList(): int
  1203.     {
  1204.         if (authUser()) {
  1205.             $count = CompareProduct::whereHas('product')->where('user_id', authId())->count();
  1206.         } else {
  1207.             $count = session()->get('compare_list') ? count(session()->get('compare_list')) : 0;
  1208.         }
  1209.         return $count;
  1210.     }
  1211.  
  1212.     public function addToCompare($id)
  1213.     {
  1214.         return CompareProduct::create([
  1215.             'user_id'       => authId(),
  1216.             'product_id'    => $id,
  1217.         ]);
  1218.     }
  1219.  
  1220.     public function productByIds($ids)
  1221.     {
  1222.         return Product::with('brand:id', 'category:id','userWishlist')->withAvg('reviews','rating')->withCount('reviews')
  1223.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')
  1224.             ->whereIn('id', $ids)->UserCheck()->IsWholesale()->IsStockOut()->get();
  1225.     }
  1226.  
  1227.     public function compareProducts()
  1228.     {
  1229.         $product_ids = CompareProduct::where('user_id', authId())->pluck('product_id')->toArray();
  1230.         return $this->productByIds($product_ids);
  1231.     }
  1232.  
  1233.     public function removeCompareProduct($id)
  1234.     {
  1235.         $compare = CompareProduct::where('user_id', authId())->where('product_id', $id)->first();
  1236.         $product = $compare->product;
  1237.         $compare->delete();
  1238.         return $product;
  1239.     }
  1240.  
  1241.     public function bestSellingProduct($category_id)
  1242.     {
  1243.  
  1244.  
  1245.  
  1246.  
  1247.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('category_id',$category_id)->ProductPublished()
  1248.         ->UserCheck()->IsWholesale()->IsStockOut()->orderBy('total_sale','desc')->first();;
  1249.  
  1250.  
  1251.     }
  1252.  
  1253.     //seller wise products
  1254.     public function featuredProducts($ids)
  1255.     {
  1256.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->whereIn('id',$ids)->ProductPublished()->where('is_featured',1)
  1257.             ->UserCheck()->IsWholesale()->IsStockOut()
  1258.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')->get();
  1259.     }
  1260.  
  1261.     public function newProducts($user_id)
  1262.     {
  1263.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('user_id',$user_id)->ProductPublished()->latest()
  1264.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')
  1265.             ->UserCheck()->IsWholesale()->IsStockOut()->take(4)->get();
  1266.     }
  1267.  
  1268.     public function sellerBestSelling($user_id)
  1269.     {
  1270.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('user_id',$user_id)->ProductPublished()->orderBy('total_sale','desc')
  1271.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')
  1272.             ->UserCheck()->IsWholesale()->IsStockOut()->take(12)->get();
  1273.     }
  1274.  
  1275.     public function sellerOfferEnding($user_id)
  1276.     {
  1277.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('user_id',$user_id)->orderBy('total_sale','desc')->where('is_wholesale',0)
  1278.             ->where('special_discount', '>', 0)->where('special_discount_end', '!=', null)->ProductPublished()
  1279.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')
  1280.             ->UserCheck()->IsWholesale()->IsStockOut()->take(12)->get();
  1281.     }
  1282.  
  1283.     public function sellerProducts($user_id): \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1284.     {
  1285.         return Product::with('userWishlist')->withAvg('reviews','rating')->withCount('reviews')->where('user_id', $user_id)->ProductPublished()
  1286.             ->orderBy('id', 'desc')
  1287.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')
  1288.             ->UserCheck()->IsWholesale()->IsStockOut()->paginate(12);
  1289.     }
  1290.  
  1291.     public function campaignProducts()
  1292.     {
  1293.         return $this->takeCampaignProducts(8, null, 0);
  1294.  
  1295.     }
  1296.  
  1297.     public function latestProducts()
  1298.     {
  1299.         return Product::withAvg('reviews','rating')->withCount('reviews')->ProductPublished()->latest()
  1300.             ->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')
  1301.             ->UserCheck()->IsWholesale()->IsStockOut()->take(6)->get();
  1302.     }
  1303.  
  1304.     public function productByFlashSale()
  1305.     {
  1306.         return $this->takeAllCampaignProducts(0, null, 0);
  1307.     }
  1308.  
  1309.     public function takeCampaignProducts($take, $id, $skip)
  1310.     {
  1311.         return Product::withAvg('reviews','rating')->withCount('reviews')->join('campaign_products', 'products.id', 'campaign_products.product_id')
  1312.             ->join('campaigns', 'campaign_products.campaign_id', 'campaigns.id')
  1313.             ->join('users', 'products.user_id', 'users.id')->where('users.status', 1)
  1314.             ->where('products.status', 'published')->where('is_approved',1)->when($id,function($q) use ($id){
  1315.                 $q->where('campaigns.id', $id);
  1316.             })
  1317.             ->where('users.is_user_banned', 0)->IsWholesale()->IsStockOut()
  1318.             ->select('products.id', 'campaigns.id as campaign_id','campaigns.slug as campaign_slug','current_stock', 'products.price', 'special_discount', 'special_discount_type', 'rating',
  1319.                 'text_color', 'start_date', 'end_date', 'products.special_discount_start', 'products.special_discount','products.special_discount_end','products.thumbnail', 'products.slug','reward','minimum_order_quantity')
  1320.             ->orderBy('campaigns.created_at', 'desc')->take($take)->get();
  1321.     }
  1322.  
  1323.     public function takeAllCampaignProducts($take, $id, $skip)
  1324.     {
  1325.         return Product::withAvg('reviews','rating')->withCount('reviews')->join('campaign_products', 'products.id', 'campaign_products.product_id')
  1326.             ->join('campaigns', 'campaign_products.campaign_id', 'campaigns.id')
  1327.             ->join('users', 'products.user_id', 'users.id')->where('users.status', 1)
  1328.             ->where('products.status', 'published')->where('is_approved',1)->when($id,function($q) use ($id){
  1329.                 $q->where('campaigns.id', $id);
  1330.             })->where('products.status', 'published')
  1331.             ->where('users.is_user_banned', 0)->IsWholesale()->IsStockOut()
  1332.             ->select('products.id', 'campaigns.id as campaign_id','campaigns.slug as campaign_slug','current_stock', 'products.price', 'special_discount', 'special_discount_type', 'rating', 'text_color', 'start_date', 'end_date', 'products.special_discount_start', 'products.special_discount','products.special_discount_end','products.thumbnail', 'products.slug','reward')
  1333.             ->orderBy('campaigns.created_at', 'desc')->paginate(16);
  1334.     }
  1335.  
  1336.     public function priceRange(): array
  1337.     {
  1338.         $min = ProductStock::min('price');
  1339.  
  1340.  
  1341.         $max = ProductStock::max('price');
  1342.  
  1343.         return [
  1344.             'min' => $min,
  1345.             'max' => $max,
  1346.         ];
  1347.     }
  1348.  
  1349.     public function searchProduct($key)
  1350.     {
  1351.         $this->saveSearchQuery(['key' => $key]);
  1352.  
  1353.         return Product::withAvg('reviews','rating')->withCount('reviews')->whereHas('productLanguages', function ($query) use ($key) {
  1354.             $query->where('name', 'like', '%' . $key . '%');
  1355.         })->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')->ProductPublished()
  1356.             ->UserCheck()->IsWholesale()->IsStockOut()->latest()->take(20)->get();
  1357.     }
  1358.     //api end
  1359.  
  1360.     //mobileApi
  1361.     public function getLatestProducts($limit,$data)
  1362.     {
  1363.  
  1364.  
  1365.  
  1366.         $data1 = Product::withAvg('reviews','rating','stock')->withCount('reviews')->ProductPublished()->when(array_key_exists('seller_id',$data),function ($query) use($data){
  1367.             $query->whereHas('sellerProfile',function ($q) use($data){
  1368.                 $q->where('id',$data['seller_id']);
  1369.             });
  1370.         })->with('stock')->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1371.             ->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate($limit);
  1372.  
  1373.  
  1374.             // $data2 = Product::withAvg('reviews','rating','stock')->withCount('reviews')->ProductPublished()->when(array_key_exists('seller_id',$data),function ($query) use($data){
  1375.             //     $query->whereHas('sellerProfile',function ($q) use($data){
  1376.             //         $q->where('id',$data['seller_id']);
  1377.             //     });
  1378.             // })->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1379.             //     ->get();
  1380.  
  1381.  
  1382.  
  1383.  
  1384.         //    $d = ProductStock::where("product_id",1)->get();
  1385.  
  1386.  
  1387.             Log::info('Showing the user profile for user: '. json_encode($data1));
  1388.  
  1389.  
  1390.         return $data1;
  1391.  
  1392.  
  1393.  
  1394.  
  1395.     }
  1396.  
  1397.     public function getTopProducts($limit)
  1398.     {
  1399.         return Product::withAvg('reviews','rating')->withCount('reviews')->ProductPublished()
  1400.             ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1401.             ->UserCheck()->IsWholesale()->IsStockOut()->orderBy('total_sale', 'desc')->paginate($limit);
  1402.     }
  1403.  
  1404.     public function bestRatedProducts($limit)
  1405.     {
  1406.         return Product::withAvg('reviews','rating')->withCount('reviews')->ProductPublished()
  1407.             ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1408.             ->UserCheck()->IsWholesale()->IsStockOut()->orderBy('rating', 'desc')->paginate($limit);
  1409.     }
  1410.  
  1411.     public function flashDeals($limit)
  1412.     {
  1413.         return Product::withAvg('reviews','rating')->withCount('reviews')->join('campaign_products', 'products.id', 'campaign_products.product_id')
  1414.         ->join('campaigns', 'campaign_products.campaign_id', 'campaigns.id')
  1415.         ->join('users', 'products.user_id', 'users.id')->where('users.status', 1)
  1416.         ->where('products.status', 'published')->where('is_approved',1)->where('campaigns.flash_sale',1)
  1417.         ->where('users.is_user_banned', 0)->where('users.status',1)->IsWholesale()->IsStockOut()
  1418.         ->select('products.id', 'current_stock', 'products.price', 'special_discount', 'special_discount_type', 'rating', 'products.special_discount_start', 'products.special_discount','products.special_discount_end',
  1419.             'products.thumbnail', 'products.slug','reward','minimum_order_quantity','reward','total_sale')
  1420.         ->orderBy('campaigns.created_at', 'desc')->paginate($limit);
  1421.     }
  1422.  
  1423.     public function brandProducts($id, $limit)
  1424.     {
  1425.         return Product::withAvg('reviews','rating')->withCount('reviews')->where('brand_id',$id)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  1426.             ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1427.             ->paginate($limit);
  1428.     }
  1429.  
  1430.     public function categoryByProducts($id, $limit)
  1431.     {
  1432.         $category_ids = \App\Utility\CategoryUtility::getMyAllChildIds($id);
  1433.         $category_ids[] = (int)$id;
  1434.  
  1435.  
  1436.  
  1437.         $data = Product::withAvg('reviews','rating')->withCount('reviews')->with('stock','productLanguages','brand','category')->whereIn('category_id',$category_ids)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  1438.         ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1439.         ->get();
  1440.  
  1441.         // Product::with('stock','productLanguages','brand')->whereIn('category_id',$category_ids)->get();
  1442.  
  1443.  
  1444.         Log::info('Showing the user profile for user: '. json_encode($data));
  1445.  
  1446.  
  1447.         return $data;
  1448.     }
  1449.  
  1450.     public function shopProducts($user_id, $limit)
  1451.     {
  1452.         return Product::withAvg('reviews','rating')->withCount('reviews')->where('user_id',$user_id)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  1453.             ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1454.             ->paginate($limit);
  1455.     }
  1456.  
  1457.     public function search($key, $paginate)
  1458.     {
  1459.         if (!$paginate) {
  1460.             $paginate = 12;
  1461.         }
  1462.  
  1463.         $this->saveSearchQuery(['key' => $key]);
  1464.  
  1465.         return Product::withAvg('reviews','rating')->withCount('reviews')->whereHas('productLanguages', function ($query) use ($key) {
  1466.             $query->where('name', 'like', '%' . $key . '%');
  1467.         })->selectRaw('id,brand_id,category_id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,has_variant,reward,current_stock')->ProductPublished()
  1468.             ->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate($paginate);
  1469.     }
  1470.  
  1471.     public function wishlistsProduct($user_id,$limit)
  1472.     {
  1473.         return Product::withAvg('reviews','rating')->withCount('reviews')->whereHas('wishlists',function ($query) use($user_id){
  1474.             $query->where('user_id',$user_id);
  1475.         })->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()
  1476.             ->selectRaw('id,status,price,special_discount,special_discount_type,special_discount_start,special_discount_end,rating,slug,thumbnail,minimum_order_quantity,reward,current_stock,total_sale,has_variant')
  1477.             ->paginate($limit);
  1478.     }
  1479.  
  1480.     public function viewedProducts($user,$paginate)
  1481.     {
  1482.         if ($user)
  1483.         {
  1484.             $auth_id = $user->id;
  1485.             $products = Product::withAvg('reviews','rating')->withCount('reviews')->whereHas('viewedProducts', function ($query) use ($auth_id) {
  1486.                 $query->where('user_id', $auth_id)->groupBy('product_id')->latest();
  1487.             })->selectRaw('id,thumbnail,slug,price,rating,current_stock,reward,minimum_order_quantity,special_discount,special_discount_start,special_discount_end')
  1488.                 ->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate($paginate);
  1489.         }
  1490.         else{
  1491.             $products = Product::withAvg('reviews','rating')->withCount('reviews')->whereHas('viewedProducts', function ($query) {
  1492.                 $query->groupBy('product_id')->latest();
  1493.             })->selectRaw('id,thumbnail,slug,price,rating,current_stock,reward,minimum_order_quantity,special_discount,special_discount_start,special_discount_end')
  1494.                 ->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()->paginate($paginate);
  1495.  
  1496.         }
  1497.         return $products;
  1498.     }
  1499.  
  1500.     public function adminProducts($id)
  1501.     {
  1502.         return Product::where('user_id',1)->where('id', '!=',$id)->ProductPublished()->UserCheck()->IsWholesale()->IsStockOut()->latest()->limit(4)->get();
  1503.     }
  1504. }
  1505.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement