<?php

namespace App\Repositories;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;

use App\Models\BusinessProducts;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;

class BusinessProductsRepository
{
    public function __construct(
        BusinessProductsCategoryValuesRepository $businessProductsCategoryValuesRepository,
        BusinessProducts $businessProducts,
        PageRepository $pageRepository,
        CommunitySpaceUsedRepository $communitySpaceUsedRepository,
        Filesystem $filesystem,
        Mailer $mailer
    ) {
        $this->businessProductsCategoryValuesRepository = $businessProductsCategoryValuesRepository;
        $this->model = $businessProducts;
        $this->pageRepository = $pageRepository;
        $this->communitySpaceUsedRepository = $communitySpaceUsedRepository;
        $this->file = $filesystem;
        $this->mailer = $mailer;
    }

    public function getByBusiness($business_id, $limit = 20)
    {
        return $this->model->where('business_id', $business_id)->orderBy('id', 'desc')->paginate($limit);
    }

    public function getProductsByBusiness($business_id, $term = null, $limit = 4)
    {
        if ($term) {
            $product = $this->model
                ->where('business_id', $business_id)
                ->where('status', 1)
                ->where(function ($product) use ($term) {
                    $product->where('product_name', 'LIKE', '%'.$term.'%')
                        ->orWhere('product_description', 'LIKE', '%'.$term.'%');
                })
                ->orderBy('id', 'desc')->get();

            return $product;
        } else {
            return $this->model->where('business_id', $business_id)->where('status', 1)->orderBy('id', 'desc')->get();
        }
    }

    public function getById($id)
    {
        return $this->model->where('id', $id)->first();
    }

    public function getByIdWithBusiness($id)
    {
        return $this->model->with('business')->where('id', $id)->first();
    }

    public function addProduct($val, $page, $liquid_mode_value, $liquid_mode_price, $size_mode_value, $color_mode_value, $price_mode_value, $sku_mode_value, $quantity_mode_value, $liquid_mode_weight = null, $liquid_mode_weight_unit = null, $liquid_mode_length = null, $liquid_mode_width = null, $liquid_mode_height = null, $liquid_mode_dimensions_unit = null, $size_mode_weight = null, $size_mode_weight_unit = null, $size_mode_length = null, $size_mode_width = null, $size_mode_height = null, $size_mode_dimensions_unit = null, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'product_name' => '',
            'quantity_available' => '',
            'price' => '',
            'tax_applicable' => '',
            'currency' => '',
            'product_description' => '',
            'product_video' => '',
            'discount' => '',
            'shipping_cost' => '',
            'shipping_cost_2' => '',
            'shipping_cost_3' => '',
            'shipping_cost_4' => '',
            'shipping_cost_5' => '',
            'item_number' => '',
            'is_free_shipping' => '',
            'is_product_physical' => 1,
            'free_area' => '',
            'is_discounted' => '',
            'product_category' => '',
            'pr_category' => 0,
            'product_image_1_data' => '',
            'product_image_2_data' => '',
            'product_image_3_data' => '',
            'product_image_4_data' => '',
            'product_image_5_data' => '',
            'weight' => '',
            'weight_unit' => 'lbs',
			'weight_2' => '',
            'weight_unit_2' => 'lbs',
			'weight_3' => '',
            'weight_unit_3' => 'lbs',
            'length' => '',
            'width' => '',
            'height' => '',
            'dimensions_unit' => 'inches',
            'package_type' => 'Box',
            'length_2' => '',
            'width_2' => '',
            'height_2' => '',
            'dimensions_unit_2' => 'inches',
            'package_type_2' => 'Box',
            'length_3' => '',
            'width_3' => '',
            'height_3' => '',
            'dimensions_unit_3' => 'inches',
            'package_type_3' => 'Box',
            'shipping_cost_free'=>'no',
            'shipping_cost_2_free'=>'no',
            'shipping_cost_3_free'=>'no',
			'has_confirmed_for_sale'=>1,
        ];

        extract(array_merge($expected, $val));

        $isProductPhysicalRaw = (is_array($val) && array_key_exists('is_product_physical', $val)) ? $val['is_product_physical'] : $is_product_physical;
        if (is_array($isProductPhysicalRaw)) {
            $isProductPhysicalRaw = end($isProductPhysicalRaw);
        }
        $isProductPhysicalInt = (int) $isProductPhysicalRaw;

        $shipping_cost = is_numeric($shipping_cost) ? $shipping_cost : 0;
        $shipping_cost_2 = is_numeric($shipping_cost_2) ? $shipping_cost_2 : 0;
        $shipping_cost_3 = is_numeric($shipping_cost_3) ? $shipping_cost_3 : 0;
        $shipping_cost_4 = is_numeric($shipping_cost_4) ? $shipping_cost_4 : 0;
        $shipping_cost_5 = is_numeric($shipping_cost_5) ? $shipping_cost_5 : 0;

        if (! $isProductPhysicalInt) {
            $shipping_cost = 0;
            $shipping_cost_2 = 0;
            $shipping_cost_3 = 0;
            $shipping_cost_4 = 0;
            $shipping_cost_5 = 0;
        }

        $product_image1 = '';

        if ($is_discounted == 0) {
            $discount = '';
        }

        $CDNRepository = app('App\\Repositories\\CDNRepository');
        $filePath = '/uploads/community/'.$page->community_id.'/business/products';

        $upload_key = Str::random(20);
        $type = 'product-image';

        if (request()->hasFile('product_video')) {
            if (! Schema::hasColumn('business_products', 'product_video')) {
                throw new \Exception('Database column "product_video" is missing in "business_products" table. Please add it then upload again.');
            }
        }

        $product_image1 = '';

        if ($product_image_1_data != '') {
            $product_image_1_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_1_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_1_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image1 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image1,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image1 = '';
            }
        }

        /*if (request()->hasFile('product_image1'))
        {
            $product_image1 = request()->file('product_image1');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt1 = $product_image1->getClientOriginalExtension();

            $file_original_ext = $fileExt1;
            $file_original_name = $product_image1->getClientOriginalName();
            $file_original_size = $product_image1->getSize();
            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName1 = md5($product_image1->getClientOriginalName() . time()) . '.' . strtolower($fileExt1);
                $product_image1_path = $filePath ."/". $fileName1;
                $product_image1->move(public_path() . '/' . $filePath, $fileName1);
                $uploadPath1 = $filePath.'/'.$fileName1;
                $newFileName1 = $CDNRepository->upload(public_path() . '/' . $uploadPath1, $uploadPath1);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image1_path);
                $product_image1 = $newFileName1;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image1,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image1="";
            }
        }*/

        $product_image2 = '';
        if ($product_image_2_data != '') {
            $product_image_2_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_2_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_2_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image2 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image2,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image2 = '';
            }
        }

        /*if (request()->hasFile('product_image2'))
        {
            $product_image2 = request()->file('product_image2');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt2 = $product_image2->getClientOriginalExtension();

            $file_original_ext = $fileExt2;
            $file_original_name = $product_image2->getClientOriginalName();
            $file_original_size = $product_image2->getSize();

            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName2 = md5($product_image2->getClientOriginalName() . time()) . '.' . strtolower($fileExt2);
                $product_image2_path = $filePath ."/". $fileName2;
                $product_image2->move(public_path() . '/' . $filePath, $fileName2);
                $uploadPath2 = $filePath.'/'.$fileName2;
                $newFileName2 = $CDNRepository->upload(public_path() . '/' . $uploadPath2, $uploadPath2);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image2_path);
                $product_image2 = $newFileName2;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image2,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image2="";
            }
        }*/

        $product_image3 = '';
        if ($product_image_3_data != '') {
            $product_image_3_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_3_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_3_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image3 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image3,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image3 = '';
            }
        }

        /*if (request()->hasFile('product_image3'))
        {
            $product_image3 = request()->file('product_image3');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt3 = $product_image3->getClientOriginalExtension();
            $file_original_ext = $fileExt3;
            $file_original_name = $product_image3->getClientOriginalName();
            $file_original_size = $product_image3->getSize();

            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName3 = md5($product_image3->getClientOriginalName() . time()) . '.' . strtolower($fileExt3);
                $product_image3_path = $filePath ."/" .$fileName3;
                $product_image3->move(public_path() . '/' . $filePath, $fileName3);
                $uploadPath3 = $filePath.'/'.$fileName3;
                $newFileName3 = $CDNRepository->upload(public_path() . '/' . $uploadPath3, $uploadPath3);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image3_path);
                $product_image3 = $newFileName3;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image3,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image3="";
            }
        }*/

        $product_image4 = '';

        if ($product_image_4_data != '') {
            $product_image_4_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_4_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_4_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image4 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image4,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image4 = '';
            }
        }

        $product_image5 = '';

        if ($product_image_5_data != '') {
            $product_image_5_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_5_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_5_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image5 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image5,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image5 = '';
            }
        }

        /*if (request()->hasFile('product_image4'))
        {
            $product_image4 = request()->file('product_image4');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt4 = $product_image4->getClientOriginalExtension();

            $file_original_ext = $fileExt4;
            $file_original_name = $product_image4->getClientOriginalName();
            $file_original_size = $product_image4->getSize();

            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName4 = md5($product_image4->getClientOriginalName() . time()) . '.' . strtolower($fileExt4);
                $product_image4_path = $filePath ."/" .$fileName4;
                $product_image4->move(public_path() . '/' . $filePath, $fileName4);
                $uploadPath4 = $filePath.'/'.$fileName4;
                $newFileName4 = $CDNRepository->upload(public_path() . '/' . $uploadPath4, $uploadPath4);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image4_path);
                $product_image4 = $newFileName4;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image4,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image4="";
            }
        }*/

        if (request()->hasFile('product_video')) {
            $product_video_file = request()->file('product_video');
            if (! $product_video_file || ! $product_video_file->isValid()) {
                throw new \Exception('Invalid product video file.');
            }

            $videoExt = strtolower((string) $product_video_file->getClientOriginalExtension());
            $allowedVideoExt = ['mp4', 'mov', 'm4v', 'webm', 'ogg', 'ogv', 'avi', 'wmv', '3gp'];
            if ($videoExt === '' || ! in_array($videoExt, $allowedVideoExt, true)) {
                throw new \Exception('Invalid product video format. Allowed: mp4, mov, m4v, webm, ogg, ogv, avi, wmv, 3gp.');
            }

            $mimeType = '';
            try {
                $mimeType = (string) $product_video_file->getMimeType();
            } catch (\Throwable $e) {
                $mimeType = '';
            }
            if ($mimeType !== '' && stripos($mimeType, 'video/') !== 0) {
                throw new \Exception('Invalid product video file type.');
            }
            $file_original_ext = $videoExt;
            $file_original_name = $product_video_file->getClientOriginalName();
            $file_original_size = (int) $product_video_file->getSize();

            $maxBytes = 10 * 1024 * 1024;
            if ($file_original_size > $maxBytes) {
                throw new \Exception('Product video upload limit is 10 MB.');
            }

            if (checkAvailableSpace($page->community_id, $file_original_size) == 0) {
                throw new \Exception('Not enough community storage space to upload product video.');
            }

            $videoPath = $filePath . '/videos';
            if (! is_dir(public_path('') . $videoPath)) {
                mkdir(public_path('') . $videoPath, 0777, true);
            }

            $videoFileName = md5($file_original_name . time()) . ($videoExt ? ('.' . $videoExt) : '');
            $product_video_file->move(public_path('') . $videoPath, $videoFileName);

            $uploadRel = ltrim($videoPath . '/' . $videoFileName, '/');
            $localFullPath = public_path() . '/' . $uploadRel;
            $uploadPath = 'media/appvideo/community/'.$page->community_id.'/business-products/'.$videoFileName;
            $newVideoName = $CDNRepository->upload($localFullPath, $uploadPath, 'videoUpload', '480');
            $CDNRepository->deleteThisFile($localFullPath);
            if (! $newVideoName) {
                throw new \Exception('Unable to upload product video.');
            }
            $product_video = $newVideoName;

            $fileArray = [
                'community_id' => $page->community_id,
                'user_id' => \Auth::user()->id,
                'file_path' => $product_video,
                'file_name' => $file_original_name,
                'file_type' => $file_original_ext,
                'file_size' => $file_original_size,
                'uploaded_date' => date('Y-m-d'),
                'type' => 'product-video',
                'type_id' => $page->id,
                'upload_key' => $upload_key,
            ];
            $this->communitySpaceUsedRepository->save($fileArray);
        }

        $product = $this->model->newInstance();
        $product->user_id = $userid;
        $product->community_id = $page->community_id;
        $product->business_id = $page->id;
        $product->product_name = sanitizeText($product_name);
        $product->quantity_available = $quantity_available;
        $product->price = $price;
        $product->tax_applicable = $tax_applicable;
        $product->currency = $currency;
        $product->product_description = $product_description;
        $product->discount = $discount;
        $product->is_discounted = $is_discounted;
        $product->shipping_cost = $shipping_cost;
        $product->shipping_cost_2 = $shipping_cost_2;
        $product->shipping_cost_3 = $shipping_cost_3;
        $product->shipping_cost_4 = $shipping_cost_4;
        $product->shipping_cost_5 = $shipping_cost_5;
        $product->is_free_shipping = $is_free_shipping;
        $product->free_area = $free_area;
        $product->product_category = $product_category;
        $product->category_id = $pr_category;
        $product->weight = $weight;
        $product->weight_unit = $weight_unit;
        $product->length = $length;
        $product->width = $width;
        $product->height = $height;
        $product->dimensions_unit = $dimensions_unit;
        $product->package_type = $package_type;
        $product->is_product_physical = $isProductPhysicalInt;
		$product->shipping_cost_free = $shipping_cost_free;
		$product->shipping_cost_2_free = $shipping_cost_2_free;
		$product->shipping_cost_3_free = $shipping_cost_3_free;
		
		$product->has_confirmed_for_sale=$has_confirmed_for_sale;
		
		$product->product_id=generateUUID();

        $product->item_number = $item_number;
        if ($product_image1 != '') {
            $product->image1 = $product_image1;
        }

        if ($product_image2 != '') {
            $product->image2 = $product_image2;
        }

        if ($product_image3 != '') {
            $product->image3 = $product_image3;
        }

        if ($product_image4 != '') {
            $product->image4 = $product_image4;
        }

        if ($product_image5 != '') {
            $product->image5 = $product_image5;
        }

		if ($product_video != '') {
			$product->product_video = $product_video;
		}

        $product->save();

        if ($product_category == 1) {
            $this->businessProductsCategoryValuesRepository->addContainerValues($product->id, $liquid_mode_value, $liquid_mode_price, 'liquid-size', $liquid_mode_weight, $liquid_mode_weight_unit, $liquid_mode_length, $liquid_mode_width, $liquid_mode_height, $liquid_mode_dimensions_unit);

            $getNewPrice = $this->businessProductsCategoryValuesRepository->getProductValue($product->id, 'liquid-size');

            if ($getNewPrice and $getNewPrice->price) {
                $newPrice = $getNewPrice->price;
            } else {
                $newPrice = 0;
            }

            $product->price = $newPrice;

            $product->save();

        } elseif ($product_category == 2) {

            $this->businessProductsCategoryValuesRepository->addValues($product->id, $size_mode_value, $color_mode_value, $price_mode_value, $sku_mode_value, $quantity_mode_value, 'wearable-size', $size_mode_weight, $size_mode_weight_unit, $size_mode_length, $size_mode_width, $size_mode_height, $size_mode_dimensions_unit);

            // $this->businessProductsCategoryValuesRepository->addContainerValues($product->id,$color_mode_value,$size_mode_price,'color');

            // $getNewPrice = $this->businessProductsCategoryValuesRepository->getProductValue($product->id,'color');

            $getNewPrice = $this->businessProductsCategoryValuesRepository->getProductValue($product->id, 'wearable-size');

            if ($getNewPrice and $getNewPrice->price) {
                $newPrice = $getNewPrice->price;
            } else {
                $newPrice = 0;
            }

            $product->price = $newPrice;
			
			
			if ($getNewPrice and $getNewPrice->quantity) {
				$product->quantity_available = $getNewPrice->quantity;
			}else{
				$product->quantity_available =0;
			}
			
			if ($getNewPrice and $getNewPrice->article_number) {
				$product->item_number = $getNewPrice->article_number;
			}else{
				$product->item_number = '';
			}
			
            $product->save();

        }

        if ($product) {
            $this->communitySpaceUsedRepository->updateId($upload_key, $product->id);
        }

        return $product;
    }

    public function productStatus($id, $value)
    {
        $id = (int) $id;
        $value = (int) $value;

        $product = $this->model->where('id', '=', $id)->first();
        if (! $product) {
            return false;
        }

        $product->status = $value;

        // Use Eloquent save so observers run (cache version bump, legacy forgets, etc.)
        return (bool) $product->save();
    }

    public function editProduct($val, $page, $productId, $liquid_mode_value, $liquid_mode_price, $size_mode_value, $color_mode_value, $price_mode_value, $sku_mode_value, $quantity_mode_value, $liquid_mode_weight = null, $liquid_mode_weight_unit = null, $liquid_mode_length = null, $liquid_mode_width = null, $liquid_mode_height = null, $liquid_mode_dimensions_unit = null, $size_mode_weight = null, $size_mode_weight_unit = null, $size_mode_length = null, $size_mode_width = null, $size_mode_height = null, $size_mode_dimensions_unit = null, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'product_name' => '',
            'quantity_available' => '',
            'price' => '',
            'tax_applicable' => '',
            'currency' => '',
            'product_description' => '',
            'product_video' => '',
            'discount' => '',
            'shipping_cost' => '',
            'shipping_cost_2' => '',
            'shipping_cost_3' => '',
            'shipping_cost_4' => '',
            'shipping_cost_5' => '',
            'item_number' => '',
            'is_free_shipping' => '',
            'is_product_physical' => 1,
            'free_area' => '',
            'is_discounted' => '',
            'product_category' => '',
            'pr_category' => 0,
            'product_image_1_data' => '',
            'product_image_2_data' => '',
            'product_image_3_data' => '',
            'product_image_4_data' => '',
            'weight' => '',
            'weight_unit' => 'lbs',
			'weight_2' => '',
            'weight_unit_2' => 'lbs',
			'weight_3' => '',
            'weight_unit_3' => 'lbs',
            'length' => '',
            'width' => '',
            'height' => '',
            'dimensions_unit' => 'inches',
            'package_type' => 'Box',
            'length_2' => '',
            'width_2' => '',
            'height_2' => '',
            'dimensions_unit_2' => 'inches',
            'package_type_2' => 'Box',
            'length_3' => '',
            'width_3' => '',
            'height_3' => '',
            'dimensions_unit_3' => 'inches',
            'package_type_3' => 'Box',
            'shipping_cost_free'=>'no',
            'shipping_cost_2_free'=>'no',
            'shipping_cost_3_free'=>'no',
			'product_type' => '',
			'recurring_order' => '',
			'subscription_min_cycle' => 1,
			'allow_local_pickup'=>0,
        ];

        extract(array_merge($expected, $val));

        $isProductPhysicalRaw = (is_array($val) && array_key_exists('is_product_physical', $val)) ? $val['is_product_physical'] : $is_product_physical;
        if (is_array($isProductPhysicalRaw)) {
            $isProductPhysicalRaw = end($isProductPhysicalRaw);
        }
        $isProductPhysicalInt = (int) $isProductPhysicalRaw;

        $shipping_cost = is_numeric($shipping_cost) ? $shipping_cost : 0;
        $shipping_cost_2 = is_numeric($shipping_cost_2) ? $shipping_cost_2 : 0;
        $shipping_cost_3 = is_numeric($shipping_cost_3) ? $shipping_cost_3 : 0;
        $shipping_cost_4 = is_numeric($shipping_cost_4) ? $shipping_cost_4 : 0;
        $shipping_cost_5 = is_numeric($shipping_cost_5) ? $shipping_cost_5 : 0;

        if (! $isProductPhysicalInt) {
            $shipping_cost = 0;
            $shipping_cost_2 = 0;
            $shipping_cost_3 = 0;
            $shipping_cost_4 = 0;
            $shipping_cost_5 = 0;
        }

        if ($is_discounted == 0) {
            $discount = '';
        }

        $product_image1 = '';

        $CDNRepository = app('App\\Repositories\\CDNRepository');
        $filePath = '/uploads/community/'.$page->community_id.'/business/products';

        $upload_key = Str::random(20);
        $type = 'product-image';

        if (request()->hasFile('product_video')) {
            if (! Schema::hasColumn('business_products', 'product_video')) {
                throw new \Exception('Database column "product_video" is missing in "business_products" table. Please add it then upload again.');
            }
        }

        $product_image1 = '';
        if ($product_image_1_data != '') {
            $product_image_1_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_1_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_1_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image1 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image1,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image1 = '';
            }
        }

        /*if (request()->hasFile('product_image1'))
        {
            $product_image1 = request()->file('product_image1');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt1 = $product_image1->getClientOriginalExtension();
               $file_original_ext = $fileExt1;
            $file_original_name = $product_image1->getClientOriginalName();
            $file_original_size = $product_image1->getSize();
            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName1 = md5($product_image1->getClientOriginalName() . time()) . '.' . strtolower($fileExt1);
                $product_image1_path = $filePath ."/". $fileName1;
                $product_image1->move(public_path() . '/' . $filePath, $fileName1);
                $uploadPath1 = $filePath.'/'.$fileName1;
                $newFileName1 = $CDNRepository->upload(public_path() . '/' . $uploadPath1, $uploadPath1);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image1_path);
                $product_image1 = $newFileName1;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image1,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image1="";
            }
        }*/

        $product_image2 = '';
        if ($product_image_2_data != '') {
            $product_image_2_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_2_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_2_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image2 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image2,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image2 = '';
            }
        }

        /*if (request()->hasFile('product_image2'))
        {
            $product_image2 = request()->file('product_image2');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt2 = $product_image2->getClientOriginalExtension();
               $file_original_ext = $fileExt2;
            $file_original_name = $product_image2->getClientOriginalName();
            $file_original_size = $product_image2->getSize();

            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName2 = md5($product_image2->getClientOriginalName() . time()) . '.' . strtolower($fileExt2);
                $product_image2_path = $filePath ."/". $fileName2;
                $product_image2->move(public_path() . '/' . $filePath, $fileName2);
                $uploadPath2 = $filePath.'/'.$fileName2;
                $newFileName2 = $CDNRepository->upload(public_path() . '/' . $uploadPath2, $uploadPath2);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image2_path);
                $product_image2 = $newFileName2;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image2,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image2="";
            }
        }*/

        $product_image3 = '';
        if ($product_image_3_data != '') {
            $product_image_3_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_3_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_3_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image3 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image3,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image3 = '';
            }
        }

        /*if (request()->hasFile('product_image3'))
        {
            $product_image3 = request()->file('product_image3');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt3 = $product_image3->getClientOriginalExtension();
            $file_original_ext = $fileExt3;
            $file_original_name = $product_image3->getClientOriginalName();
            $file_original_size = $product_image3->getSize();

            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName3 = md5($product_image3->getClientOriginalName() . time()) . '.' . strtolower($fileExt3);
                $product_image3_path = $filePath ."/" .$fileName3;
                $product_image3->move(public_path() . '/' . $filePath, $fileName3);
                $uploadPath3 = $filePath.'/'.$fileName3;
                $newFileName3 = $CDNRepository->upload(public_path() . '/' . $uploadPath3, $uploadPath3);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image3_path);
                $product_image3 = $newFileName3;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image3,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image3="";
            }
        }*/

        $product_image4 = '';
        if ($product_image_4_data != '') {
            $product_image_4_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_4_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_4_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image4 = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image4,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $type,
                    'type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image4 = '';
            }
        }

        /*if (request()->hasFile('product_image4'))
        {
            $product_image4 = request()->file('product_image4');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt4 = $product_image4->getClientOriginalExtension();
            $file_original_ext = $fileExt4;
            $file_original_name = $product_image4->getClientOriginalName();
            $file_original_size = $product_image4->getSize();

            if(checkAvailableSpace($page->community_id,$file_original_size)!=0){
                $fileName4 = md5($product_image4->getClientOriginalName() . time()) . '.' . strtolower($fileExt4);
                $product_image4_path = $filePath ."/" .$fileName4;
                $product_image4->move(public_path() . '/' . $filePath, $fileName4);
                $uploadPath4 = $filePath.'/'.$fileName4;
                $newFileName4 = $CDNRepository->upload(public_path() . '/' . $uploadPath4, $uploadPath4);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image4_path);
                $product_image4 = $newFileName4;

                $fileArray=[
                    'community_id'	=>	$page->community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image4,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $type,
                    'type_id'       =>  $page->id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image4="";
            }
        }*/

        if (request()->hasFile('product_video')) {
            $product_video_file = request()->file('product_video');
            if (! $product_video_file || ! $product_video_file->isValid()) {
                throw new \Exception('Invalid product video file.');
            }

            $videoExt = strtolower((string) $product_video_file->getClientOriginalExtension());
            $allowedVideoExt = ['mp4', 'mov', 'm4v', 'webm', 'ogg', 'ogv', 'avi', 'wmv', '3gp'];
            if ($videoExt === '' || ! in_array($videoExt, $allowedVideoExt, true)) {
                throw new \Exception('Invalid product video format. Allowed: mp4, mov, m4v, webm, ogg, ogv, avi, wmv, 3gp.');
            }

            $mimeType = '';
            try {
                $mimeType = (string) $product_video_file->getMimeType();
            } catch (\Throwable $e) {
                $mimeType = '';
            }
            if ($mimeType !== '' && stripos($mimeType, 'video/') !== 0) {
                throw new \Exception('Invalid product video file type.');
            }
            $file_original_ext = $videoExt;
            $file_original_name = $product_video_file->getClientOriginalName();
            $file_original_size = (int) $product_video_file->getSize();

            $maxBytes = 10 * 1024 * 1024;
            if ($file_original_size > $maxBytes) {
                throw new \Exception('Product video upload limit is 10 MB.');
            }

            if (checkAvailableSpace($page->community_id, $file_original_size) == 0) {
                throw new \Exception('Not enough community storage space to upload product video.');
            }

            $videoPath = $filePath . '/videos';
            if (! is_dir(public_path('') . $videoPath)) {
                mkdir(public_path('') . $videoPath, 0777, true);
            }

            $videoFileName = md5($file_original_name . time()) . ($videoExt ? ('.' . $videoExt) : '');
            $product_video_file->move(public_path('') . $videoPath, $videoFileName);

            $uploadRel = ltrim($videoPath . '/' . $videoFileName, '/');
            $localFullPath = public_path() . '/' . $uploadRel;
            $uploadPath = 'media/appvideo/community/'.$page->community_id.'/business-products/'.$videoFileName;
            $newVideoName = $CDNRepository->upload($localFullPath, $uploadPath, 'videoUpload', '480');
            $CDNRepository->deleteThisFile($localFullPath);
            if (! $newVideoName) {
                throw new \Exception('Unable to upload product video.');
            }
            $product_video = $newVideoName;

            $fileArray = [
                'community_id' => $page->community_id,
                'user_id' => \Auth::user()->id,
                'file_path' => $product_video,
                'file_name' => $file_original_name,
                'file_type' => $file_original_ext,
                'file_size' => $file_original_size,
                'uploaded_date' => date('Y-m-d'),
                'type' => 'product-video',
                'type_id' => $page->id,
                'upload_key' => $upload_key,
            ];
            $this->communitySpaceUsedRepository->save($fileArray);
        }

        $product = $this->getById($productId);
        $product->user_id = $userid;
        $product->community_id = $page->community_id;
        $product->business_id = $page->id;
        $product->product_name = sanitizeText($product_name);
        $product->quantity_available = $quantity_available;
        $product->price = $price;
        $product->tax_applicable = $tax_applicable;
        $product->shipping_cost = $shipping_cost;
        $product->shipping_cost_2 = $shipping_cost_2;
        $product->shipping_cost_3 = $shipping_cost_3;
        $product->shipping_cost_4 = $shipping_cost_4;
        $product->shipping_cost_5 = $shipping_cost_5;
        $product->currency = $currency;
        $product->product_description = $product_description;
        $product->discount = $discount;
        $product->is_discounted = $is_discounted;
        $product->is_free_shipping = $is_free_shipping;
        $product->free_area = $free_area;
       // $product->product_category = $product_category;
        $product->category_id = $pr_category;
        $product->weight = $weight;
        $product->weight_unit = $weight_unit;
        $product->length = $length;
        $product->width = $width;
        $product->height = $height;
        $product->dimensions_unit = $dimensions_unit;
        $product->package_type = $package_type;
        $product->is_product_physical = $isProductPhysicalInt;
		$product->shipping_cost_free = $shipping_cost_free;
		$product->shipping_cost_2_free = $shipping_cost_2_free;
		$product->shipping_cost_3_free = $shipping_cost_3_free;
		
		$product->product_type = $product_type;
		$product->allow_local_pickup=$allow_local_pickup;
		 
		if ($product_type == 1) {
            $product->recurring_order = $recurring_order;
			$product->subscription_min_cycle = $subscription_min_cycle;
        }
		
        
		$product->item_number = $item_number;
        if ($product_image1 != '') {
            $product->image1 = $product_image1;
        }

        if ($product_image2 != '') {
            $product->image2 = $product_image2;
        }

        if ($product_image3 != '') {
            $product->image3 = $product_image3;
        }

        if ($product_image4 != '') {
            $product->image4 = $product_image4;
        }

		if ($product_video != '') {
			$product->product_video = $product_video;
		}
		
		$product->has_confirmed_for_sale=1;

        $product->save();

		$product_category=$product->product_category;

        if ($product_category == 1) {
            // $liquidValues= $val['liquid_mode_value'];

            $this->businessProductsCategoryValuesRepository->addContainerValues($product->id, $liquid_mode_value, $liquid_mode_price, 'liquid-size', $liquid_mode_weight, $liquid_mode_weight_unit, $liquid_mode_length, $liquid_mode_width, $liquid_mode_height, $liquid_mode_dimensions_unit);

            $getNewPrice = $this->businessProductsCategoryValuesRepository->getProductValue($product->id, 'liquid-size');

            if ($getNewPrice and $getNewPrice->price) {
                $newPrice = $getNewPrice->price;
            } else {
                $newPrice = 0;
            }

            $product->price = $newPrice;

            $product->save();

        } elseif ($product_category == 2) {
            // $this->businessProductsCategoryValuesRepository->addValues($product->id,$size_mode_value,'wearable-size');

            $this->businessProductsCategoryValuesRepository->addValues($product->id, $size_mode_value, $color_mode_value, $price_mode_value, $sku_mode_value, $quantity_mode_value, 'wearable-size', $size_mode_weight, $size_mode_weight_unit, $size_mode_length, $size_mode_width, $size_mode_height, $size_mode_dimensions_unit);
            // $this->businessProductsCategoryValuesRepository->addContainerValues($product->id,$color_mode_value,$size_mode_price,'color');

            // $getNewPrice = $this->businessProductsCategoryValuesRepository->getProductValue($product->id,'color');

            $getNewPrice = $this->businessProductsCategoryValuesRepository->getProductValue($product->id, 'wearable-size');

            if ($getNewPrice and $getNewPrice->price) {
                $newPrice = $getNewPrice->price;
            } else {
                $newPrice = 0;
            }

            $product->price = $newPrice;
			
			if ($getNewPrice and $getNewPrice->quantity) {
				$product->quantity_available = $getNewPrice->quantity;
			}else{
				$product->quantity_available =0;
			}
			
			if ($getNewPrice and $getNewPrice->article_number) {
				$product->item_number = $getNewPrice->article_number;
			}else{
				$product->item_number = '';
			}
			

            $product->save();

			return  $product;
        }

        if ($product) {
            $this->communitySpaceUsedRepository->updateId($upload_key, $product->id);
        }
    }

    public function getByIdBusiness($id, $business_id)
    {
	
        return $this->model->where('id', $id)->where('business_id', $business_id)->where('status', 1)->orderBy('id', 'desc')->paginate(1);
    }
	
	public function getByIdBusinessSingle($id, $store)
    {
		$business_id=$store->id;
		
		if (\Auth::check()){
			$userid = \Auth::user()->id;	
			if($store and $store->user_id==$userid){
       			return $this->model->where('id', $id)->where('business_id', $business_id)->where('status', 1)->orderBy('id', 'desc')->paginate(1);
			}
		}
		
		 $product = $this->model
        ->where('id', $id)
        ->where('business_id', $business_id)
        ->where('status', 1)
        ->first();
		
		 // Hide incomplete products from everyone else
    if (
        $product->product_name == "" ||
        $product->category_id == "" ||
        $product->category_id == 0 ||
        $product->item_number == "" ||
        $product->quantity_available == "" ||
        $product->quantity_available == 0 ||
        $product->price == "" ||
        $product->price == 0 ||
        ($product->is_discounted == 1 && ($product->discount == "" || $product->discount == 0)) ||
        $product->length == "" ||
        $product->length == 0 ||
        $product->width == "" ||
        $product->width == 0 ||
        $product->height == "" ||
        $product->height == 0 ||
        $product->weight == "" ||
        $product->weight == 0 ||
        $product->shipping_cost == "" ||
        $product->shipping_cost == 0 ||
        $product->shipping_cost_2 == "" ||
        $product->shipping_cost_2 == 0 ||
        $product->shipping_cost_3 == "" ||
        $product->shipping_cost_3 == 0
    ) {
        return collect(); // Product is incomplete, don't show it
    }

    return $this->model
        ->where('id', $id)
        ->where('business_id', $business_id)
        ->where('status', 1)
        ->orderBy('id', 'desc')
        ->paginate(1);	 
    }

    public function getByBusinessId($id, $business_id)
    {
        return $this->model->where('id', $id)->where('business_id', $business_id)->first();
    }

    public function getAllByTitle($title)
    {
        $result = $this->model->where('product_name', 'like', '%'.$title.'%')->pluck('business_id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function getProductsByBusinessAdvance($pages, $term, $searchPages, $community_id, $offset = 0)
    {
        $limit = 9;

        $products = $this->model->with('business')->where('status', 1);

        $publicBusinessCommunity = app('App\\Repositories\\CommunityRepository')->publicBusinessCommunity();

        if ($searchPages == 'location') {
            $searchPages = 'yes';
            $term = '';
        }

        if ($publicBusinessCommunity and $community_id != $publicBusinessCommunity->id) {
            $products = $products->where('community_id', '=', $community_id);
        }

        if ($term and $searchPages == 'no') {
            $products = $products->where(function ($product) use ($term) {
                $product->where('product_name', 'LIKE', '%'.$term.'%')
                    ->orWhere('product_description', 'LIKE', '%'.$term.'%');
            })
                ->orderBy('id', 'desc')
            // ->paginate($limit);
                ->skip($offset)->take(9)->get();

            return $products;
        } elseif (! $term and $searchPages == 'yes') {
            $products = $products->whereIn('business_id', $pages)
                ->orderBy('id', 'desc')
            // ->paginate($limit);
                ->skip($offset)->take(9)->get();

            return $products;
        } elseif ($term and $searchPages == 'yes') {
            $products = $products->where(function ($product) use ($term) {
                $product->where('product_name', 'LIKE', '%'.$term.'%')
                    ->orWhere('product_description', 'LIKE', '%'.$term.'%');
            })
                ->whereIn('business_id', $pages)
                ->orderBy('id', 'desc')
            // ->paginate($limit);
                ->skip($offset)->take(9)->get();

            return $products;

        } else {
            $products = $products
                ->where('status', 1)
                ->orderBy('id', 'desc')
            // ->paginate($limit);
                ->skip($offset)->take(9)->get();

            return $products;
        }
    }

    public function getByBusinessIds($ids, $productIds)
    {
        return $this->model
            ->with('business')
            ->where('status', 1)
            ->whereIn('business_id', $ids)
            ->whereNotIn('id', $productIds)
            ->take(4)->orderBy(\DB::raw('rand()'))
            ->get();
    }

    public function addSocialProduct($val, $userid, $posted_in_community)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'product_type' => '',
            'product_name' => '',
            'quantity_available' => '',
            'price' => '',
            'tax_applicable' => '',
            'currency' => '',
            'product_description' => '',
            'discount' => '',
            'shipping_cost' => '',
            'shipping_cost_2' => '',
            'shipping_cost_3' => '',
            'shipping_cost_4' => '',
            'shipping_cost_5' => '',
            'item_number' => '',
            'is_free_shipping' => '',
            'free_area' => '',
            'is_discounted' => '',
            'recurring_order' => '',
            'recurring_shipping_cost' => '',
            'business_id' => 0,
            'subscription_min_cycle' => 1,
            'digital_product_type' => 0,
            'product_image_1_data' => '',
            'product_image_2_data' => '',
            'product_image_3_data' => '',
            'course_what_you_will_learn' => '',
            'course_related_topics' => '',
            'course_requirements' => '',
            'course_description' => '',
            'who_this_course_is_for' => '',
        ];

        extract(array_merge($expected, $val));

        $product_image1 = '';

        $is_discounted = 1;
        if ($discount == 0) {
            $is_discounted = 0;
        }

        $CDNRepository = app('App\\Repositories\\CDNRepository');
        $filePath = 'uploads/users/'.$userid.'/products';

        $filePath1 = '/uploads/users/'.$userid.'/products';

        $upload_key = Str::random(20);
        $upload_community_id = $posted_in_community;
        $upload_type_id = 0;
        $upload_type = 'social-product';

        $digital_video_sample_file = '';
        $digital_video_file = '';
        $digital_image_sample_file = '';
        $digital_image_file = '';
        $digital_sample_file = '';
        $digital_file_file = '';
        $digital_sample_file_original_name = '';
        $digital_sample_file_extension = '';
        $digital_file_original_name = '';
        $digital_file_extension = '';

        $digital_image_sample_file_2 = '';
        $digital_image_sample_file_3 = '';
        $digital_image_sample_file_4 = '';
        $digital_image_sample_file_5 = '';
        $digital_file_cover_image = '';

        $product_image1 = '';

        if ($product_image_1_data != '') {
            $product_image_1_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_1_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath1;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_1_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image1 = $newFileName;

                $fileArray = [
                    'community_id' => $upload_community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image1,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $upload_type,
                    'type_id' => $upload_type_id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image1 = '';
            }
        }

        /*if (request()->hasFile('product_image1'))
        {
            $product_image1 = request()->file('product_image1');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt1 = $product_image1->getClientOriginalExtension();
            $file_original_ext = $fileExt1;
            $file_original_name =$product_image1->getClientOriginalName();
            $file_original_size=$product_image1->getSize();

            if(checkAvailableSpace($upload_community_id,$file_original_size)!=0){
                $fileName1 = md5($product_image1->getClientOriginalName() . time()) . '.' . strtolower($fileExt1);
                $product_image1_path = $filePath ."/". $fileName1;
                $product_image1->move(public_path() . '/' . $filePath, $fileName1);
                $uploadPath1 = $filePath.'/'.$fileName1;
                $newFileName1 = $CDNRepository->upload(public_path() . '/' . $uploadPath1, $uploadPath1);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image1_path);
                $product_image1 = $newFileName1;

                $fileArray=[
                    'community_id'	=>	$upload_community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image1,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $upload_type,
                    'type_id'       =>  $upload_type_id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image1="";
            }
        }*/

        $product_image2 = '';

        if ($product_image_2_data != '') {
            $product_image_2_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_2_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath1;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_2_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image2 = $newFileName;

                $fileArray = [
                    'community_id' => $upload_community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image2,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $upload_type,
                    'type_id' => $upload_type_id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image2 = '';
            }
        }

        /*if (request()->hasFile('product_image2'))
        {
            $product_image2 = request()->file('product_image2');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt2 = $product_image2->getClientOriginalExtension();
            $file_original_ext = $fileExt2;
            $file_original_name = $product_image2->getClientOriginalName();
            $file_original_size = $product_image2->getSize();

            if(checkAvailableSpace($upload_community_id,$file_original_size)!=0){
                $fileName2 = md5($product_image2->getClientOriginalName() . time()) . '.' . strtolower($fileExt2);
                $product_image2_path = $filePath ."/". $fileName2;
                $product_image2->move(public_path() . '/' . $filePath, $fileName2);
                $uploadPath2 = $filePath.'/'.$fileName2;
                $newFileName2 = $CDNRepository->upload(public_path() . '/' . $uploadPath2, $uploadPath2);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image2_path);
                $product_image2 = $newFileName2;
                $fileArray=[
                    'community_id'	=>	$upload_community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image2,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $upload_type,
                    'type_id'       =>  $upload_type_id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image2="";
            }
        }*/

        $product_image3 = '';

        if ($product_image_3_data != '') {
            $product_image_3_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_3_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath1;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_3_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image3 = $newFileName;

                $fileArray = [
                    'community_id' => $upload_community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image3,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $upload_type,
                    'type_id' => $upload_type_id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image3 = '';
            }
        }

        /*if (request()->hasFile('product_image3'))
        {
            $product_image3 = request()->file('product_image3');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt3 = $product_image3->getClientOriginalExtension();
            $file_original_ext = $fileExt3;
            $file_original_name = $product_image3->getClientOriginalName();
            $file_original_size = $product_image3->getSize();

            if(checkAvailableSpace($upload_community_id,$file_original_size)!=0){
                $fileName3 = md5($product_image3->getClientOriginalName() . time()) . '.' . strtolower($fileExt3);
                $product_image3_path = $filePath ."/" .$fileName3;
                $product_image3->move(public_path() . '/' . $filePath, $fileName3);
                $uploadPath3 = $filePath.'/'.$fileName3;
                $newFileName3 = $CDNRepository->upload(public_path() . '/' . $uploadPath3, $uploadPath3);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image3_path);
                $product_image3 = $newFileName3;
                $fileArray=[
                    'community_id'	=>	$upload_community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image3,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $upload_type,
                    'type_id'       =>  $upload_type_id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image3="";
            }
        }*/

        if ($product_type == 2) {
            if ($digital_product_type == 1) {
                $digital_video_sample_file = request()->file('digital_video_sample_file');
                if ($digital_video_sample_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_video_sample_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_video_sample_file->getClientOriginalName();
                    $file_original_size = $digital_video_sample_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_video_sample_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_video_sample_file_path = $filePath.'/'.$fileName3;
                        $digital_video_sample_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $videoUploadPath = 'media/appvideo/'.$userid.'/products'.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $videoUploadPath, 'videoUpload');
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_video_sample_file_path);
                        $digital_video_sample_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_video_sample_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_video_sample_file = '';
                    }
                }

                $digital_video_file = request()->file('digital_video_file');
                if ($digital_video_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_video_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_video_file->getClientOriginalName();
                    $file_original_size = $digital_video_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_video_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_video_file_path = $filePath.'/'.$fileName3;
                        $digital_video_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $videoUploadPath = 'media/appvideo/'.$userid.'/products'.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $videoUploadPath, 'videoUpload');
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_video_file_path);
                        $digital_video_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_video_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_video_file = '';
                    }
                }
            } elseif ($digital_product_type == 2) {
                $digital_image_sample_file = request()->file('digital_image_sample_file');
                if ($digital_image_sample_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_path);
                        $digital_image_sample_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file = '';
                    }
                }

                $digital_image_sample_file_2 = request()->file('digital_image_sample_file_2');
                if ($digital_image_sample_file_2) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_2->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_2->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_2->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_2->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_2_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_2->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_2_path);
                        $digital_image_sample_file_2 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_2,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_2 = '';
                    }
                }

                $digital_image_sample_file_3 = request()->file('digital_image_sample_file_3');
                if ($digital_image_sample_file_3) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_3->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_3->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_3->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_3->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_3_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_3->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_3_path);
                        $digital_image_sample_file_3 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_3,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_3 = '';
                    }
                }

                $digital_image_sample_file_4 = request()->file('digital_image_sample_file_4');
                if ($digital_image_sample_file_4) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_4->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_4->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_4->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_4->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_4_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_4->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_4_path);
                        $digital_image_sample_file_4 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_4,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_4 = '';
                    }
                }

                $digital_image_sample_file_5 = request()->file('digital_image_sample_file_5');
                if ($digital_image_sample_file_5) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_5->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_5->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_5->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_5->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_5_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_5->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_5_path);
                        $digital_image_sample_file_5 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_5,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_5 = '';
                    }
                }

                $digital_image_file = request()->file('digital_image_file');
                if ($digital_image_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_file->getClientOriginalName();
                    $file_original_size = $digital_image_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_file_path = $filePath.'/'.$fileName3;
                        $digital_image_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_file_path);
                        $digital_image_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_file = '';
                    }
                }
            } elseif ($digital_product_type == 3) {

                $digital_file_cover_image = request()->file('digital_file_cover_image');
                if ($digital_file_cover_image) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_file_cover_image->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_file_cover_image->getClientOriginalName();
                    $file_original_size = $digital_file_cover_image->getSize();

                    $digital_file_cover_image_original_name = $file_original_name;
                    $digital_file_cover_image_extension = $fileExt3;

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_file_cover_image->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_file_cover_image_path = $filePath.'/'.$fileName3;
                        $digital_file_cover_image->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_file_cover_image_path);
                        $digital_file_cover_image = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_file_cover_image,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_file_cover_image = '';
                    }
                }

                $digital_sample_file = request()->file('digital_sample_file');
                if ($digital_sample_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_sample_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_sample_file->getClientOriginalName();
                    $file_original_size = $digital_sample_file->getSize();

                    $digital_sample_file_original_name = $file_original_name;
                    $digital_sample_file_extension = $fileExt3;

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_sample_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_sample_file_path = $filePath.'/'.$fileName3;
                        $digital_sample_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_sample_file_path);
                        $digital_sample_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_sample_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_sample_file = '';
                    }
                }

                $digital_file_file = request()->file('digital_file');
                if ($digital_file_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_file_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_file_file->getClientOriginalName();
                    $file_original_size = $digital_file_file->getSize();

                    $digital_file_original_name = $file_original_name;
                    $digital_file_extension = $fileExt3;

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_file_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_file_file_path = $filePath.'/'.$fileName3;
                        $digital_file_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_file_file_path);
                        $digital_file_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_file_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_file_file = '';
                    }
                }
            }
        }

        $course_video_preview_file = '';

        if ($product_type == 3) {
            $course_video_preview_file = request()->file('course_video_preview_file');
            if ($course_video_preview_file) {
                $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                $fileExt3 = $course_video_preview_file->getClientOriginalExtension();
                $file_original_ext = $fileExt3;
                $file_original_name = $course_video_preview_file->getClientOriginalName();
                $file_original_size = $course_video_preview_file->getSize();

                if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                    $fileName3 = md5($course_video_preview_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                    $digital_video_sample_file_path = $filePath.'/'.$fileName3;
                    $course_video_preview_file->move(public_path().'/'.$filePath, $fileName3);
                    $uploadPath3 = $filePath.'/'.$fileName3;
                    $videoUploadPath = 'media/appvideo/'.$userid.'/products'.'/'.$fileName3;
                    $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $videoUploadPath, 'videoUpload');
                    $CDNRepository->deleteThisFile(public_path().'/'.$digital_video_sample_file_path);
                    $course_video_preview_file = $newFileName3;
                    $fileArray = [
                        'community_id' => $upload_community_id,
                        'user_id' => \Auth::user()->id,
                        'file_path' => $course_video_preview_file,
                        'file_name' => $file_original_name,
                        'file_type' => $file_original_ext,
                        'file_size' => $file_original_size,
                        'uploaded_date' => date('Y-m-d'),
                        'type' => $upload_type,
                        'type_id' => $upload_type_id,
                        'upload_key' => $upload_key,
                    ];
                    $this->communitySpaceUsedRepository->save($fileArray);
                } else {
                    $course_video_preview_file = '';
                }
            }
        }

        $product = $this->model->newInstance();
        $product->user_id = $userid;
        $product->community_id = 0;
        $product->business_id = $business_id;
        $product->product_type = $product_type;
        if (is_array($val) && array_key_exists('is_product_physical', $val)) {
            $product->is_product_physical = (int) $val['is_product_physical'];
        }
        $product->product_name = sanitizeText($product_name);
        $product->quantity_available = $quantity_available;
        $product->price = $price;
        $product->tax_applicable = $tax_applicable;
        $product->currency = $currency;
        $product->product_description = $product_description;
        $product->discount = $discount;
        $product->is_discounted = $is_discounted;
        $product->item_number = $item_number;
        $product->posted_in_community = $posted_in_community;
        $product->subscription_min_cycle = $subscription_min_cycle;

        $product->digital_sample_file_original_name = $digital_sample_file_original_name;
        $product->digital_sample_file_extension = $digital_sample_file_extension;

        $product->digital_file_original_name = $digital_file_original_name;
        $product->digital_file_extension = $digital_file_extension;

        if ($product_type == 0) {
            $product->shipping_cost = $shipping_cost;
            $product->shipping_cost_2 = $shipping_cost_2;
            $product->shipping_cost_3 = $shipping_cost_3;
            $product->shipping_cost_4 = $shipping_cost_4;
            $product->shipping_cost_5 = $shipping_cost_5;

            if ($shipping_cost == '' and $shipping_cost_2 = '' and $shipping_cost_3 == '' and $shipping_cost_4 == '' and $shipping_cost_5 == '') {
                $product->is_free_shipping = 1;
            } else {
                $product->is_free_shipping = 0;
            }

            $product->free_area = $free_area;
        } else {
            $product->recurring_order = $recurring_order;
            $product->recurring_shipping_cost = $recurring_shipping_cost;
        }

        if ($product_image1 != '') {
            $product->image1 = $product_image1;
        }

        if ($product_image2 != '') {
            $product->image2 = $product_image2;
        }

        if ($product_image3 != '') {
            $product->image3 = $product_image3;
        }

        if ($digital_video_sample_file != '') {
            $product->digital_video_sample_file = $digital_video_sample_file;
        }

        if ($digital_video_file != '') {
            $product->digital_video_file = $digital_video_file;
        }

        if ($digital_image_sample_file != '') {
            $product->digital_image_sample_file = $digital_image_sample_file;
        }

        if ($digital_image_sample_file_2 != '') {
            $product->digital_image_sample_file1 = $digital_image_sample_file_2;
        }

        if ($digital_image_sample_file_3 != '') {
            $product->digital_image_sample_file2 = $digital_image_sample_file_3;
        }

        if ($digital_image_sample_file_4 != '') {
            $product->digital_image_sample_file3 = $digital_image_sample_file_4;
        }

        if ($digital_image_sample_file_5 != '') {
            $product->digital_image_sample_file4 = $digital_image_sample_file_5;
        }

        if ($digital_image_file != '') {
            $product->digital_image_file = $digital_image_file;
        }

        if ($digital_file_cover_image != '') {
            $product->digital_file_sample_cover = $digital_file_cover_image;
        }

        if ($digital_sample_file != '') {
            $product->digital_file_sample_file = $digital_sample_file;
        }

        if ($digital_file_file != '') {
            $product->digital_file_file = $digital_file_file;
        }

        $product->digital_type = $digital_product_type;

        if ($product_type == 3) {
            if ($course_video_preview_file) {
                $product->course_preview_video = $course_video_preview_file;
            }

            $product->course_what_you_will_learn = $course_what_you_will_learn;
            $product->course_related_topics = $course_related_topics;
            $product->course_requirements = $course_requirements;
            $product->course_description = $course_description;
            $product->who_this_course_is_for = $who_this_course_is_for;
        }

		$product->product_id=generateUUID();
		
        $product->save();

        if ($product) {
            $this->communitySpaceUsedRepository->updateId($upload_key, $product->id);
        }

        return $product;
    }

    public function editSocialProduct($product, $val, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'product_type' => '',
            'product_name' => '',
            'quantity_available' => '',
            'price' => '',
            'tax_applicable' => '',
            'currency' => '',
            'product_description' => '',
            'discount' => '',
            'shipping_cost' => '',
            'shipping_cost_2' => '',
            'shipping_cost_3' => '',
            'shipping_cost_4' => '',
            'shipping_cost_5' => '',
            'item_number' => '',
            'is_free_shipping' => '',
            'free_area' => '',
            'is_discounted' => '',
            'recurring_order' => '',
            'recurring_shipping_cost' => '',
            'business_id' => 0,
            'subscription_min_cycle' => 1,
            'product_image_1_data' => '',
            'product_image_2_data' => '',
            'product_image_3_data' => '',
            'course_what_you_will_learn' => '',
            'course_related_topics' => '',
            'course_requirements' => '',
            'course_description' => '',
            'who_this_course_is_for' => '',
        ];

        extract(array_merge($expected, $val));

        $product_image1 = '';

        $is_discounted = 1;

        if ($discount == 0) {
            $is_discounted = 0;
        }

        $CDNRepository = app('App\\Repositories\\CDNRepository');
        $filePath = 'uploads/users/'.$userid.'/products';

        $filePath1 = '/uploads/users/'.$userid.'/products';

        $upload_key = Str::random(20);
        $upload_community_id = $product->posted_in_community;
        $upload_type_id = 0;
        $upload_type = 'social-product';

        $digital_video_sample_file = '';
        $digital_video_file = '';
        $digital_image_sample_file = '';
        $digital_image_file = '';
        $digital_sample_file = '';
        $digital_file_file = '';
        $digital_sample_file_original_name = '';
        $digital_sample_file_extension = '';
        $digital_file_original_name = '';
        $digital_file_extension = '';

        $digital_image_sample_file_2 = '';
        $digital_image_sample_file_3 = '';
        $digital_image_sample_file_4 = '';
        $digital_image_sample_file_5 = '';
        $digital_file_cover_image = '';

        $product_image1 = '';

        if ($product_image_1_data != '') {
            $product_image_1_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_1_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath1;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_1_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image1 = $newFileName;

                $fileArray = [
                    'community_id' => $upload_community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image1,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $upload_type,
                    'type_id' => $upload_type_id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image1 = '';
            }
        }

        /*if (request()->hasFile('product_image1'))
        {
            $product_image1 = request()->file('product_image1');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt1 = $product_image1->getClientOriginalExtension();
            $file_original_ext = $fileExt1;
            $file_original_name =$product_image1->getClientOriginalName();
            $file_original_size=$product_image1->getSize();

            if(checkAvailableSpace($upload_community_id,$file_original_size)!=0){
                $fileName1 = md5($product_image1->getClientOriginalName() . time()) . '.' . strtolower($fileExt1);
                $product_image1_path = $filePath ."/". $fileName1;
                $product_image1->move(public_path() . '/' . $filePath, $fileName1);
                $uploadPath1 = $filePath.'/'.$fileName1;
                $newFileName1 = $CDNRepository->upload(public_path() . '/' . $uploadPath1, $uploadPath1);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image1_path);
                $product_image1 = $newFileName1;
                $fileArray=[
                    'community_id'	=>	$upload_community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image1,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $upload_type,
                    'type_id'       =>  $upload_type_id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image1="";
            }
        }*/

        $product_image2 = '';

        if ($product_image_2_data != '') {
            $product_image_2_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_2_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath1;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_2_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image2 = $newFileName;

                $fileArray = [
                    'community_id' => $upload_community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image2,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $upload_type,
                    'type_id' => $upload_type_id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image2 = '';
            }
        }

        /*if (request()->hasFile('product_image2'))
        {
            $product_image2 = request()->file('product_image2');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt2 = $product_image2->getClientOriginalExtension();
               $file_original_ext = $fileExt2;
            $file_original_name = $product_image2->getClientOriginalName();
            $file_original_size = $product_image2->getSize();

            if(checkAvailableSpace($upload_community_id,$file_original_size)!=0){
                $fileName2 = md5($product_image2->getClientOriginalName() . time()) . '.' . strtolower($fileExt2);
                $product_image2_path = $filePath ."/". $fileName2;
                $product_image2->move(public_path() . '/' . $filePath, $fileName2);
                $uploadPath2 = $filePath.'/'.$fileName2;
                $newFileName2 = $CDNRepository->upload(public_path() . '/' . $uploadPath2, $uploadPath2);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image2_path);
                $product_image2 = $newFileName2;
                $fileArray=[
                    'community_id'	=>	$upload_community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image2,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $upload_type,
                    'type_id'       =>  $upload_type_id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image2="";
            }
        }*/

        $product_image3 = '';

        if ($product_image_3_data != '') {
            $product_image_3_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $product_image_3_data));
            $img_name = Str::random(32).'.jpg';
            $img_url = $filePath1;
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $product_image_3_data);

            $file_original_ext = 'jpg';
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;
            $img = ltrim($img, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');
            if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $product_image3 = $newFileName;

                $fileArray = [
                    'community_id' => $upload_community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $product_image3,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => $upload_type,
                    'type_id' => $upload_type_id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $product_image3 = '';
            }
        }

        /*if (request()->hasFile('product_image3'))
        {
            $product_image3 = request()->file('product_image3');
            $this->file->makeDirectory(public_path() . '/' . $filePath, 0777, TRUE, TRUE);
            $fileExt3 = $product_image3->getClientOriginalExtension();
            $file_original_ext = $fileExt3;
            $file_original_name = $product_image3->getClientOriginalName();
            $file_original_size = $product_image3->getSize();

            if(checkAvailableSpace($upload_community_id,$file_original_size)!=0){
                $fileName3 = md5($product_image3->getClientOriginalName() . time()) . '.' . strtolower($fileExt3);
                $product_image3_path = $filePath ."/" .$fileName3;
                $product_image3->move(public_path() . '/' . $filePath, $fileName3);
                $uploadPath3 = $filePath.'/'.$fileName3;
                $newFileName3 = $CDNRepository->upload(public_path() . '/' . $uploadPath3, $uploadPath3);
                $CDNRepository->deleteThisFile(public_path() . '/' . $product_image3_path);
                $product_image3 = $newFileName3;
                $fileArray=[
                    'community_id'	=>	$upload_community_id,
                    'user_id'		=>	\Auth::user()->id,
                    'file_path'		=>	$product_image3,
                    'file_name'		=>	$file_original_name,
                    'file_type'		=>	$file_original_ext,
                    'file_size'		=>	$file_original_size,
                    'uploaded_date'	=>	date("Y-m-d"),
                    'type'          =>  $upload_type,
                    'type_id'       =>  $upload_type_id,
                    'upload_key'    =>  $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }else{
                $product_image3="";
            }
        }*/

        $product_type = $product->product_type;
        $digital_product_type = $product->digital_type;

        if ($product_type == 2) {
            if ($digital_product_type == 1) {
                $digital_video_sample_file = request()->file('digital_video_sample_file');
                if ($digital_video_sample_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_video_sample_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_video_sample_file->getClientOriginalName();
                    $file_original_size = $digital_video_sample_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_video_sample_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_video_sample_file_path = $filePath.'/'.$fileName3;
                        $digital_video_sample_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $videoUploadPath = 'media/appvideo/'.$userid.'/products'.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $videoUploadPath, 'videoUpload');
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_video_sample_file_path);
                        $digital_video_sample_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_video_sample_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_video_sample_file = '';
                    }
                }

                $digital_video_file = request()->file('digital_video_file');
                if ($digital_video_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_video_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_video_file->getClientOriginalName();
                    $file_original_size = $digital_video_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_video_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_video_file_path = $filePath.'/'.$fileName3;
                        $digital_video_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $videoUploadPath = 'media/appvideo/'.$userid.'/products'.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $videoUploadPath, 'videoUpload');
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_video_file_path);
                        $digital_video_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_video_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_video_file = '';
                    }
                }
            } elseif ($digital_product_type == 2) {
                $digital_image_sample_file = request()->file('digital_image_sample_file');
                if ($digital_image_sample_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_path);
                        $digital_image_sample_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file = '';
                    }
                }

                $digital_image_sample_file_2 = request()->file('digital_image_sample_file_2');
                if ($digital_image_sample_file_2) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_2->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_2->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_2->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_2->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_2_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_2->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_2_path);
                        $digital_image_sample_file_2 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_2,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_2 = '';
                    }
                }

                $digital_image_sample_file_3 = request()->file('digital_image_sample_file_3');
                if ($digital_image_sample_file_3) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_3->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_3->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_3->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_3->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_3_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_3->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_3_path);
                        $digital_image_sample_file_3 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_3,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_3 = '';
                    }
                }

                $digital_image_sample_file_4 = request()->file('digital_image_sample_file_4');
                if ($digital_image_sample_file_4) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_4->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_4->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_4->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_4->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_4_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_4->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_4_path);
                        $digital_image_sample_file_4 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_4,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_4 = '';
                    }
                }

                $digital_image_sample_file_5 = request()->file('digital_image_sample_file_5');
                if ($digital_image_sample_file_5) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_sample_file_5->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_sample_file_5->getClientOriginalName();
                    $file_original_size = $digital_image_sample_file_5->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_sample_file_5->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_sample_file_5_path = $filePath.'/'.$fileName3;
                        $digital_image_sample_file_5->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_sample_file_5_path);
                        $digital_image_sample_file_5 = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_sample_file_5,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_sample_file_5 = '';
                    }
                }

                $digital_image_file = request()->file('digital_image_file');
                if ($digital_image_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_image_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_image_file->getClientOriginalName();
                    $file_original_size = $digital_image_file->getSize();

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_image_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_image_file_path = $filePath.'/'.$fileName3;
                        $digital_image_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_image_file_path);
                        $digital_image_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_image_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_image_file = '';
                    }
                }
            } elseif ($digital_product_type == 3) {

                $digital_file_cover_image = request()->file('digital_file_cover_image');
                if ($digital_file_cover_image) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_file_cover_image->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_file_cover_image->getClientOriginalName();
                    $file_original_size = $digital_file_cover_image->getSize();

                    $digital_file_cover_image_original_name = $file_original_name;
                    $digital_file_cover_image_extension = $fileExt3;

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_file_cover_image->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_file_cover_image_path = $filePath.'/'.$fileName3;
                        $digital_file_cover_image->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_file_cover_image_path);
                        $digital_file_cover_image = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_file_cover_image,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_file_cover_image = '';
                    }
                }

                $digital_sample_file = request()->file('digital_sample_file');
                if ($digital_sample_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_sample_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_sample_file->getClientOriginalName();
                    $file_original_size = $digital_sample_file->getSize();

                    $digital_sample_file_original_name = $file_original_name;
                    $digital_sample_file_extension = $fileExt3;

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_sample_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_sample_file_path = $filePath.'/'.$fileName3;
                        $digital_sample_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_sample_file_path);
                        $digital_sample_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_sample_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_sample_file = '';
                    }
                }

                $digital_file_file = request()->file('digital_file');
                if ($digital_file_file) {
                    $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                    $fileExt3 = $digital_file_file->getClientOriginalExtension();
                    $file_original_ext = $fileExt3;
                    $file_original_name = $digital_file_file->getClientOriginalName();
                    $file_original_size = $digital_file_file->getSize();

                    $digital_file_original_name = $file_original_name;
                    $digital_file_extension = $fileExt3;

                    if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                        $fileName3 = md5($digital_file_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                        $digital_file_file_path = $filePath.'/'.$fileName3;
                        $digital_file_file->move(public_path().'/'.$filePath, $fileName3);
                        $uploadPath3 = $filePath.'/'.$fileName3;
                        $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $uploadPath3);
                        $CDNRepository->deleteThisFile(public_path().'/'.$digital_file_file_path);
                        $digital_file_file = $newFileName3;
                        $fileArray = [
                            'community_id' => $upload_community_id,
                            'user_id' => \Auth::user()->id,
                            'file_path' => $digital_file_file,
                            'file_name' => $file_original_name,
                            'file_type' => $file_original_ext,
                            'file_size' => $file_original_size,
                            'uploaded_date' => date('Y-m-d'),
                            'type' => $upload_type,
                            'type_id' => $upload_type_id,
                            'upload_key' => $upload_key,
                        ];
                        $this->communitySpaceUsedRepository->save($fileArray);
                    } else {
                        $digital_file_file = '';
                    }
                }
            }
        }

        $course_video_preview_file = '';

        if ($product_type == 3) {
            $course_video_preview_file = request()->file('course_video_preview_file');
            if ($course_video_preview_file) {
                $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
                $fileExt3 = $course_video_preview_file->getClientOriginalExtension();
                $file_original_ext = $fileExt3;
                $file_original_name = $course_video_preview_file->getClientOriginalName();
                $file_original_size = $course_video_preview_file->getSize();

                if (checkAvailableSpace($upload_community_id, $file_original_size) != 0) {
                    $fileName3 = md5($course_video_preview_file->getClientOriginalName().time()).'.'.strtolower($fileExt3);
                    $digital_video_sample_file_path = $filePath.'/'.$fileName3;
                    $course_video_preview_file->move(public_path().'/'.$filePath, $fileName3);
                    $uploadPath3 = $filePath.'/'.$fileName3;
                    $videoUploadPath = 'media/appvideo/'.$userid.'/products'.'/'.$fileName3;
                    $newFileName3 = $CDNRepository->upload(public_path().'/'.$uploadPath3, $videoUploadPath, 'videoUpload');
                    $CDNRepository->deleteThisFile(public_path().'/'.$digital_video_sample_file_path);
                    $course_video_preview_file = $newFileName3;
                    $fileArray = [
                        'community_id' => $upload_community_id,
                        'user_id' => \Auth::user()->id,
                        'file_path' => $course_video_preview_file,
                        'file_name' => $file_original_name,
                        'file_type' => $file_original_ext,
                        'file_size' => $file_original_size,
                        'uploaded_date' => date('Y-m-d'),
                        'type' => $upload_type,
                        'type_id' => $upload_type_id,
                        'upload_key' => $upload_key,
                    ];
                    $this->communitySpaceUsedRepository->save($fileArray);
                } else {
                    $course_video_preview_file = '';
                }
            }
        }

        if ($product_type == 3) {
            if ($course_video_preview_file) {
                $product->course_preview_video = $course_video_preview_file;
            }
            $product->course_what_you_will_learn = $course_what_you_will_learn;
            $product->course_related_topics = $course_related_topics;
            $product->course_requirements = $course_requirements;
            $product->course_description = $course_description;
            $product->who_this_course_is_for = $who_this_course_is_for;
        }

        $product->product_name = sanitizeText($product_name);
        $product->quantity_available = $quantity_available;
        $product->price = $price;
        $product->tax_applicable = $tax_applicable;
        $product->currency = $currency;
        $product->product_description = $product_description;
        $product->discount = $discount;
        $product->is_discounted = $is_discounted;
        $product->item_number = $item_number;
        $product->business_id = $business_id;
        $product->subscription_min_cycle = $subscription_min_cycle;
        if (is_array($val) && array_key_exists('is_product_physical', $val)) {
            $product->is_product_physical = (int) $val['is_product_physical'];
        }

        if ($product_type == 0) {
            $product->shipping_cost = $shipping_cost;
            $product->shipping_cost_2 = $shipping_cost_2;
            $product->shipping_cost_3 = $shipping_cost_3;
            $product->shipping_cost_4 = $shipping_cost_4;
            $product->shipping_cost_5 = $shipping_cost_5;

            if ($shipping_cost == '' and $shipping_cost_2 = '' and $shipping_cost_3 == '' and $shipping_cost_4 == '' and $shipping_cost_5 == '') {
                $product->is_free_shipping = 1;
            } else {
                $product->is_free_shipping = 0;
            }

            $product->free_area = $free_area;
        } else {
            $product->recurring_order = $recurring_order;
            $product->recurring_shipping_cost = $recurring_shipping_cost;
        }

        if ($product_image1 != '') {
            $product->image1 = $product_image1;
        }

        if ($product_image2 != '') {
            $product->image2 = $product_image2;
        }

        if ($product_image3 != '') {
            $product->image3 = $product_image3;
        }

        if ($digital_video_sample_file != '') {
            $product->digital_video_sample_file = $digital_video_sample_file;
        }

        if ($digital_video_file != '') {
            $product->digital_video_file = $digital_video_file;
        }

        if ($digital_image_sample_file != '') {
            $product->digital_image_sample_file = $digital_image_sample_file;
        }

        if ($digital_image_sample_file_2 != '') {
            $product->digital_image_sample_file1 = $digital_image_sample_file_2;
        }

        if ($digital_image_sample_file_3 != '') {
            $product->digital_image_sample_file2 = $digital_image_sample_file_3;
        }

        if ($digital_image_sample_file_4 != '') {
            $product->digital_image_sample_file3 = $digital_image_sample_file_4;
        }

        if ($digital_image_sample_file_5 != '') {
            $product->digital_image_sample_file4 = $digital_image_sample_file_5;
        }

        if ($digital_image_file != '') {
            $product->digital_image_file = $digital_image_file;
        }

        if ($digital_file_cover_image != '') {
            $product->digital_file_sample_cover = $digital_file_cover_image;
        }

        if ($digital_sample_file != '') {
            $product->digital_file_sample_file = $digital_sample_file;
        }

        if ($digital_file_file != '') {
            $product->digital_file_file = $digital_file_file;
        }

        $product->save();

        if ($product) {
            $this->communitySpaceUsedRepository->updateId($upload_key, $product->id);
        }

        return $product;
    }

    public function getByBusinessCategoryId($business_id, $category_id)
    {
        return $this->model
            ->where('business_id', $business_id)
            ->where('category_id', $category_id)
			
			->where('status', 1)
			->where('product_name', '<>', '')
			->where('category_id', '>', 0)
			->where('item_number', '<>', '')
			->where('quantity_available', '>', 0)
			->where('price', '>', 0)
			->where(function ($q) {
				$q->where('is_discounted', 0)
				  ->orWhere(function ($q) {
					  $q->where('is_discounted', 1)
						->where('discount', '>', 0);
				  });
			})
			->where('length', '>', 0)
			->where('width', '>', 0)
			->where('height', '>', 0)
			->where('weight', '>', 0)
			->where('shipping_cost', '>', 0)
			->where('shipping_cost_2', '>', 0)
			->where('shipping_cost_3', '>', 0)
			->orderBy('sold_quantiry', 'desc')
			
            ->get();
    }

    public function getByBusinessIdQuanitity($business_id)
    {
        return $this->model->where('business_id', $business_id)->where('status', 1)->orderBy('sold_quantiry', 'desc')->get();
    }
	
	public function getByBusinessIdQuanitityPr($business_id)
    {
        return $this->model->where('business_id', $business_id)->where('status', 1)->orderBy('sold_quantiry', 'desc')->get();
    }

    public function getByBusinessIdPaginated($business_id, $offset = 0, $limit = 8)
    {
        $business_id = (int) $business_id;
        $offset = (int) $offset;
        $limit = (int) $limit;
        $version = (int) Cache::get('business_products_cache_version_' . $business_id, 1);
        $cacheKey = 'business_products_paginated_' . $business_id . '_v' . $version . '_offset_' . $offset . '_limit_' . $limit;
        
		if (\Auth::check()){
			$userid = \Auth::user()->id;
			$store=$this->pageRepository->getById($business_id);
			if($store and $store->user_id==$userid){
				//return Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id, $offset, $limit) {
					return $this->model
						->where('business_id', $business_id)
						->where('status', 1)
						->where('product_name', '<>', '')
						->where('category_id', '>', 0)
						->where('item_number', '<>', '')
						->where('quantity_available', '>', 0)
						->where('price', '>', 0)
						->where(function ($q) {
							$q->where('is_discounted', 0)
							  ->orWhere(function ($q) {
								  $q->where('is_discounted', 1)
									->where('discount', '>', 0);
							  });
						})
						->where('length', '>', 0)
						->where('width', '>', 0)
						->where('height', '>', 0)
						->where('weight', '>', 0)
						->where('shipping_cost', '>', 0)
						->where('shipping_cost_2', '>', 0)
						->where('shipping_cost_3', '>', 0)
						->orderBy('sold_quantiry', 'desc')
						->offset($offset)
						->limit($limit)
						->get();
				//});
			}else{
				return Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id, $offset, $limit) {
					return $this->model
						->where('business_id', $business_id)
						->where('status', 1)
						->where('product_name', '<>', '')
						->where('category_id', '>', 0)
						->where('item_number', '<>', '')
						->where('quantity_available', '>', 0)
						->where('price', '>', 0)
						->where(function ($q) {
							$q->where('is_discounted', 0)
							  ->orWhere(function ($q) {
								  $q->where('is_discounted', 1)
									->where('discount', '>', 0);
							  });
						})
						->where('length', '>', 0)
						->where('width', '>', 0)
						->where('height', '>', 0)
						->where('weight', '>', 0)
						->where('shipping_cost', '>', 0)
						->where('shipping_cost_2', '>', 0)
						->where('shipping_cost_3', '>', 0)
						->orderBy('sold_quantiry', 'desc')
						->offset($offset)
						->limit($limit)
						->get();
				});
			}	
		}else{
			return Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id, $offset, $limit) {
				return $this->model
					->where('business_id', $business_id)
					->where('status', 1)
					->where('product_name', '<>', '')
					->where('category_id', '>', 0)
					->where('item_number', '<>', '')
					->where('quantity_available', '>', 0)
					->where('price', '>', 0)
					->where(function ($q) {
						$q->where('is_discounted', 0)
						  ->orWhere(function ($q) {
							  $q->where('is_discounted', 1)
								->where('discount', '>', 0);
						  });
					})
					->where('length', '>', 0)
					->where('width', '>', 0)
					->where('height', '>', 0)
					->where('weight', '>', 0)
					->where('shipping_cost', '>', 0)
					->where('shipping_cost_2', '>', 0)
					->where('shipping_cost_3', '>', 0)
					->orderBy('sold_quantiry', 'desc')
					->offset($offset)
					->limit($limit)
					->get();
			});
		}	
    }

    public function getTotalProductsCount($business_id)
    {
		$business_id = (int) $business_id;
		$version = (int) Cache::get('business_products_cache_version_' . $business_id, 1);
		$cacheKey = 'business_products_total_' . $business_id . '_v' . $version;
        
		if (\Auth::check()){
			$userid = \Auth::user()->id;
			$store=$this->pageRepository->getById($business_id);
			//if($store and $store->user_id==$userid){
				//return Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id) {
				//	return $this->model->where('business_id', $business_id)->where('status', 1)->count();
				//});
			//}else{
				return Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id) {
					return $this->model->where('business_id', $business_id)
					->where('status', 1)
					->where('product_name', '<>', '')
					->where('category_id', '>', 0)
					->where('item_number', '<>', '')
					->where('quantity_available', '>', 0)
					->where('price', '>', 0)
					->where(function ($q) {
						$q->where('is_discounted', 0)
						  ->orWhere(function ($q) {
							  $q->where('is_discounted', 1)
								->where('discount', '>', 0);
						  });
					})
					->where('length', '>', 0)
					->where('width', '>', 0)
					->where('height', '>', 0)
					->where('weight', '>', 0)
					->where('shipping_cost', '>', 0)
					->where('shipping_cost_2', '>', 0)
					->where('shipping_cost_3', '>', 0)
				->count();
				});
			//}
		}else{
			return Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id) {
				return $this->model->where('business_id', $business_id)->where('status', 1)
				->where('product_name', '<>', '')
				->where('category_id', '>', 0)
				->where('item_number', '<>', '')
				->where('quantity_available', '>', 0)
				->where('price', '>', 0)
				->where(function ($q) {
					$q->where('is_discounted', 0)
					  ->orWhere(function ($q) {
						  $q->where('is_discounted', 1)
							->where('discount', '>', 0);
					  });
				})
				->where('length', '>', 0)
				->where('width', '>', 0)
				->where('height', '>', 0)
				->where('weight', '>', 0)
				->where('shipping_cost', '>', 0)
				->where('shipping_cost_2', '>', 0)
				->where('shipping_cost_3', '>', 0)
				->count();
			});
		}	
    }

    public function getAllProductsLimited($business_id, $limit = 5)
    {
		if (\Auth::check()){
			$userid = \Auth::user()->id;
			$business_id = (int) $business_id;
			$limit = (int) $limit;
			$version = (int) Cache::get('business_products_cache_version_' . $business_id, 1);
			$cacheKey = 'business_products_limited_' . $business_id . '_v' . $version . '_limit_' . $limit;
			
			$store=$this->pageRepository->getById($business_id);
			if($store and $store->user_id==$userid){
				return \Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id, $limit) {
					return $this->model->where('business_id', $business_id)
						->where('status', 1)->orderBy('sold_quantiry', 'desc')
						->paginate($limit);
				});
			}else{
				//return \Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id, $limit) {
					return $this->model->where('business_id', $business_id)
						//->where('has_confirmed_for_sale', 1)
						->where('status', 1)
						->where('product_name', '<>', '')
						->where('category_id', '>', 0)
						->where('item_number', '<>', '')
						->where('quantity_available', '>', 0)
						->where('price', '>', 0)
						->where(function ($q) {
							$q->where('is_discounted', 0)
							  ->orWhere(function ($q) {
								  $q->where('is_discounted', 1)
									->where('discount', '>', 0);
							  });
						})
						->where('length', '>', 0)
						->where('width', '>', 0)
						->where('height', '>', 0)
						->where('weight', '>', 0)
						->where('shipping_cost', '>', 0)
						->where('shipping_cost_2', '>', 0)
						->where('shipping_cost_3', '>', 0)
						->orderBy('sold_quantiry', 'desc')
						->paginate($limit);
				//});
			}									
		}else{
			$business_id = (int) $business_id;
			$limit = (int) $limit;
			$version = (int) Cache::get('business_products_cache_version_' . $business_id, 1);
			$cacheKey = 'business_products_limited_' . $business_id . '_v' . $version . '_limit_' . $limit;
			
			//return \Cache::remember($cacheKey, now()->addMonth(), function () use ($business_id, $limit) {
				return $this->model
					//->where('has_confirmed_for_sale', 1)
					->where('business_id', $business_id)
					->where('status', 1)
					->where('product_name', '<>', '')
					->where('category_id', '>', 0)
					->where('item_number', '<>', '')
					->where('quantity_available', '>', 0)
					->where('price', '>', 0)
					->where(function ($q) {
						$q->where('is_discounted', 0)
						  ->orWhere(function ($q) {
							  $q->where('is_discounted', 1)
								->where('discount', '>', 0);
						  });
					})
					->where('length', '>', 0)
					->where('width', '>', 0)
					->where('height', '>', 0)
					->where('weight', '>', 0)
					->where('shipping_cost', '>', 0)
					->where('shipping_cost_2', '>', 0)
					->where('shipping_cost_3', '>', 0)
					->orderBy('sold_quantiry', 'desc')
					->paginate($limit);
			//});
		}	
    }

    public function searchProducts($term, $business_id)
    {
        $products = $this->model
            ->where('business_id', $business_id)
            ->where('status', 1);

        $products = $products->where(function ($product) use ($term) {
            $product->where('product_name', 'LIKE', '%'.$term.'%')
                ->orWhere('product_description', 'LIKE', '%'.$term.'%');
        });
		
		if (\Auth::check()){
			$userid = \Auth::user()->id;
			$store=$this->pageRepository->getById($business_id);
			if($store and $store->user_id!=$userid){
				$products = $products->where('status', 1)
				->where('product_name', '<>', '')
				->where('category_id', '>', 0)
				->where('item_number', '<>', '')
				->where('quantity_available', '>', 0)
				->where('price', '>', 0)
				->where(function ($q) {
					$q->where('is_discounted', 0)
					  ->orWhere(function ($q) {
						  $q->where('is_discounted', 1)
							->where('discount', '>', 0);
					  });
				})
				->where('length', '>', 0)
				->where('width', '>', 0)
				->where('height', '>', 0)
				->where('weight', '>', 0)
				->where('shipping_cost', '>', 0)
				->where('shipping_cost_2', '>', 0)
				->where('shipping_cost_3', '>', 0);
			}
		}else{
			$products = $products->where('status', 1)
			->where('product_name', '<>', '')
			->where('category_id', '>', 0)
			->where('item_number', '<>', '')
			->where('quantity_available', '>', 0)
			->where('price', '>', 0)
			->where(function ($q) {
				$q->where('is_discounted', 0)
				  ->orWhere(function ($q) {
					  $q->where('is_discounted', 1)
						->where('discount', '>', 0);
				  });
			})
			->where('length', '>', 0)
			->where('width', '>', 0)
			->where('height', '>', 0)
			->where('weight', '>', 0)
			->where('shipping_cost', '>', 0)
			->where('shipping_cost_2', '>', 0)
			->where('shipping_cost_3', '>', 0);
		}
		
		
        $products = $products->orderBy('sold_quantiry', 'desc')->get();


        return $products;
    }

    public function productsByCommunityId($community_id)
    {
        $products = $this->model;

        $inactiveBusiness = $this->pageRepository->getInactiveBusinessIds($community_id);
        $products = $products->whereNotIn('business_id', $inactiveBusiness);

        if ($community_id != id4MartCommunityId()) {
            $products = $products->where('community_id', $community_id);
        }

        $products = $products->where('status', 1)->count();

        return $products;
    }

    public function getByCommunity($community_id, $term = null)
    {
        $products = $this->model;

        $inactiveBusiness = $this->pageRepository->getInactiveBusinessIds($community_id);
        $products = $products->whereNotIn('business_id', $inactiveBusiness);

        if ($community_id != id4MartCommunityId()) {
            $products = $products->where('community_id', $community_id);
        }

        if ($term) {
            $products = $products->where(function ($product) use ($term) {
                $product->where('product_name', 'LIKE', '%'.$term.'%')
                    ->orWhere('product_description', 'LIKE', '%'.$term.'%');
            });
        }

        $products = $products->where('status', 1)->orderBy('id', 'desc')->paginate(13);

        return $products;
    }

    public function getPopularProductsAll($community_id)
    {
        $products = $this->model;

        $inactiveBusiness = $this->pageRepository->getInactiveBusinessIds($community_id);
        $products = $products->whereNotIn('business_id', $inactiveBusiness);

        if ($community_id != id4MartCommunityId()) {
            $products = $products->where('community_id', $community_id)->where('is_popular', '=', 1);
        } else {
            $products = $products->where('global_popular', '=', 1);
        }

        $products = $products->where('status', 1)->orderBy('id', 'desc')->get();

        return $products;
    }

    public function getPopularProducts($community_id, $offset = 0)
    {
        $products = $this->model;

        $inactiveBusiness = $this->pageRepository->getInactiveBusinessIds($community_id);
        $products = $products->whereNotIn('business_id', $inactiveBusiness);

        if ($community_id != id4MartCommunityId()) {
            $products = $products->where('community_id', $community_id)->where('is_popular', '=', 1);
        } else {
            $products = $products->where('global_popular', '=', 1);
        }

        $products = $products->where('status', 1)
            ->orderBy('id','desc')
            ->skip($offset)
            ->take(9)->get();

        return $products;
    }

    public function getDraftProducts($user_id)
    {
        return $this->model
            ->where('user_id','=',$user_id)
            ->where('is_draft','=',1)
            ->orderBy('id', 'desc')
            ->paginate(10);
    }
	
	public function addChamberProduct($page_id,$community_id,$userid,$title,$price,$desc,$product_image1)
	{
		$product = $this->model->newInstance();
        $product->user_id = $userid;
        $product->community_id = $community_id;
        $product->business_id = $page_id;
        $product->product_name = sanitizeText($title);
		$product->quantity_available = 100;
		$product->price = $price;
		$product->product_description = $desc;
		$product->discount = 0;
		$product->image1 = $product_image1;
		$product->status = 1;
		$product->product_type = 0;
		$product->digital_type = 0;
		$product->product_id=generateUUID();
		$product->save();
	}
	
	public function setPrId()
	{
		$products=$this->model
            ->where('product_id','=',NULL)
            ->get();
			
		foreach($products as $product){
			$product->product_id=generateUUID();
			$product->save();
		}		
	}
	
	public function getProductByProductId($product_id)
	{
        $product = $this->model->where('status', 1)->where('product_id','=',$product_id)->first();
		return $product;
	}
}