<?php

namespace App\Repositories;
use Illuminate\Support\Str;
use Illuminate\Mail\Mailer;
use App\Models\Page;
use Illuminate\Events\Dispatcher;
use Illuminate\Http\Request;

class PageRepository
{
    public function __construct(Page $page,
        PhotoRepository $photoRepository,
        LikeRepository $likeRepository,
        MustAvoidUserRepository $mustAvoidUserRepository,
        PhotoAlbumRepository $photoAlbumRepository,
        CommunityRepository $communityRepository,
        CommunitySpaceUsedRepository $communitySpaceUsedRepository,
        Dispatcher $event,
        Request $request,
		Mailer $mailer
    ) {
        $this->model = $page;
		$this->mailer = $mailer;
        $this->photoRepository = $photoRepository;
        $this->likeRepository = $likeRepository;
        $this->mustAvoidUserRepository = $mustAvoidUserRepository;
        $this->photoAlbum = $photoAlbumRepository;
        $this->communityRepository = $communityRepository;
        $this->communitySpaceUsedRepository = $communitySpaceUsedRepository;
        $this->event = $event;
        $this->request = $request;
    }

    /**
     * Create page
     *
     * @param  array  $val
     * @return \App\Models\Page
     */
    public function create($val, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'title' => '',
            'description' => '',
            'website' => '',
            'url' => '',
            'category' => '',
            'email' => '',
            'contact' => '',
            'country' => '',
            'state' => '',
            'city' => '',
            'street' => '',
            'zip' => '',
            'container_color' => '',
            'container_transparancy' => '',
            'community_id' => '',
            'subcategory'=>'',
            'page_type' => 0,
            'status' => 1,
            'full_address' => '',
            'latitude' => '',
            'longitude' => '',
        ];

        /**
         * @var $title
         * @var $description
         * @var $website
         * @var $category
         * @var $url
         */
        extract(array_merge($expected, $val));

        $currency = 'USD';
        $community = $this->communityRepository->getById($community_id);
        if ($community and $community->currency != '') {
            $currency = $community->currency;
        }

		$url=$this->generateSlug($title);
		 
        // if (!empty($title) and !empty($category)) {
        $page = $this->model->newInstance();
        $page->title = sanitizeText($title, 130);
        $page->slug = sanitizeText($url);
        $page->user_id = $userid;
        $page->description = $description;
        $page->category_id = sanitizeText($category);
        $page->subcategory_id = sanitizeText($subcategory);
        $page->website = sanitizeText($website);
        $page->business_email = sanitizeText($email);
        $page->business_contact = sanitizeText($contact);
        $page->country = sanitizeText($country);
        $page->state = sanitizeText($state);
        $page->city = sanitizeText($city);
        $page->street = sanitizeText($street);
        $page->zip = sanitizeText($zip);
        $page->container_color = sanitizeText($container_color);
        $page->container_transparancy = sanitizeText($container_transparancy);
        $page->community_id = $community_id;
        $page->page_type = $page_type;
        $page->status = $status;
        $page->full_address = $full_address;
        $page->latitude = $latitude;
        $page->longitude = $longitude;
        $page->currency = $currency;
		$page->theme = 3;

		$page->product_note1="24-hour fast shipping";
		$page->product_note2="Unused/Unopened Returns";
		$page->product_note3="24/7 live customer support";
		$page->product_note4="Secure SSL Payments";
		
        $page->save();

		$user=$page->user;
		
		try {
			$this->mailer->send('emails.auth.store-create', [
				'page_id' => $page->id,
				'fullname'=>$user->fullname,
				'page_url'=>$page->present()->businessUrl(),
			 ], function ($mail) use ($page,$user) {
				$mail->to($user->email_address, $user->fullname)
					->subject('Congratulations! You have successfully created your New Store');
			});
		} catch (\Exception $e) {
			\Log::error('Mail send failed: ' . $e->getMessage(), [
				//'user_id' => $user->id,
				//'email'   => $user->email_address,
				'trace'   => $e->getTraceAsString(),
			]);
		}

        $this->event->dispatch('page.add', [$page]);

        return $page;
        // }

        // return false;
    }

    public function saveDesign($container_transparancy, $container_color, $theme, $page)
    {
        $page->container_color = sanitizeText($container_color);
        $page->container_transparancy = sanitizeText($container_transparancy);
        $page->theme = $theme;
        $page->save();
    }

    /**
     * @return bool
     */
    public function save($val, $page)
    {
        $expected = [
            'title' => '',
            /* 'description', */
            'website' => '',
            'category' => '',
            'url' => '',
            'title' => '',
            'info' => [],
            'email' => '',
            'contact' => '',
            'country' => '',
            'state' => '',
            'city' => '',
            'street' => '',
            'zip' => '',
            'container_color' => '',
            'container_transparancy' => '',
            'show_address' => 1,
            'show_claim_btn' => 1,
            'subcategory' => '',
            'page_type' => '',
            'currency' => '',
            'tax_applicable' => '',
            'full_address' => '',
            'gift_card' => 0,
            'latitude' => '',
            'longitude' => '',
        ];

        /**
         * @var $title
         * @var $description
         * @var $website
         * @var $category
         * @var $info
         * @var $url
         */
        extract(array_merge($expected, $val));

        /* $page->description = $description; */
        $page->website = sanitizeText($website);
        $page->title = sanitizeText($title, 130);
        $page->category_id = sanitizeText($category);
        $page->subcategory_id = sanitizeText($subcategory);
        $page->info = serialize($info);
        $page->business_email = sanitizeText($email);
       // $page->business_contact = sanitizeText($contact);
        $page->country = sanitizeText($country);
        $page->state = sanitizeText($state);
        $page->city = sanitizeText($city);
        $page->street = sanitizeText($street);
        $page->zip = sanitizeText($zip);
        /*$page->container_color = sanitizeText($container_color);
        $page->container_transparancy = sanitizeText($container_transparancy);*/

        $page->show_address = $show_address;
        $page->show_claim_btn = $show_claim_btn;
        $page->page_type = $page_type;
        // $page->currency = $currency;
       // $page->product_tax = $tax_applicable;
        $page->full_address = $full_address;
        $page->gift_card = $gift_card;
        $page->latitude = $latitude;
        $page->longitude = $longitude;
        $page->save();

        return true;
    }
	
	public function saveTax($val, $page)
    {
        $expected = [
            'product_tax_name' => '',
            'product_tax' => '',
            'product_tax_name_1' => '',
            'product_tax_1' => '',
            'product_tax_name_2' => '',
            'product_tax_2' => '',
            'shipping_carrier' => 'usps',
        ];
		
        extract(array_merge($expected, $val));

        $shipping_carrier = in_array($shipping_carrier, ['usps', 'canada_post'], true) ? $shipping_carrier : 'usps';
       
        $page->product_tax_name = $product_tax_name;
		$page->product_tax = $product_tax;
		$page->product_tax_name_1 = $product_tax_name_1;
		$page->product_tax_1 = $product_tax_1;
		$page->product_tax_name_2 = $product_tax_name_2;
		$page->product_tax_2 = $product_tax_2;

        // Shipping carrier settings (no migration required; only set if columns exist)
        if (class_exists('Schema') && \Schema::hasColumn('pages', 'shipping_carrier')) {
            $page->shipping_carrier = $shipping_carrier;
        }
        if (class_exists('Schema') && \Schema::hasColumn('pages', 'shipping_usps_enabled')) {
            $page->shipping_usps_enabled = ($shipping_carrier === 'usps') ? 1 : 0;
        }
        if (class_exists('Schema') && \Schema::hasColumn('pages', 'shipping_canada_post_enabled')) {
            $page->shipping_canada_post_enabled = ($shipping_carrier === 'canada_post') ? 1 : 0;
        }

        $page->save();

        return true;
    }

    public function saveTaxDetails($val, $page)
    {
        $expected = [
            'business_number_file' => '',
            'business_tax_number' => '',
            'business_registration_date' => '',
            'business_registration_city_name' => '',
			'business_name'=>'',
        ];

        extract(array_merge($expected, $val));

        // Only set fields if columns exist (some installs may differ)
        if (!class_exists('Schema') || \Schema::hasColumn('pages', 'business_number_file')) {
            $page->business_number_file = $business_number_file;
        }
        if (!class_exists('Schema') || \Schema::hasColumn('pages', 'business_tax_number')) {
            $page->business_tax_number = sanitizeText($business_tax_number);
        }
        if (!class_exists('Schema') || \Schema::hasColumn('pages', 'business_registration_date')) {
            $page->business_registration_date = sanitizeText($business_registration_date);
        }
		
		$page->business_name=$business_name;

        // Column name in this project DB is `business_registraton_city_name` (note: misspelt)
        $page->business_registraton_city_name = sanitizeText($business_registration_city_name);

        $page->save();
        return true;
    }

    public function saveDescription($val, $page)
    {
        $expected = [
            'description',
            'community_gallery_logo1_path' => '',
            'community_gallery_logo2_path' => '',
        ];

        $community_id = $page->community_id;

        extract(array_merge($expected, $val));

        $CDNRepository = app('App\\Repositories\\CDNRepository');

        $data = $community_gallery_logo1_path;
        $img = '';

        $upload_key = Str::random(20);
        $type = 'business-gallery';

        if ($data != '') {
            $fileData = $data;

            $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
            $img_name = Str::random(32).'.jpg';
            $img_url = '/uploads/community/'.$community_id.'/banner';
            if (! is_dir(public_path('').$img_url)) {
                mkdir(public_path('').$img_url, 0777, true);
            }
            file_put_contents(public_path('/').$img_url.'/'.$img_name, $data);

            $file_original_ext = explode(';', explode('/', $fileData)[1])[0];
            $file_original_name = $img_name;
            $file_original_size = filesize(public_path('/').$img_url.'/'.$img_name);
            $img = $img_url.'/'.$img_name;

            /*$compress = compressImage(public_path('').$img, public_path('').$img, 70);

            if($compress)
            {*/
            $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);
                $img = $newFileName;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $img,
                    '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' => 0,
                    'sub_type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $img = '';
            }

            /* } */
        }

        $data1 = $community_gallery_logo2_path;
        $img1 = '';
        if ($data1 != '') {
            $fileData1 = $data1;

            $data1 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data1));
            $img_name1 = Str::random(32).'.jpg';
            $img_url1 = '/uploads/community/'.$community_id.'/banner';
            if (! is_dir(public_path('').$img_url1)) {
                mkdir(public_path('').$img_url1, 0777, true);
            }
            file_put_contents(public_path('/').$img_url1.'/'.$img_name1, $data1);

            $file_original_ext = explode(';', explode('/', $fileData1)[1])[0];
            $file_original_name = $img_name1;
            $file_original_size = filesize(public_path('/').$img_url1.'/'.$img_name1);

            $img1 = $img_url1.'/'.$img_name1;

            /*$compress1 = compressImage(public_path('').$img1, public_path('').$img1, 70);
            if($compress1)
            {*/
            $img1 = ltrim($img1, '/');

            $CDNRepository = app('App\\Repositories\\CDNRepository');

            if (checkAvailableSpace($page->community_id, $file_original_size) != 0) {
                $newFileName1 = $CDNRepository->upload(public_path().'/'.$img1, $img1);
                $CDNRepository->deleteThisFile(public_path().'/'.$img1);
                $img1 = $newFileName1;

                $fileArray = [
                    'community_id' => $page->community_id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $img1,
                    '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' => 0,
                    'sub_type_id' => $page->id,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            } else {
                $CDNRepository->deleteThisFile(public_path().'/'.$img1);
                $img1 = '';
            }
            /* } */
        }

        if ($img != '') {
            $page->banner_image_1 = $img;
        }

        if ($img1 != '') {
            $page->banner_image_2 = $img1;
        }

        $page->description = $description;
        $page->save();

        return true;
    }

    public function adminEdit($val, $page)
    {
        $expected = [
            'description' => '',
            'verified' => 0,
            'kyc_completed' => 0,
        ];

        /**
         * @var $description
         * @var $verified
         */
        extract(array_merge($expected, $val));

        $page->description = $description;
        $page->verified = $verified;
        $page->kyc_completed = (int) $kyc_completed;
        $page->save();

        return true;
    }

    public function exists($title)
    {
        return $this->model->where('title', '=', $title)->first();
    }

    public function get($id)
    {
        /*return $this->model->with('likes')
            // ->where('title', '=', $id)
            ->where('is_deleted', '=', 0)
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
            ->where(function ($q) use ($id) {
                $q->where('slug', '=', $id)->orWhere('id', '=', $id);
            })
            ->first();*/
			
       
		$cacheKey = 'page_get_' . md5($id . '_' . implode(',', $this->mustAvoidUserRepository->get()));
		return \Cache::remember($cacheKey, now()->addMonth(), function () use ($id) {
			return $this->model
				->where('is_deleted', '=', 0)
				->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
				->where(function ($q) use ($id) {
					$q->where('slug', '=', $id)->orWhere('id', '=', $id);
				})
				->first();
		});
    }

    public function changePhoto($image, $page, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        // $slug = 'page-'.$page->id;
        $album = $this->photoAlbum->add('pages', $user->id, true);
        if ($album) {
            $slug = 'album-'.$album->id;
        } else {
            $slug = 'page-'.$page->id;
        }

        // $image = sanitizeText($image);
        //  $image = $this->photoRepository->add($image, $user->id, $slug);

        $param = [
            'path' => 'users/'.$user->id,
            'slug' => $slug,
            'userid' => $user->id,
            'url' => true,
        ];
        $image = $this->photoRepository->upload($image, $param);
        if (! $image) {
            return false;
        }
        $this->photoRepository->deleteFilesFromLocal($image); // delete files from local

        /**
         * Now save user avatar
         */
        $page->logo = $image;
        $page->save();

        return $image;
    }

    public function changePhotoTheme2($image, $page, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $album = $this->photoAlbum->add('pages', $user->id, true);
        if ($album) {
            $slug = 'album-'.$album->id;
        } else {
            $slug = 'page-'.$page->id;
        }

        $param = [
            'path' => 'users/'.$user->id,
            'slug' => $slug,
            'userid' => $user->id,
            'url' => true,
        ];
        $image = $this->photoRepository->upload($image, $param);
        if (! $image) {
            return false;
        }
        $this->photoRepository->deleteFilesFromLocal($image); // delete files from local

        $page->theme2_logo = $image;
        $page->save();

        return $image;
    }

    public function updateCover($id, $image)
    {
        return $this->model->where('id', '=', $id)->update(['cover' => sanitizeText($image)]);
    }

    public function search($term, $limit = 10, $community_id = 0)
    {
        $page = $this->model->with('likes')
            ->where('is_deleted', '=', 0)
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get());

        if ($community_id) {
            $page = $page->where('community_id', '=', $community_id);
        }

        $page = $page->where(function ($page) use ($term) {
            $page->where('title', 'LIKE', '%'.$term.'%')
                ->orWhere('description', 'LIKE', '%'.$term.'%');
        });

        $page = $page->paginate($limit);

        return $page;
    }

    public function suggest($limit = 3)
    {
        $userid = \Auth::user()->id;
        $likes = $this->likeRepository->getLikesId('page', $userid);
        /**$connectionRepository = app('App\Repositories\\ConnectionRepository');
        $friendsId = $connectionRepository->getAllFriendConnectionIds($userid);

        $friendsLiked = ['00'];

        foreach($friendsId as $uid) {
            $fLikes = $this->likeRepository->getLikesId('page', $uid);

            if (is_array($fLikes)) $friendsLiked = array_merge($friendsLiked, $fLikes);
        }
        ->where(function($query) use($friendsLiked) {
        $query->whereIn('id', $friendsLiked)
        ->orWhere('id', '!=', '');
        })
         **/

        $communityUsers = app('App\Repositories\\UserRepository')->getSimilarCommunityUsers($userid);
        if (! empty($communityUsers)) {
            $query = $this->model->with('likes')
                ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
                ->whereNotIn('id', $likes)
                ->where('user_id', '!=', \Auth::user()->id)
                ->where('is_deleted', '=', 0)
                ->whereIn('user_id', $communityUsers)
                ->orderBy(\DB::raw('rand()'));

            return $query = $query->remember(now()->addMonth(), 'page-suggestions-'.\Auth::user()->id)->take($limit)->get();
        } else {
            return null;
        }
    }

    public function suggestAdmin($term, $page, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $userRepository = app('App\Repositories\UserRepository');

        $userIds = ['none'];
        // people who like this page
        $likesId = $this->likeRepository->getIds('page', $page->id);
        $userIds = array_merge($userIds, $likesId);

        // also friends only
        $friendsId = app('App\Repositories\ConnectionRepository')->getFriendsId($userid);
        $userIds = array_merge($userIds, $friendsId);

        return $userRepository->searchByIds($term, $userIds, null, $userid);
    }

    public function friendsToLike($pageId, $limit = 5, $offset = 0, $term = '', $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $userRepository = app('App\Repositories\UserRepository');
        $userIds = ['none'];
        // people who like this page
        $likesId = $this->likeRepository->getIds('page', $pageId);
        $userIds = array_merge($userIds, $likesId);

        // also friends only
        $friendsId = app('App\Repositories\ConnectionRepository')->getFriendsId($userid);
        $friendsId[] = 0;

        return $userRepository->listByIds($friendsId, [0], $limit, $offset, $term);
    }

    public function lists($category = null, $limit = 10, $term = null)
    {
        $query = $this->model->where('is_deleted', '=', 0)->orderBy('id', 'desc')
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get());

        if (! empty($category)) {
            $query = $query->where('category_id', '=', $category);
        }

        if ($term) {
            $query = $query->where('title', 'LIKE', '%'.$term.'%');
        }

        return $query = $query->paginate($limit);
    }

    public function kycUploadedStores($limit = 20, $term = null, $kyc = null)
    {
        $query = $this->model
            ->with('user')
            ->where('is_deleted', '=', 0)
            ->whereNotNull('business_number_file')
            ->where('business_number_file', '!=', '')
            ->orderBy('id', 'desc');

        if ($term) {
            $query = $query->where(function ($q) use ($term) {
                $q->where('title', 'LIKE', '%'.$term.'%')
                    ->orWhere('slug', 'LIKE', '%'.$term.'%');
            });
        }

        // Optional filter: kyc_completed = 0/1
        if ($kyc !== null && $kyc !== '') {
            $kyc = (int) $kyc;
            if (in_array($kyc, [0, 1], true)) {
                if (!class_exists('Schema') || \Schema::hasColumn('pages', 'kyc_completed')) {
                    $query = $query->where('kyc_completed', '=', $kyc);
                }
            }
        }

        return $query->paginate($limit);
    }

    public function listsByCommunity($category = null, $limit = 10, $term = null)
    {
        $query = $this->model->where('is_deleted', '=', 0)->orderBy('id', 'desc')
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get());

        if (! empty($category)) {
            $query = $query->where('category_id', '=', $category);
        }

        if ($term) {
            $query = $query->where('title', 'LIKE', '%'.$term.'%');
        }

        $query = $query->where('community_id', '!=', 0);
        $query = $query->where('status', '=', 1);

        return $query = $query->paginate($limit);
    }

    public function myLists($limit = 10, $term = null)
    {
        $query = $this->model->with('likes')->where('is_deleted', '=', 0)->where('user_id', '=', \Auth::user()->id)->where('community_id', '!=', 0);
        if ($term) {
            $query = $query->where('title', 'LIKE', '%'.$term.'%');
        }

        return $query->orderBy('id', 'desc')->paginate($limit);
    }
	
	public function myAssociatedLists($limit = 10, $term = null)
    {
		$pageAdminRepo = app('App\\Repositories\\PageAdminRepository');

		$adminPageIds = (array) $pageAdminRepo->getByUserId(\Auth::user()->id);
		$ownedPageIds = (array) $this->getByBusinesIds();
		$ids = array_values(array_unique(array_filter(array_merge($adminPageIds, $ownedPageIds))));
		
        $query = $this->model->with('likes')->where('is_deleted', '=', 0)->whereIn('id', $ids)->where('community_id', '!=', 0);
		
        if ($term) {
            $query = $query->where('title', 'LIKE', '%'.$term.'%');
        }

        return $query->orderBy('id', 'desc')->paginate($limit);
    }

    public function myListsId()
    {
        $result = $this->model->with('likes')->where('is_deleted', '=', 0)->where('user_id', '=', \Auth::user()->id)->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function delete($id, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $page = $this->get($id);

        if ($page) {

            if ($page->user_id != $userid) {
                if (\Auth::check()) {
                    if (! \Auth::user()->isAdmin()) {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            return $this->model->where('id', '=', $id)->update(['is_deleted' => 1]);

            /*$page->delete();

            foreach([
                        'App\\Repositories\\PostRepository',
                        'App\\Repositories\\LikeRepository',
                        'App\\Repositories\\PhotoRepository',
                    ] as $object) {
                app($object)->deleteAllByPage($id,$userid);
            }*/
        }

    }

    public function deleteAllByUser($userid)
    {
        // return $this->model->where('user_id', '=', $userid)->delete();
        return $this->model->where('user_id', '=', $userid)->update(['is_deleted' => 1]);
    }

    public function total()
    {
        return $this->model->count();
    }

    public function getById($id)
    {
        return $this->model->where('id', '=', $id)->where('is_deleted', '=', 0)->first();
    }
	
	public function getByUserIdFirst($user_id)
    {
        return $this->model->where('user_id', '=', $user_id)->where('is_deleted', '=', 0)->orderBy('id', 'asc')->first();
    }

    public function findById($id)
    {
        return $this->model->where('id', '=', $id)->first();
    }
	
	public function findSignupByUserId($user_id)
    {
        return $this->model->where('user_id', '=', $user_id)->where('community_signup', '=', 1)->where('community_activated', '=', 0)->first();
    }

    public function listAll($category, $offset, $term = null)
    {
        $cacheKey = 'pages_list_all_' . ($category ?? 'all') . '_offset_' . $offset . '_term_' . md5($term ?? '') . '_avoid_' . md5(implode(',', $this->mustAvoidUserRepository->get()));
        
        return \Cache::remember($cacheKey, now()->addMonth(), function () use ($category, $offset, $term) {
            $query = $this->model->where('is_deleted', '=', 0)->orderBy('id', 'desc')
                ->whereNotIn('user_id', $this->mustAvoidUserRepository->get());

            if (! empty($category)) {
                $query = $query->where('category_id', '=', $category);
            }

            if ($term) {
                $query = $query->where('title', 'LIKE', '%'.$term.'%');
            }

            return $query = $query->skip($offset)->take(10)->get();
        });
    }

    public function myListsAll($offset = null, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->model->with('likes')->where('user_id', '=', $userid)->where('is_deleted', '=', 0)->orderBy('id', 'desc')->skip($offset)->take(10)->get();
    }

    public function uploadBusinesses($val, $owneruserid, $communityId, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'title' => '',
            'description' => '',
            'website' => '',
            'url' => '',
            'category' => '',
            'business_email' => '',
            'business_contact' => '',
            'country' => '',
            'state' => '',
            'city' => '',
            'street' => '',
            'zip' => '',
            'container_color' => '',
            'container_transparancy' => '',
            'community_id' => '',
            'category' => '',
            'subcategory' => '',
            'page_type' => '',
            'full_address' => '',
            'latitude' => '',
            'longitude' => '',
            'status' => 1,
        ];

        /**
         * @var $title
         * @var $description
         * @var $website
         * @var $category
         * @var $url
         */
        extract(array_merge($expected, $val));

        $currency = 'USD';
        $community = $this->communityRepository->getById($communityId);
        if ($community and $community->currency != '') {
            $currency = $community->currency;
        }

        $url = $this->generateSlug($title);

        $page = $this->model->newInstance();
        $page->title = sanitizeText($title, 130);
        $page->slug = sanitizeText($url);
        $page->user_id = $userid;
        $page->description = $description;
        $page->business_email = sanitizeText($business_email);
        $page->business_contact = sanitizeText($business_contact);
        $page->country = sanitizeText($country);
        $page->state = sanitizeText($state);
        $page->city = sanitizeText($city);
        $page->street = sanitizeText($street);
        $page->zip = sanitizeText($zip);
        $page->community_id = $communityId;
        $page->website = sanitizeText($website);
        $page->category_id = sanitizeText($category);
        $page->subcategory_id = sanitizeText($subcategory);
        $page->page_type = sanitizeText($page_type);
        $page->latitude = $latitude;
        $page->longitude = $longitude;
        $page->status = $status;
        $page->full_address = $street;
        $page->currency = $currency;
        $page->save();

        $this->event->dispatch('page.add', [$page]);

        return $page;
    }

    public function generateSlug($name)
    {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '', $name)));

        $data = $this->getBySlugGenerate($slug);
        $_newslug = $slug;

        if ($data) {
            $n = 1;
            $max_index = 2000;
            while ($n < $max_index) { // just to be safe
                $_newslug = $slug.$n;
                $findnewslug = $this->getBySlug($_newslug);
                if (!$findnewslug) {
                    break;
                }
                $n++;
            }
        }

        return $_newslug;
    }
	
	public function getBySlugGenerate($slug)
    {
        return $this->model->where('slug', '=', $slug)->where('is_deleted', '=', 0)->exists();
    }

    public function getBySlug($slug)
    {
        $cacheKey = 'page_by_slug_' . md5($slug);
        
        return \Cache::remember($cacheKey, now()->addMonth(), function () use ($slug) {
            return $this->model->where('slug', '=', $slug)->where('is_deleted', '=', 0)->first();
        });
    }

    public function getByTitleUserId($slug, $userid)
    {
        return $this->model->where('title', '=', $slug)->where('user_id', '=', $userid)->first();
    }

    public function myBusinessesCount()
    {
        $myBusinessesCount = $this->model->where('user_id', '=', \Auth::user()->id)->where('is_deleted', '=', 0)->where('community_id', '!=', 0)->get();

        return count($myBusinessesCount);
    }

    public function myBusinessesPendingReviewCount($communityId)
    {
        $myBusinessesCount = $this->model->where('community_id', '=', $communityId)->where('is_deleted', '=', 0)->where('community_id', '=', $communityId)->where('status', '=', 0)->count();

        return $myBusinessesCount;
    }

    public function updateSeoContents($val, $pageId)
    {
        $expected = [
            'seo_keywords',
            'seo_meta_title',
            'seo_meta_description',
        ];

        extract(array_merge($expected, $val));

        $page = $this->getById($pageId);

        if ($page) {
            $page->seo_keywords = $seo_keywords;
            $page->seo_meta_title = $seo_meta_title;
            $page->seo_meta_description = $seo_meta_description;
            $page->save();
        }
    }

    public function getByIds($ids, $limit = 10, $term = null)
    {
        if (! empty($ids)) {
            return $this->model->whereIn('id', $ids)->where('community_id', '!=', 0)->where('is_deleted', '=', 0)->paginate($limit);
        }
    }

    public function getByIdsMine($ids, $term = null, $limit = 10)
    {
        if ($term) {
            return $this->model->whereIn('id', $ids)->where('is_deleted', '=', 0)->where('title', 'like', '%'.$term.'%')->where('community_id', '!=', 0)->orderBy('id', 'desc')->paginate($limit);
        } else {
            return $this->model->whereIn('id', $ids)->where('is_deleted', '=', 0)->where('community_id', '!=', 0)->orderBy('id', 'desc')->paginate($limit);
        }
    }

    public function getAll($term = null, $limit = 10)
    {
        if ($term) {
            return $this->model->where('is_deleted', '=', 0)->where('title', 'like', '%'.$term.'%')->where('community_id', '!=', 0)->orderBy('id', 'desc')->paginate($limit);
        } else {
            return $this->model->where('is_deleted', '=', 0)->where('community_id', '!=', 0)->orderBy('id', 'desc')->paginate($limit);
        }
    }

    public function searchPage($term, $cateroies, $subcateroies, $limit = 10)
    {
        // return $this->model->where('community_id', '!=', 0)->whereIn('category_id', $cateroies)->orWhereIn('subcategory_id', $subcateroies)->orWhere('title', 'like', '%'.$term.'%')->orWhere('description', 'like', '%'.$term.'%')->paginate($limit);

        return $pages = $this->model->where('community_id', '!=', 0)
            ->where('is_deleted', '=', 0)
            ->where('status', '=', 1)
            ->where(function ($q) use ($term, $cateroies, $subcateroies) {
                $q->where('title', 'like', '%'.$term.'%');

                if (! empty($cateroies)) {
                    $q = $q->orWhereIn('category_id', $cateroies);
                }

                if (! empty($subcateroies)) {
                    $q = $q->orWhereIn('subcategory_id', $subcateroies);
                }
            })
            ->orderBy('id', 'desc')->paginate(10);
    }

    public function searchPageByCategory($category_id, $limit = 10)
    {
        $cacheKey = 'pages_by_category_' . $category_id . '_limit_' . $limit;
        
        return \Cache::remember($cacheKey, now()->addMonth(), function () use ($category_id, $limit) {
            return $this->model->where('community_id', '!=', 0)->where('is_deleted', '=', 0)->where('status', '=', 1)->where('category_id', $category_id)->orderBy('id', 'desc')->paginate($limit);
        });
    }

    public function searchPageByCategoryCommunity($category_id, $community_id, $offset = 0)
    {
        $cacheKey = 'pages_by_category_community_' . $category_id . '_' . $community_id . '_offset_' . $offset;
        
        return \Cache::remember($cacheKey, now()->addMonth(), function () use ($category_id, $community_id, $offset) {
            return $this->model
                ->where('community_id', '=', $community_id)
                ->where('is_deleted', '=', 0)
                ->where('status', '=', 1)
                ->where('category_id', $category_id)
                ->orderBy('id', 'desc')
            // ->paginate($limit);
                ->skip($offset)->take(9)->get();
        });
    }

    public function searchPageCommunity($term, $cateroies, $subcateroies, $community_id, $business_city_name, $business_state_name, $business_country_name, $business_category, $business_zip_code, $limit = 10, $location_radius = '', $business_latitude = '', $business_longitude = '', $product_business_ids = null, $business_search_type = null, $offset = 0)
    {
        // return $this->model->where('community_id', '!=', 0)->whereIn('category_id', $cateroies)->orWhereIn('subcategory_id', $subcateroies)->orWhere('title', 'like', '%'.$term.'%')->orWhere('description', 'like', '%'.$term.'%')->paginate($limit);

        /*$pages=$this->model->where('community_id', '=', $community_id)
                          ->where('is_deleted', '=', 0)
                         ->where('status', '=', 1);	*/

        $pages = $this->model;

        $publicBusinessCommunity = app('App\\Repositories\\CommunityRepository')->publicBusinessCommunity();

        if (! $publicBusinessCommunity) {
            $pages = $pages->where('community_id', '=', $community_id);
        }

        if ($publicBusinessCommunity and $community_id != $publicBusinessCommunity->id) {
            $pages = $pages->where('community_id', '=', $community_id);
        }

        $pages = $pages->where('is_deleted', '=', 0)
            ->where('status', '=', 1)
            ->orderBy('id', 'desc');

        if ($location_radius != '' and $business_latitude != '' and $business_longitude != '') {

            $radius_km = $location_radius;
            $latitude = $business_latitude;
            $longitude = $business_longitude;

            $sql_distance = ' ,(((acos(sin(('.$latitude.'*pi()/180)) * sin((`p`.`latitude`*pi()/180))+cos(('.$latitude.'*pi()/180)) * cos((`p`.`latitude`*pi()/180)) * cos((('.$longitude.'-`p`.`longitude`)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance ';

            // $sql_distance=" ,( 6371 * acos( cos( radians({$latitude}) ) * cos( radians( `latitude` ) ) * cos( radians( `longitude` ) - radians({$longitude}) ) + sin( radians({$latitude}) ) * sin( radians( `latitude` ) ) ) ) AS distance";

            $having = " HAVING (distance <= $radius_km) ";

            $order_by = 'distance ASC ';

            $where = 'WHERE is_deleted=0 && status=1';

            if ($publicBusinessCommunity and $community_id != $publicBusinessCommunity->id) {
                $where = $where.' && community_id='.$community_id.'';
            }

            if ($business_category != '') {
                $where = $where.' && category_id='.$business_category.'';
            }

            $sql = 'SELECT p.id'.$sql_distance." FROM id_pages p $where $having ORDER BY $order_by";

            $results = \DB::select($sql);

            $ids = [];
            if (! empty($results)) {
                foreach ($results as $res) {
                    array_push($ids, $res->id);
                }
            }

            $pages = $this->model;

            if ($business_search_type == 1) {
                $result = $pages->whereIn('id', $ids)->pluck('id');
                $pages = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;

                return $pages;
            } else {

                $pages = $pages->where(function ($q) use ($term, $cateroies, $subcateroies, $product_business_ids) {

                    if ($term != '') {
                        $q->where(function ($q) use ($term) {
                            $q->where('title', 'like', '%'.$term.'%')
                                ->orWhere('country', 'like', '%'.$term.'%')
                                ->orWhere('state', 'like', '%'.$term.'%')
                                ->orWhere('city', 'like', '%'.$term.'%')
                                ->orWhere('street', 'like', '%'.$term.'%')
                                ->orWhere('full_address', 'like', '%'.$term.'%');
                        })->orWhere(function ($q) use ($cateroies, $subcateroies, $product_business_ids) {
                            // if(!is_null($cateroies)){
                            $q = $q->orWhereIn('category_id', $cateroies)
                              // }

                              // if(!is_null($subcateroies)){
                                ->orWhereIn('subcategory_id', $subcateroies)

                              // if(!is_null($product_business_ids)){
                                ->orWhereIn('id', $product_business_ids);
                            //   }

                        });
                    } else {
                        $q = $q->where('status', '=', 1);
                    }
                })
                    ->whereIn('id', $ids)
                    ->orderBy('id', 'desc')
                // ->paginate(9);
                    ->skip($offset)->take(9)->get();

                return $pages;
            }

        } else {
            if ($business_zip_code) {
                $shortZip = substr($business_zip_code, 0, 3);
                $pages->where('zip', 'like', $shortZip.'%');
            } else {
                if ($business_city_name != '') {
                    $pages->where('city', '=', $business_city_name);
                }

                if ($business_state_name != '') {
                    $business_state_name = getStateFullName($business_state_name);
                    $pages->where('state', '=', $business_state_name);
                }
            }

            if ($business_country_name != '') {
                $pages->where('country', '=', $business_country_name);
            }
        }

        if ($business_search_type == 1) {
            $result = $pages->pluck('id');
            $pages = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;

            return $pages;
        } else {
            if ($business_category != '') {
                $pages->where('category_id', '=', $business_category);
            }

            $pages = $pages->where(function ($q) use ($term, $cateroies, $subcateroies, $product_business_ids) {

                if ($term != '') {
                    $q->where(function ($q) use ($term) {
                        $q->where('title', 'like', '%'.$term.'%')
                            ->orWhere('country', 'like', '%'.$term.'%')
                            ->orWhere('state', 'like', '%'.$term.'%')
                            ->orWhere('city', 'like', '%'.$term.'%')
                            ->orWhere('street', 'like', '%'.$term.'%')
                            ->orWhere('full_address', 'like', '%'.$term.'%');
                    })->orWhere(function ($q) use ($cateroies, $subcateroies, $product_business_ids) {
                        // if(!is_null($cateroies)){
                        $q = $q->orWhereIn('category_id', $cateroies)
                              // }

                              // if(!is_null($subcateroies)){
                            ->orWhereIn('subcategory_id', $subcateroies)

                              // if(!is_null($product_business_ids)){
                            ->orWhereIn('id', $product_business_ids);
                        //   }
                    });
                } else {
                    $q = $q->where('status', '=', 1);
                }
            })
                ->orderBy('id', 'desc')
                // ->paginate(9);
                ->skip($offset)->take(9)->get();

            return $pages;
        }
    }

    public function getOtherUsersBusiness($communityId, $limit = 10)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->model->where('community_id', '=', $communityId)->where('is_deleted', '=', 0)->where('user_id', '!=', $userid)->orderBy('id', 'desc')->paginate($limit);
    }
	
	public function getByCommunityIdCount($community_id)
    {
        return $this->model->where('community_id', $community_id)->where('is_deleted', '=', 0)->count();
    }

    public function getCommunityBusinesses($communityId, $limit = 10)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->model->where('community_id', '=', $communityId)->where('is_deleted', '=', 0)->orderBy('id', 'desc')->paginate($limit);
    }

    public function getPendingReviewList($communityId, $limit = 10)
    {
       // return $this->model->where('community_id', '=', $communityId)->where('is_deleted', '=', 0)->where('status', '=', 0)->orderBy('id', 'desc')->paginate($limit);
	   
	     return $this->model->where('community_id', '=', $communityId)->where('is_deleted', '=', 0)->orderBy('id', 'desc')->paginate($limit);
    }

    public function changeBusinessStatus($page, $val)
    {
        $page->status = $val;
        $page->save();
    }
	
	public function changeBusinessStatusReason($page, $val,$reason)
    {
        $page->status = $val;
		
		//if($val==0){
			$page->deactivated_reason = $reason;
			$page->deactivated_by_userid = \Auth::user()->id;
		//}
		
        $page->save();
    }

	public function updateKycReviewStatus($page, $kycCompleted)
    {
        $page->kyc_completed = (int) $kycCompleted;
        $page->status = 1;
        $page->save();
    }

    public function changeBusinessFaturing($page, $val)
    {
        $page->is_featured = $val;
        $page->save();
    }

    public function getByBusinesIds()
    {
        $result = $this->model->where('is_deleted', '=', 0)->where('user_id', '=', \Auth::user()->id)->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function changeBusinessCommunication($page, $val)
    {
        $page->business_communication = $val;
        $page->save();
    }

    public function myBusinessesAllCount()
    {
        $businessIds = app('App\\Repositories\\PageAdminRepository')->getByUserId();
        $myBusinessIds = $this->getByBusinesIds($businessIds);

        $allIds = array_merge($businessIds, $myBusinessIds);

        return $this->model->whereIn('id', $allIds)->where('is_deleted', '=', 0)->where('community_id', '!=', 0)->count();
    }

    public function getNamesByCommunity($term, $communityid)
    {
        $result = $this->model->where('is_deleted', '=', 0)->where('title', 'LIKE', '%'.$term.'%')->where('community_id', '=', $communityid)->take(50)->pluck('title');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
        // return $this->model->where("title",'LIKE', '%'.$term.'%')->groupBy('title')->take(50)->pluck('title');
    }

    public function findByCommunityBusinessName($communityid, $term)
    {
        return $this->model->where('is_deleted', '=', 0)->where('title', $term)->where('community_id', '=', $communityid)->get();
    }

    public function communityBusinessTotal($community_id)
    {
        // online users totalonline
        return $this->model->where('is_deleted', '=', 0)->where('community_id', '=', $community_id)->count();
    }

    public function totalBusinesses($community_id)
    {
        // online users totalonline
        return $this->model->where('is_deleted', '=', 0)->count();
    }

    public function listAllFeatured($community_id)
    {
        return $this->model->where('community_id', '=', $community_id)->where('is_featured', '=', 1)->where('is_deleted', '=', 0)->orderBy('id', 'desc')->get();
    }

    public function listAllFeaturedByAddress($community_id, $business_city_name = null, $business_state_name = null, $business_country_name = null, $business_zip_code = null, $offset = 0)
    {

        $pages = $this->model;

        /*$publicBusinessCommunity=app('App\\Repositories\\CommunityRepository')->publicBusinessCommunity();

        if($publicBusinessCommunity and $community_id!=$publicBusinessCommunity->id){
            $pages=$pages->where('community_id', '=', $community_id);
        }*/

        if ($community_id != id4MartCommunityId()) {
            $pages = $pages->where('community_id', $community_id)->where('is_featured', '=', 1);
        } else {
            $pages = $pages->where('is_featured_global', '=', 1);
        }

        $pages = $pages->where('is_deleted', '=', 0)
                   /* ->where('is_featured', '=', 1) */
            ->where('status', '=', 1)
            ->orderBy('id', 'desc');

        if ($business_zip_code) {
            $shortZip = substr($business_zip_code, 0, 3);
            $pages->where('zip', 'like', $shortZip.'%');
        } else {
            if ($business_city_name != '') {
                $pages->where('city', '=', $business_city_name);
            }

            if ($business_state_name != '') {
                $business_state_name = getStateFullName($business_state_name);
                $pages->where('state', '=', $business_state_name);
            }
        }

        if ($business_country_name != '') {
            $pages->where('country', '=', $business_country_name);
        }

        // $pages=$pages->paginate(6);

        $pages = $pages->skip($offset)->take(9)->get();

        return $pages;
    }

    public function getAllFeatured($community_id, $business_city_name = null, $business_state_name = null, $business_country_name = null, $business_zip_code = null, $offset = 0)
    {

        $pages = $this->model;
        /*$publicBusinessCommunity=app('App\\Repositories\\CommunityRepository')->publicBusinessCommunity();

        if($publicBusinessCommunity and $community_id!=$publicBusinessCommunity->id){
            $pages=$pages->where('community_id', '=', $community_id);
        }*/

        if ($community_id != id4MartCommunityId()) {
            $pages = $pages->where('community_id', $community_id)->where('is_featured', '=', 1);
        } else {
            $pages = $pages->where('is_featured_global', '=', 1);
        }

        $pages = $pages->where('is_deleted', '=', 0)
                   /* ->where('is_featured', '=', 1) */
            ->where('status', '=', 1)
            ->orderBy('id', 'desc');

        if ($business_zip_code) {
            $shortZip = substr($business_zip_code, 0, 3);
            $pages->where('zip', 'like', $shortZip.'%');
        } else {
            if ($business_city_name != '') {
                $pages->where('city', '=', $business_city_name);
            }

            if ($business_state_name != '') {
                $business_state_name = getStateFullName($business_state_name);
                $pages->where('state', '=', $business_state_name);
            }
        }

        if ($business_country_name != '') {
            $pages->where('country', '=', $business_country_name);
        }

        $pages = $pages->get();

        return $pages;
    }

    public function featuredBusinessesByCategory($community_id, $category, $business_city_name, $business_state_name, $business_country_name, $business_zip_code, $offset = 0)
    {
        /*$pages=$this->model->where('community_id', '=', $community_id)
                          ->where('is_deleted', '=', 0)
                    ->where('is_featured', '=', 1)
                         ->where('status', '=', 1)
                    ->orderBy('id', 'desc');	*/

        $pages = $this->model;

        /* $publicBusinessCommunity=app('App\\Repositories\\CommunityRepository')->publicBusinessCommunity();

         if($publicBusinessCommunity and $community_id!=$publicBusinessCommunity->id){
             $pages=$pages->where('community_id', '=', $community_id);
         }*/

        if ($community_id != id4MartCommunityId()) {
            $pages = $pages->where('community_id', $community_id)->where('is_featured', '=', 1);
        } else {
            $pages = $pages->where('is_featured_global', '=', 1);
        }

        $pages = $pages->where('is_deleted', '=', 0)
                   /* ->where('is_featured', '=', 1) */
            ->where('status', '=', 1)
            ->orderBy('id', 'desc');
        if ($business_zip_code) {
            $shortZip = substr($business_zip_code, 0, 3);
            $pages->where('zip', 'like', $shortZip.'%');
        } else {
            if ($business_city_name != '') {
                $pages->where('city', '=', $business_city_name);
            }

            if ($business_state_name != '') {
                $business_state_name = getStateFullName($business_state_name);
                $pages->where('state', '=', $business_state_name);
            }
        }

        if ($business_country_name != '') {
            $pages->where('country', '=', $business_country_name);
        }

        if ($category == 'other') {
            $pages->whereNotIn('category_id', [23, 17, 15]);
        }

        if ($category != 'other') {
            $pages->where('category_id', '=', $category);
        }

        // $pages=$pages->get();
        // $pages=$pages->paginate(6);

        $pages = $pages->skip($offset)->take(9)->get();

        return $pages;
    }

    public function updateLatitudeLongitude()
    {
        $pages = $this->model
            ->where('latitude', '=', '')
            ->orWhere('latitude', '=', '')
            ->get();

        if ($pages) {
            foreach ($pages as $page) {

                if ($page->street != '' || $page->city != '' || $page->zip != '' || $page->state != '' || $page->state != '') {

                    $location = $page->street.' '.$page->city.' '.$page->zip.' '.$page->state.' '.$page->country;

                    $location = trim($location);

                    $newLocation = str_replace(' ', '+', $location);

                    // Use environment variable for Google Maps API key
                    $mapsKey = config('services.google_maps.api_key', 'AIzaSyDTy41lNmvfYbNFjv1_E0tg2EilMaxzGVs');
                    $geocode = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$newLocation.'&sensor=false&key='.$mapsKey);

                    $output = json_decode($geocode);

                    if (isset($output->results[0]->geometry->location->lat) and isset($output->results[0]->geometry->location->lng)) {
                        $lat = $output->results[0]->geometry->location->lat;
                        $long = $output->results[0]->geometry->location->lng;

                        $page->latitude = $lat;
                        $page->longitude = $long;

                        $page->save();
                    }
                }
            }
        }
    }

    public function uploadFevicon($id, $logo)
    {
        return $this->model->where('id', '=', $id)->update(['fevicon_image' => $logo]);
    }

    public function updateSlug($url, $page)
    {
        $page->slug = $url;
        $page->save();

        return $page;
    }

    public function getMyBusineses()
    {
        return $this->model->where('is_deleted', '=', 0)->where('user_id', '=', \Auth::user()->id)->get();
    }

    public function updateCurrencyByCommunity($community_id, $currency)
    {
        return $this->model->where('community_id', '=', $community_id)->update(['currency' => $currency]);
    }

    public function getInactiveBusinessIds($community_id)
    {
        $pages = $this->model;

        if ($community_id != id4MartCommunityId()) {
            $pages = $pages->where('community_id', '=', $community_id);
        }

        $pages = $pages->where(function ($page) {
            $page->where('is_deleted', '=', 1)
                ->orWhere('status', '=', 0);
        });

        $result = $pages->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function getActiveBusinessIds($community_id)
    {
        $pages = $this->model;
        $pages = $pages->where('community_id', '=', $community_id);

        $result = $pages->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function getActiveBusinessIdsByUser($community_id, $user_id)
    {
        $pages = $this->model;
        $pages = $pages->where('community_id', '=', $community_id)->where('user_id', '=', $user_id);

        $result = $pages->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }
	
	public function getWebsiteThemePage($community)
    {
        return $this->model
		->where('user_id', '=', $community->user_id)
		->where('default_for_website', '=', 1)
		->where('is_deleted', '=', 0)->first();
    }
}