<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Http\Controllers\Base\UserBaseController;
use App\Interfaces\PhotoRepositoryInterface;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;
use Stripe;
use Illuminate\Support\Facades\Session;
use App\Http\Controllers\Traits\LazyLoadsRepositories;

class CommunityController extends UserBaseController
{
    use LazyLoadsRepositories;

    public function __construct(
        PhotoRepositoryInterface $photoRepositoryInterface,
        Filesystem $filesystem,
        Mailer $mailer
    ) {
        parent::__construct();
        $this->photo = $photoRepositoryInterface;
        $this->file = $filesystem;
        $this->mailer = $mailer;
    }

    public function index()
    {
        return $this->preRender($this->theme->section('community.index', [
            'communities' => $this->communityRepository()->getMyCommunities(),
        ]), $this->setTitle(trans('community.communities')));
    }

    public function joined()
    {
        return $this->preRender($this->theme->section('community.joined', [
            'communities' => $this->communityRepository()->getJoinedCommunities(),
        ]), $this->setTitle(trans('community.communities')));
    }

    public function create(Request $request)
    {
        return redirect('home');

        $message = null;
        if ($val = $request->get('val')) {

            /**
             * @var $privacy
             */
            extract($val);
            if ($privacy == 1) {
                $validator = \Validator::make($val, [
                    'public_name' => 'required|predefined|validalpha|min:3',
                    'public_url' => 'required|predefined|validalpha|min:3|alpha_dash|slug|unique:communities,slug',
                ]);
            } else {
                $validator = \Validator::make($val, [
                    'private_name' => 'required|predefined|validalpha|min:3',
                    'private_url' => 'required|predefined|validalpha|min:3|alpha_dash|slug|unique:communities,slug',
                ]);
            }

            if (! $validator->fails()) {
                $community = $this->communityRepository()->create($val);

                if ($community) {
                    // redirect to community page
                    return redirect($community->present()->url());
                } else {
                    $message = trans('community.create-error');
                }
            } else {
                $message = $validator->messages()->first();
            }
        }

        return $this->preRender($this->theme->section('community.create', ['message' => $message]),
            $this->setTitle(trans('community.create')));
    }

    public function leave($id, Request $request)
    {
        $userid = $request->get('userid');
        $this->communityRepository()->leave($id, $userid);

        return redirect(\URL::previous());
    }

    public function assignModerator($id, $userid)
    {
        $this->communityRepository()->assignModerator($id, $userid);

        return redirect(\URL::previous());
    }

    public function removeModerator($id, $userid)
    {
        $this->communityRepository()->removeModerator($id, $userid);

        return redirect(\URL::previous());
    }

    public function delete($id, Request $request)
    {
        $this->communityRepository()->delete($id);

        $ref = $request->get('ref', false);

        if ($ref) {
            return redirect(\URL::previous());
        }

        return \Redirect::route('communities');
    }

    public function checkCommunitySlug(Request $request)
    {
        $val = $request->get('val');
        $communityId = $request->get('communityId');

        if (! preg_match('/^([-a-z0-9])+$/i', $val)) {
            return 0;
        } else {
            return $checkCommunityData = $this->communityRepository()->checkCommunitySlug($val, $communityId);
        }
    }

    public function getLogo($id)
    {
        $community = $this->communityRepository()->getById($id);
        if ($community) {
            return $community->present()->getLogo();
        }
    }

    public function changeGroupType(Request $request)
    {
        $group_type = $request->get('group_type');
        $id = $request->get('id');

        $this->communityCategoryRepository()->changeGroupType($id, $group_type);
    }

    public function uploadCommunityImages(Request $request)
    {
        if (count($_FILES) > 0 && isset($_FILES['file']['name'])) {
            $upload_community = $request->get('upload_community');
            $upload_type = $request->get('upload_type');

            $user = \Auth::user();
            $images = $request->file('file');

            if (! $this->photoRepository()->imagesMetSizes($images)) {
                return false;
            }
            $image = '';
            $album = '';

            $community_image = '';
            $logoimage = $images;

            $filePath = 'uploads/users/'.$user->id.'/community';
            $CDNRepository = app('App\\Repositories\\CDNRepository');

            $fileExt = $logoimage->getClientOriginalExtension();
            $file_original_ext = $fileExt;
            $file_original_name = $logoimage->getClientOriginalName();
            $file_original_size = $logoimage->getSize();

            if (checkAvailableSpace($upload_community, $file_original_size) == 0) {
                $array = ['error' => true, 'message' => 'No sufficient space available to upload.'];

                return stripslashes(json_encode($array));
            }

            $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);

            $fileName = md5($logoimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
            $logoimage_path = $filePath.'/'.$fileName;

            $logoimage->move(public_path().'/'.$filePath, $fileName);

            $uploadPath = 'uploads/users/'.$user->id.'/community/'.$fileName;
            $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);

            $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
            $image = $newFileName;

            $fileArray = [
                'community_id' => $upload_community,
                'user_id' => \Auth::user()->id,
                'file_path' => $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' => 0,
                'sub_type_id' => 0,
                'upload_key' => Str::random(20),
            ];

            $this->communitySpaceUsedRepository()->save($fileArray);

            if ($image != '') {
                $array = ['filelink' => \Image::url($image)];

                return stripslashes(json_encode($array));
            } else {
                $array = ['error' => true, 'message' => 'Something went wrong...'];

                return stripslashes(json_encode($array));
            }
        }

    }

    public function themesUploadImages(Request $request)
    {
        $user = \Auth::user();
        $images = $request->file('nomefile');

        if (! $this->photoRepository()->imagesMetSizes($images)) {
            return false;
        }

        $image = '';
        $album = '';
        $community_image = '';
        $logoimage = $images;
        $upload_key = Str::random(20);
        $upload_type = $request->get('upload_type');
        if (! $upload_type) {
            $upload_type = 'Page';
        }

        $community_id = $request->get('upload_community_id');
        if (! $community_id) {
            $community_id = 0;
        }

        if ($logoimage) {
            $filePath = 'uploads/users/'.$user->id.'/community/themes';
            $CDNRepository = app('App\\Repositories\\CDNRepository');
            $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
            $fileExt = $logoimage->getClientOriginalExtension();

            $file_original_ext = $fileExt;
            $file_original_name = $logoimage->getClientOriginalName();
            $file_original_size = $logoimage->getSize();

            if (checkAvailableSpace($community_id, $file_original_size) == 0) {
                $array = ['error' => 2, 'message' => 'No sufficient space available to upload.'];

                return stripslashes(json_encode($array));
            }

            $fileName = md5($logoimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
            $logoimage_path = $filePath.'/'.$fileName;
            $logoimage->move(public_path().'/'.$filePath, $fileName);
            $uploadPath = 'uploads/users/'.$user->id.'/community/themes/'.$fileName;
            $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);
            $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
            $image = $newFileName;

            $fileArray = [
                'community_id' => $community_id,
                'user_id' => \Auth::user()->id,
                'file_path' => $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' => 0,
                'sub_type_id' => 0,
                'upload_key' => $upload_key,
            ];
            $this->communitySpaceUsedRepository()->save($fileArray);
        }

        if ($image != '') {
            $array = ['error' => 0, 'filelink' => \Image::url($image)];

            return stripslashes(json_encode($array));
        } else {
            $array = ['error' => 1, 'message' => 'Something went wrong...'];

            return stripslashes(json_encode($array));
        }
    }

    public function themesUploadVideo(Request $request)
    {
        $user = \Auth::user();
        $video = $request->file('upload-theme-video-input');

        $videoPlayUrl = '';
        $videoUrl = '';
        $ThumbnailUrl = '';

        $upload_key = Str::random(20);
        $upload_type = $request->get('upload_type');
        if (! $upload_type) {
            $upload_type = 'Page';
        }

        $community_id = $request->get('upload_community_id');
        if (! $community_id) {
            $community_id = 0;
        }

        if ($video) {
            $mainFile = $video;
            $fileExt = $mainFile->getClientOriginalExtension();
            $file_original_ext = $fileExt;
            $file_original_name = $mainFile->getClientOriginalName();
            $file_original_size = $mainFile->getSize();

            if (checkAvailableSpace($community_id, $file_original_size) == 0) {
                $array = ['error' => 2, 'message' => 'No sufficient space available to upload.'];

                return stripslashes(json_encode($array));
            }

            $userid = \Auth::user()->id;
            $filePath = 'uploads/users/'.$user->id.'/community/themes';

            // ensure the folder exists
            $CDNRepository = app('App\\Repositories\\CDNRepository');

            $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
            $fileName = md5($mainFile->getClientOriginalName().time()).'.'.$fileExt;
            $file_path = $filePath.'/'.$fileName;

            $mainFile->move(public_path().'/'.$filePath, $fileName);
            $uploadPath = 'media/appvideo/'.$user->id.'/'.$fileName;

            $newFileName = $CDNRepository->upload(public_path().'/'.$file_path, $uploadPath, 'videoUpload', '480');

            $CDNRepository->deleteThisFile(public_path().'/'.$file_path);
            $file_path = $newFileName;

            $videoUrl = $CDNRepository->getVideoOutpuLinkMp4($file_path);
            $thumbnailUrl = $CDNRepository->getVideoThumbnail($file_path);

            $videoPlayUrl = $file_path;
            // $videoPlayUrl=\URL()."/post/play/video?path=".$videoUrl."&thumbnail=".$thumbnailUrl;

            $fileArray = [
                'community_id' => $community_id,
                'user_id' => \Auth::user()->id,
                'file_path' => $videoPlayUrl,
                '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' => 0,
                'sub_type_id' => 0,
                'upload_key' => $upload_key,
            ];
            $this->communitySpaceUsedRepository()->save($fileArray);
        }

        if ($file_path != '') {
            $array = ['error' => 0, 'videoPlayUrl' => $videoPlayUrl, 'videoUrl' => $videoUrl, 'thumbnailUrl' => $thumbnailUrl];

            return stripslashes(json_encode($array));
        } else {
            $array = ['error' => 1, 'message' => 'Something went wrong...'];

            return stripslashes(json_encode($array));
        }
    }

    public function getVideoThumbnail(Request $request)
    {
        $file_path = $request->get('videoPlayUrl');
        $CDNRepository = app('App\\Repositories\\CDNRepository');

        $thumbnailUrl = $CDNRepository->getVideoThumbnail($file_path);

        return $thumbnailUrl;
    }

    public function communityPageAction(Request $request)
    {
        $value = $request->get('value');
        $pageId = $request->get('pageId');
        $communityId = $request->get('communityId');
        $action = $this->communityPagesRepository()->communityPageAction($value, $pageId, $communityId);
        /*if($action){
            return true;
        }*/

    }

    public function userCommunities()
    {
        $communitiesJoined = $this->communityRepository()->getMyAllJoinedCommunities();
        $myOwnedCommunity = $this->communityRepository()->getExternalByUserId(\Auth::user()->id);

        $primaryCommunity = '';
        $primaryCommunityId = \Auth::user()->community_signup;
        if ($primaryCommunityId == 0) {
            $primaryCommunityId = \Auth::user()->primary_community;
        }

        if ($primaryCommunityId) {
            $primaryCommunity = $this->communityRepository()->getById($primaryCommunityId);
        }

        return $this->render('user.communities-joined', ['communitiesJoined' => $communitiesJoined, 'myOwnedCommunity' => $myOwnedCommunity, 'primaryCommunity' => $primaryCommunity, 'primaryCommunityId' => $primaryCommunityId]);
    }

    public function userSurveys()
    {
        $posted_in_community = getVisitingCommunityId();

        $posts = app('App\\Repositories\\PostRepository')->pluck('user-timeline', 0, null, null, null, null, null, null, 'onlysurveys', $posted_in_community);

        return $this->render('user.surveys', ['posts' => $posts]);
    }

    public function getCommunityEmails(Request $request)
    {
        $community_id = $request->get('community_id');
        $category = $request->get('category');
        $category_id = $request->get('category_id');

        return $emails = $this->communityMembersEmailsRepository()->getAll($community_id, $category, $category_id);
    }

    public function getCommunitySurveyEmails(Request $request)
    {
        $community_id = $request->get('community_id');
        $category = $request->get('category');

        return $emails = $this->communityMembersEmailsRepository()->getCommunitySurveyEmails($community_id, $category);
    }

    public function validateOrganizationCode(Request $request)
    {
        $identityCode = $request->get('identityCode');

        return $community = $this->communityRepository()->validateOrganizationCode($identityCode);
    }

    public function addCategory(Request $request)
    {
        $id = $request->get('id');
        $name = $request->get('text');

        $category = $this->communityCategoryRepository()->add($id, $name);

        if ($category) {

            $topic = (string) $this->theme->section('community.page.team-menu', ['community' => $category->community, 'category' => $category]);

            return json_encode([
                'title' => '# '.$category->title,
                'topic_link' => $topic,
                'url' => $category->community->present()->url('category/'.$category->slug),
                'status' => 1,
            ]);
        } else {
            return json_encode([
                'status' => 0,
                'message' => trans('community.category-create-error'),
            ]);
        }
    }

    public function createOwn(Request $request)
    {
        $message = '';
        //$myOwnedCommunity = $this->communityRepository()->getExternalByUserId(\Auth::user()->id);

		$myOwnedCommunity = $this->communityRepository()->getExternalByUserIdIncomplete(\Auth::user()->id);		 
        //if (! $myOwnedCommunity || ($myOwnedCommunity and !$myOwnedCommunity->present()->hasCardAdded())) {
		
		$plan_id= $request->get('orgplanid');
		
		if($myOwnedCommunity || $plan_id) {
            $user = \Auth::user();
            
			
			if ($val = $request->get('val')) {
                $rules = [
                    'community_name' => 'required',
                    'community_description' => 'required',
                    'community_slug' => 'required|predefined|min:3|alpha_dash|slug|unique:communities,slug',
                ];
                $validator = \Validator::make($val, $rules);

                if (! $validator->fails()) {
                    $credential = [
                        'community_name' => '',
                        'community_description' => '',
                        'searchable' => 0,
                        'moderator_action' => 1,
                        'domain' => '',
                        'domain_name' => '',
                        'community_slug' => '',
                    ];

                    extract($credential = array_merge($credential, $val));

                    $externalCommunity = $this->communityRepository()->addExternalCommunity($user->id, $community_name, $community_description, $searchable, $moderator_action, $domain, $domain_name, $community_slug, 1, 1);

                    if ($externalCommunity) {
                        if (\Auth::user()->favourite_community == 0) {
                            $this->userRepository()->setFavouriteCm($externalCommunity->id);
                        }

                        // return redirect($externalCommunity->present()->url());

                        $community = $externalCommunity;

                        $urlDomain = config('community-domain.domain-url');
                        $scheme = 'https';
                        $mainUrl = parse_url(config('app.url'));
                        if (isset($mainUrl['host'])) {
                            $urlDomain = $mainUrl['host'];
                            $scheme = $mainUrl['scheme'];
                        }

                        $cmUrl = $scheme.'://'.$community->slug.'.'.$urlDomain;
                        $community_login_url = $cmUrl.'/c/'.$community->id.'/login';
                        $community_forgot_link = $cmUrl.'/c/'.$community->id.'/forgotpass';

                        try {
                            $this->mailer->send('emails.community-activated-inside', [
                                'fullname' => $user->fullname,
                                'email_address' => $user->email_address,
                                'community_title' => $community->title,
                                'community_url' => $cmUrl,
                                'community_login_url' => $community_login_url,
                                'community_forgot_link' => $community_forgot_link,
                            ], function ($mail) use ($user) {
                                $mail->to($user->email_address, $user->fullname)
                                    ->subject('Your account has been activated successfully');
                            });
                        } catch (\Exception $e) {

                        }

                        return $this->render('community.create-own-success', ['community' => $externalCommunity]);
                    }
                } else {
                    $message = $validator->messages()->first();
                }
            }
			
            $organizationDetails = $this->usersOrganizationRepository()->getByUserId(\Auth::user()->id);
			
			if($myOwnedCommunity){
				$plan_id= $myOwnedCommunity->pricing_plan;	
			}			
			
			if($plan_id){			
				$plan=$this->pricingPlansRepository()->getPlanByPlanId($plan_id);
            	return $this->render('community.create-own', ['message' => $message, 'plan' => $plan, 'organizationDetails' => $organizationDetails]);
		    }else{
				$resumeData=\Auth::user()->present()->isResumeCreated();
				if(!$resumeData){
					$desUrl = \URL::route('ip-create');
				}else{
					$desUrl = \URL::to('ip/')."/".$resumeData->slug."/manage";
				}
				
				return redirect($desUrl);
			}		
        } else {
			$myOwnedCommunity = $this->communityRepository()->getExternalByUserId(\Auth::user()->id);
			if($myOwnedCommunity){
           		 return redirect($myOwnedCommunity->present()->url());
			}else{
				$resumeData=\Auth::user()->present()->isResumeCreated();
				if(!$resumeData){
					$desUrl = \URL::route('ip-create');
				}else{
					$desUrl = \URL::to('ip/')."/".$resumeData->slug."/manage";
				}
				
				return redirect($desUrl);
			}		 
        }
    }

    public function uploadCover(Request $request)
    {
        $response = [
            'code' => 0,
            'message' => trans('photo.error', ['size' => formatBytes()]),
            'url' => '',
        ];
        if (! $request->get('coverImg')) {
            return $response;
        }
        if (! $request->get('commId')) {
            return $response;
        }

        $data = $request->get('coverImg');
        $id = $request->get('commId');
        if (! empty($data) && ! empty($id)) {
            /**
             * Update user profile photo
             */
            try {
                $originalImage = $data;
                $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

                $img_name = Str::random(32).'.jpg';
                $img_url = '/uploads/cover';
                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('/', $originalImage)[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($id, $file_original_size) == 0) {
                    $CDNRepository->deleteThisFile(public_path().'/'.$img);

                    return json_encode([
                        'code' => 0,
                        'status' => 'error',
                        'message' => 'No sufficient space available to upload.',
                    ]);
                }

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                // if ($newFileName != $img) {
                // that means file has been successfully uploaded to a CDN Server so
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $img = $newFileName;
                // }

                $upload_key = Str::random(20);
                $fileArray = [
                    'community_id' => $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' => 'community-responsive-logo',
                    'type_id' => 0,
                    'sub_type_id' => 0,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository()->save($fileArray);

                // $this->communityRepository()->updateLogo($id, $img);
                $this->communityRepository()->updateLogoAvatar($id, $img);

                return json_encode([
                    'status' => 'success',
                    'url' => \Image::url($img),
                ]);
                // }
            } catch (\Exception $e) {
                return json_encode([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                ]);
            }
        } else {
            return json_encode([
                'status' => 'error',
                'message' => 'Error things',
            ]);
        }

        return json_encode($response);
    }

    public function uploadFevicon(Request $request)
    {
        $response = [
            'code' => 0,
            'message' => trans('photo.error', ['size' => formatBytes()]),
            'url' => '',
        ];
        if (! $request->get('coverImg')) {
            return $response;
        }
        if (! $request->get('commId')) {
            return $response;
        }

        $data = $request->get('coverImg');
        $id = $request->get('commId');
        if (! empty($data) && ! empty($id)) {
            /**
             * Update user profile photo
             */
            try {
                $originalImage = $data;
                $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
                $img_name = Str::random(32).'.jpg';
                $img_url = '/uploads/community/'.$id.'/fevicon';
                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('/', $originalImage)[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($id, $file_original_size) == 0) {
                    $CDNRepository->deleteThisFile(public_path().'/'.$img);

                    return json_encode([
                        'code' => 0,
                        'status' => 'error',
                        'message' => 'No sufficient space available to upload.',
                    ]);
                }

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                // if ($newFileName != $img) {
                // that means file has been successfully uploaded to a CDN Server so
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $img = $newFileName;
                // }

                $fileArray = [
                    'community_id' => $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' => 'community-fevicon',
                    'type_id' => 0,
                    'sub_type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository()->save($fileArray);

                // $this->communityRepository()->updateLogo($id, $img);
                $this->communityRepository()->uploadFevicon($id, $img);

                return json_encode([
                    'status' => 'success',
                    'url' => \Image::url($img),
                ]);
                // }
            } catch (\Exception $e) {
                return json_encode([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                ]);
            }
        } else {
            return json_encode([
                'status' => 'error',
                'message' => 'Error things',
            ]);
        }

        return json_encode($response);
    }

    public function nominationImage(Request $request)
    {
        $response = [
            'code' => 0,
            'message' => trans('photo.error', ['size' => formatBytes()]),
            'url' => '',
        ];
        if (! $request->get('coverImg')) {
            return $response;
        }
        if (! $request->get('commId')) {
            return $response;
        }

        $data = $request->get('coverImg');
        $id = $request->get('commId');

        $form = $this->communityFormsRepository()->getById($id);

        if (! empty($data) && ! empty($id) and $form and $form->user_id == \Auth::user()->id) {
            /**
             * Update user profile photo
             */
            try {
                $originalImage = $data;
                $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
                $img_name = Str::random(32).'.jpg';
                $img_url = '/uploads/community/'.$form->community_id.'/forms/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('/', $originalImage)[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($form->community_id, $file_original_size) == 0) {
                    $CDNRepository->deleteThisFile(public_path().'/'.$img);

                    return json_encode([
                        'code' => 0,
                        'status' => 'error',
                        'message' => 'No sufficient space available to upload.',
                    ]);
                }

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                // if ($newFileName != $img) {
                // that means file has been successfully uploaded to a CDN Server so
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $img = $newFileName;
                // }

                $fileArray = [
                    'community_id' => $form->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' => 'nomination-banner',
                    'type_id' => 0,
                    'sub_type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository()->save($fileArray);

                $form->nomination_banner = $img;
                $form->save();

                return json_encode([
                    'status' => 'success',
                    'url' => \Image::url($img),
                ]);
                // }
            } catch (\Exception $e) {
                return json_encode([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                ]);
            }
        } else {
            return json_encode([
                'status' => 'error',
                'message' => 'Error things',
            ]);
        }

        return json_encode($response);
    }

    public function votingImage(Request $request)
    {
        $response = [
            'code' => 0,
            'message' => trans('photo.error', ['size' => formatBytes()]),
            'url' => '',
        ];
        if (! $request->get('coverImg')) {
            return $response;
        }
        if (! $request->get('commId')) {
            return $response;
        }

        $data = $request->get('coverImg');
        $id = $request->get('commId');

        $form = $this->communityFormsRepository()->getById($id);

        if (! empty($data) && ! empty($id) and $form and $form->user_id == \Auth::user()->id) {
            /**
             * Update user profile photo
             */
            try {
                $originalImage = $data;
                $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
                $img_name = Str::random(32).'.jpg';
                $img_url = '/uploads/community/'.$form->community_id.'/forms/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('/', $originalImage)[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($form->community_id, $file_original_size) == 0) {
                    $CDNRepository->deleteThisFile(public_path().'/'.$img);

                    return json_encode([
                        'code' => 0,
                        'status' => 'error',
                        'message' => 'No sufficient space available to upload.',
                    ]);
                }

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                // if ($newFileName != $img) {
                // that means file has been successfully uploaded to a CDN Server so
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $img = $newFileName;
                // }

                $fileArray = [
                    'community_id' => $form->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' => 'nomination-banner',
                    'type_id' => 0,
                    'sub_type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository()->save($fileArray);

                $form->voting_banner = $img;
                $form->save();

                return json_encode([
                    'status' => 'success',
                    'url' => \Image::url($img),
                ]);
                // }
            } catch (\Exception $e) {
                return json_encode([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                ]);
            }
        } else {
            return json_encode([
                'status' => 'error',
                'message' => 'Error things',
            ]);
        }

        return json_encode($response);
    }

    public function deleteCategory($id)
    {
        $this->communityCategoryRepository()->delete($id);

        return '1';
    }

    public function editCategory(Request $request)
    {
        $id = $request->get('id');
        $name = $request->get('title');
        $category = $this->communityCategoryRepository()->editCategory($id, $name);

        return $category->title;
    }

    public function surveyForm($slug, $form_slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $form = $this->communityFormsRepository()->getByCommunityIdSlug($this->community->id, $form_slug);

        if ($form) {
            $canViewLink = false;

            if ($this->community->timezone) {
                $timezone = $this->community->timezone;
                date_default_timezone_set($timezone);
            }

            $sdate = '';
            if ($form->survey_start_date) {
                $sdate = date('M d Y H:i:s', strtotime($form->survey_start_date));
            }

            $edate = '';
            if ($form->survey_end_date) {
                $edate = date('M d Y H:i:s', strtotime($form->survey_end_date));
            }

            if ($this->community->present()->isAdmin() || ($sdate == '' and $edate == '')) {
                $canViewLink = true;
            } else {
                if (time() >= strtotime($sdate) and time() <= strtotime($edate)) {
                    $canViewLink = true;
                }
            }

            if ($form->status == 0) {
                if (\Auth::check()) {
                    if ($this->community->present()->isAdmin() || \Auth::user()->id == $form->user_id) {

                    } else {
                        return redirect($this->community->present()->url());
                    }
                } else {
                    return redirect($this->community->present()->url());
                }
            }

            $community = $this->community;
            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }

            $this->theme->share('ogUrl', $community->present()->url('').'/sform/'.$form->slug);

            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            if ($form->nomination_banner) {
                $this->theme->share('ogImage', \Image::url($form->nomination_banner));
            }

            $this->theme->share('ogTitle', strip_tags($form->title));

            $this->theme->share('site_description', strip_tags($form->nomination_banner_texts));

            $categories = $this->communityFormsCategoryRepository()->getByFormIdAll($form->id);

            if ($val = $request->get('val')) {
                $data = $this->communityFormsAnswersRepository()->addResult($val, $this->community->id, $form->id, $this->community->present()->isAdmin());

                if ($data) {
                    if ($form->message_to_nominators) {
                        $message = $form->message_to_nominators;
                    } else {
                        $message = trans('formsurveys.nomination-success-default');
                    }
                    \Session::flash('success_form', $message);
                } else {
                    $message = trans('formsurveys.nomination-submit-error');
                    \Session::flash('success_form', $message);
                }

                return redirect($this->community->present()->url('sform').'/'.$form->slug);
            }

            /*if($form->login_required_for_action==1){
                $isSubmited="";
                if(\Auth::check()){
                    $isSubmited=$this->communityFormsAnswersRepository()->getByUserId($form->id);
                }
            }else{
                $isSubmited=$this->communityFormsAnswersRepository()->getByIpForm($form->id);
            }*/

            $isSubmited = '';
            if (\Auth::check()) {
                if (! $this->community->present()->isAdmin()) {
                    $isSubmited = 'yes';
                    $categories = $this->communityFormsCategoryRepository()->getByFormIdAll($form->id);
                    if (count($categories) > 0) {
                        foreach ($categories as $category) {
                            $hasSubmitedByCategory = $this->communityFormsAnswersRepository()->hasSubmitedByCategory($form->id, $category->id);
                            if (! $hasSubmitedByCategory) {
                                $isSubmited = '';
                            }
                        }
                    } else {
                        $isSubmited = '';
                    }
                }
            }

			$page_header = $this->communityPagesRepository()->getByIdComIdHeader('award',$this->community->id);	
			
            return $this->render('community.survey.longform', [
                'form' => $form,
                'categories' => $categories,
                'isSubmited' => $isSubmited,
                'community' => $community,
                'canViewLink' => $canViewLink,
				'page_header'=>$page_header,
            ], [
                'title' => $this->setTitle(''),
            ]);
        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function voting($slug, $form_slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $form = $this->communityFormsRepository()->getByCommunityIdSlug($this->community->id, $form_slug);

        // if($form){
        /*$canViewLink=false;
        if($form and ($form->activate_voting_link==1 ||  $this->community->present()->isAdmin())){
            $canViewLink=true;
        }*/

        /*$canViewLink=false;
        if($form)
        {
            if($this->community->timezone){
                $timezone=$this->community->timezone;
                date_default_timezone_set($timezone);
            }

            $sdate="";
            if($form->voting_start_date){
                $sdate=date('Y-m-d H:i:s',strtotime($form->voting_start_date));
            }

            $edate="";
            if($form->voting_end_date){
                $edate=date('Y-m-d H:i:s',strtotime($form->voting_end_date));
            }

            if($this->community->present()->isAdmin() || ($sdate=="" and $edate=="")){
                $canViewLink=true;
            }else{
                if(time() >= strtotime($sdate) and time() <= strtotime($edate)){
                    $canViewLink=true;
                }
            }
        }*/

        if ($form) {
            $community = $this->community;
            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }

            if ($form->status == 0) {
                if (\Auth::check()) {
                    if ($this->community->present()->isAdmin() || \Auth::user()->id == $form->user_id) {

                    } else {
                        return redirect($this->community->present()->url());
                    }
                } else {
                    return redirect($this->community->present()->url());
                }
            }

            $this->theme->share('ogUrl', $community->present()->url('').'/voting/'.$form->slug);
            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            if ($form->voting_banner) {
                $this->theme->share('ogImage', \Image::url($form->voting_banner));
            }

            $this->theme->share('ogTitle', strip_tags($form->title));

            $this->theme->share('site_description', strip_tags($form->title));

            $categories = $this->communityFormsCategoryRepository()->getByFormIdAll($form->id);
			$page_header = $this->communityPagesRepository()->getByIdComIdHeader('award',$this->community->id);	
			
            return $this->render('community.survey.voting.categories', [
                'form' => $form,
                'categories' => $categories,
                'community' => $community,
				'page_header'=>$page_header
            ], [
                'title' => $this->setTitle(''),
            ]);

        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function votingcategory($slug, $form_slug, $category_id, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $form = $this->communityFormsRepository()->getByCommunityIdSlug($this->community->id, $form_slug);
        $category = $this->communityFormsCategoryRepository()->getById($category_id, $this->community->id);

        // if($form and $category){
        /*$canViewLink=false;
        if($form and $category and($form->activate_voting_link==1 || $this->community->present()->isAdmin())){
            $canViewLink=true;
        }*/

        if ($form) {
            $canViewLink = false;

            if ($this->community->timezone) {
                $timezone = $this->community->timezone;
                date_default_timezone_set($timezone);
            }

            $sdate = '';
            if ($form->voting_start_date) {
                $sdate = date('M d Y H:i:s', strtotime($form->voting_start_date));
            }

            $edate = '';
            if ($form->voting_end_date) {
                $edate = date('M d Y H:i:s', strtotime($form->voting_end_date));
            }

            if ($this->community->present()->isAdmin() || ($sdate == '' and $edate == '')) {
                $canViewLink = true;
            } else {
                if (time() >= strtotime($sdate) and time() <= strtotime($edate)) {
                    $canViewLink = true;
                }
            }

            $community = $this->community;
            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }

            if ($form->status == 0) {
                if (\Auth::check()) {
                    if ($this->community->present()->isAdmin() || \Auth::user()->id == $form->user_id) {

                    } else {
                        return redirect($this->community->present()->url());
                    }
                } else {
                    return redirect($this->community->present()->url());
                }
            }

            $this->theme->share('ogUrl', $community->present()->url('').'/voting/'.$form->slug);

            if ($form->voting_banner) {
                $this->theme->share('ogImage', \Image::url($form->voting_banner));
            }

            $this->theme->share('ogTitle', strip_tags($form->title));

            $this->theme->share('site_description', strip_tags($form->title));
            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            $answers = $this->communityFormsAnswersRepository()->getAnswersByCategoryWithNominations($form->id, $category_id, $form->nomination_limit);

            if ($val = $request->get('val')) {
                $data = $this->communityFormsAnswersVotingRepository()->addVote($val, $this->community->id, $form->id, $category->id);

                if ($form->message_to_voters) {
                    $message = $form->message_to_voters;
                } else {
                    $message = 'Successfully submitted. Thank you for your vote!';
                }

                \Session::flash('success_form_msg', $message);

                // return $message;

                return redirect($this->community->present()->url('votingcategory').'/'.$form->slug.'/'.$category_id);
            }

            /*if($form->login_required_for_action==1){
                $isSubmited="";
                if(\Auth::check()){
                    $isSubmited=$this->communityFormsAnswersVotingRepository()->getByUserId($category_id);
                }
            }else{
                $isSubmited=$this->communityFormsAnswersVotingRepository()->getByIpCategory($category_id);
            }*/

            $isSubmited = '';
            if ($form->login_required_for_voting == 1) {
                if (\Auth::check()) {
                    $isSubmited = $this->communityFormsAnswersVotingRepository()->getByUserId($category_id);
                }
            }

            $categories = $this->communityFormsCategoryRepository()->getByFormIdAll($form->id);

            return $this->render('community.survey.voting.voting', [
                'form' => $form,
                'category' => $category,
                'answers' => $answers,
                'categories' => $categories,
                'isSubmited' => $isSubmited,
                'community' => $community,
                'canViewLink' => $canViewLink,
            ], [
                'title' => $this->setTitle(''),
            ]);

        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function getBusinessNames($slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        $term = $request->get('term');
        $pages = $this->pageRepository()->getNamesByCommunity($term, $this->community->id);
        $return_arr = [];
        foreach ($pages as $page) {
            $return_arr[] = ['value' => ucwords($page), 'label' => ucwords($page)];
        }

        return json_encode($return_arr);
    }

    public function form($slug, $form_slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $form = $this->communityFormsRepository()->getByCommunityIdSlug($this->community->id, $form_slug);

        if ($form) {

            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $community->title);
            $this->theme->share('ogTitle', $community->title);

            if ($community->present()->getLogo()) {
                $this->theme->share('ogImage', $community->present()->getLogo());
            } else {
                $this->theme->share('ogImage', $community->present()->getLogoAvatar());
            }

            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            $this->theme->share('site_description', $community->title);

            /*if(!$this->community->present()->isAdmin() and $form->status==0){
                return redirect($this->community->present()->url());
            }*/

            if ($form->type == 0) {
                $fields = $this->customFieldRepository()->getFormFieldAll('community-form', $this->community->id, $form->id);

                $message = '';
                if ($val = $request->get('val')) {
                    $data = $this->communityFormsSubmittedRepository()->saveData($val, $this->community->id, $form->id);
                    if ($data) {
                        $message = 'You have submitted successfully. Please allow time to respond to your application.';
                        \Session::flash('success_form', $message);
                    } else {
                        // $message="Something went wrong, please try again later.!";
                    }
                }

                $isSubmited = '';

                /*if($form->login_required_for_action==1){
                    if(\Auth::check()){
                        $isSubmited=$this->communityFormsSubmittedRepository()->getByUserId($form->id);
                    }
                }
                */
                return $this->render('community.forms.form', [
                    'form' => $form,
                    'fields' => $fields,
                    'isSubmited' => $isSubmited,
                    'community' => $community,
                ], [
                    'title' => $this->setTitle(''),
                ]);
            } else {
                return redirect($this->community->present()->url('sform').'/'.$form->slug);
            }
        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function trackCommunityCampaingEmail($code)
    {
        $this->communityCampaignEmailsSentRepository()->trackCommunityCampaingEmail($code);
        $path = \Theme::asset()->img('theme/images/track.png');

        header('Content-Type: image/png');
        readfile($path);
    }

    public function infoPage($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        return $this->render('community.pannel.cms.infopage', [
            'community' => $community,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function survey($slug, $survey_slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $survey = $this->communitySurveysRepository()->getByCommunityIdSlug($survey_slug, $this->community->id);

        if ($survey and $survey->is_deleted == 0 and $survey->community_id == $this->community->id) {

            $community = $this->community;
            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }

            // $questions=$this->communitySurveyQuestionsRepository()->getQuestions($survey->id,$this->community->id);

            if (! \Auth::check() and $survey->only_for_group != 0) {
                return redirect($this->community->present()->url());
            }

            if ($survey->only_for_group != 0 and \Auth::check()) {
                if (($survey->group_id and $this->community->present()->canViewCategory($survey->group_id)) || ($survey->admin_group_id and $this->community->present()->canManageGroup($survey->admin_group_id))) {

                } else {
                    $canViewCategory = $this->community->present()->canViewCategory($survey->only_for_group);

                    if (! $canViewCategory) {
                        return redirect($this->community->present()->url());
                    }
                }
            }

            $canViewLink = false;

            $sdate = '';
            if ($survey->survey_start_date != '0000-00-00 00:00:00') {
                $sdate = date('M d Y H:i:s', strtotime($survey->survey_start_date));
            }

            $edate = '';
            if ($survey->survey_end_date != '0000-00-00 00:00:00') {
                $edate = date('M d Y H:i:s', strtotime($survey->survey_end_date));
            }

            if ($this->community->present()->isAdmin() || ($sdate == '' and $edate == '')) {
                $canViewLink = true;
            } else {

                if ($sdate != '' and $edate != '' and time() >= strtotime($sdate) and time() <= strtotime($edate)) {
                    $canViewLink = true;
                } elseif ($sdate != '' and $edate == '' and time() >= strtotime($sdate)) {
                    $canViewLink = true;
                }
            }

            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $survey->title);
            $this->theme->share('ogTitle', $survey->title);

            if ($survey->header_image) {
                $this->theme->share('ogImage', \Image::url($survey->header_image));
            } else {
                if ($community->present()->getLogo()) {
                    $this->theme->share('ogImage', $community->present()->getLogo());
                } else {
                    $this->theme->share('ogImage', $community->present()->getLogoAvatar());
                }
            }

            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
            $this->theme->share('site_description', $survey->title);
            $questions = $this->communitySurveyQuestionsRepository()->getMainQuestions($survey->id, $this->community->id);

            if ($request->get('val') || isset($_FILES['documents'])) {
                $survey_id = '';

                if ($survey->activate_captcha == 1) {
                    $val = $request->get('val');
                    $verifyToken = '';

                    if (is_array($val) && array_key_exists('captcha_slider_verify', $val)) {
                        $verifyToken = trim((string) $val['captcha_slider_verify']);
                    } else {
                        $verifyToken = trim((string) $request->input('captcha_slider_verify', ''));
                    }

                    if ($verifyToken === '') {
                        $message = 'Please complete security verification.';
                        \Session::put('captcha_error_msg', $message);
                        \Session::put('survey_submit_msg', '');

                        return redirect($this->community->present()->url('survey').'/'.$survey->slug);
                    }

                    $verifiedAt = (int) $request->session()->get('slider_captcha_verified:'.$verifyToken, 0);
                    if ($verifiedAt <= 0 || (time() - $verifiedAt) > 10 * 60) {
                        $message = 'Please complete security verification.';
                        \Session::put('captcha_error_msg', $message);
                        \Session::put('survey_submit_msg', '');

                        return redirect($this->community->present()->url('survey').'/'.$survey->slug);
                    }

                    // single-use token
                    $request->session()->forget('slider_captcha_verified:'.$verifyToken);
                }

                $this->communitySurveyAnswersRepository()->addAnswer($request->get('val'), $survey->id, $this->community->id, $community, $survey);

                if ($survey->submit_success_message) {
                    $message = $survey->submit_success_message;
                } else {
                    $message = 'You have submitted successfully. Thank you for your participation.';
                }

                \Session::flash('success_form', $message);

                /*if($survey->submit_redirect_link){
                    return redirect($survey->submit_redirect_link);
                }else{
                    return redirect($this->community->present()->url('survey')."/".$survey->slug);
                }*/

                \Session::put('captcha_error_msg', '');

                \Session::put('survey_submit_msg', $message);

                return redirect($this->community->present()->url('survey').'/'.$survey->slug);
            }

			$page_header = $this->communityPagesRepository()->getByIdComIdHeader('surveys',$this->community->id);
			
            return $this->render('community.survey.survey', [
                'survey' => $survey,
                'community' => $community,
                'questions' => $questions,
                'canViewLink' => $canViewLink,
				'page_header'=>$page_header
            ], [
                'title' => $this->setTitle(''),
            ]);
        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function irProfilePage($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }
        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        return $this->render('community.pannel.cms.irprofile', [
            'community' => $community,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function businessPage($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        return $this->render('community.pannel.cms.businesspage', [
            'community' => $community,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function getSubQuestion($slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $id = $request->get('id');
        $question = $this->communitySurveyQuestionsRepository()->getByOptionId($id, $this->community->id);
        if ($question and $question->question != '') {
            return (string) $this->theme->section('community.survey.option-subquestion', ['question' => $question]);
        } else {
            return '';
        }
    }

    public function competition($slug, $competition_slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $competition = $this->communityCompetitionRepository()->getByCommunityIdSlug($competition_slug, $this->community->id);

        if ($competition and $competition->community_id == $this->community->id and $competition->disabled == 0) {
            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $community->title);
            $this->theme->share('ogTitle', $community->title);

            if ($community->present()->getLogo()) {
                $this->theme->share('ogImage', $community->present()->getLogo());
            } else {
                $this->theme->share('ogImage', $community->present()->getLogoAvatar());
            }

            $this->theme->share('site_description', $community->title);

            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            $category = $this->communityCategoryRepository()->get($competition->group_id, $this->community->id);
            if ($category and $category->allow_competitions == 1) {

                $community = $this->community;
                $hasSubmited = '';
                if (! \Auth::check()) {
                    $this->communityOutsideTheme($community);
                } else {
                    $hasSubmited = $this->foodRepository()->geByCommunityId($this->community->id, $competition->id);
                }

                $winner = '';
                if ($competition->show_selected == 1) {
                    $winner = $this->foodRepository()->geByCommunityCompetitionWinner($this->community->id, $competition->id);
                }

                return $this->render('community.competition.competition', [
                    'competition' => $competition,
                    'community' => $community,
                    'hasSubmited' => $hasSubmited,
                    'food' => $winner,
                ], [
                    'title' => $this->setTitle(''),
                ]);
            }
        }

        return redirect($this->community->present()->url());
    }

    public function competitionFinalist($slug, $competition_slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $competition = $this->communityCompetitionRepository()->getByCommunityIdSlug($competition_slug, $this->community->id);

        if ($competition and $competition->community_id == $this->community->id and $competition->disabled == 0) {
            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $community->title);
            $this->theme->share('ogTitle', $community->title);

            if ($community->present()->getLogo()) {
                $this->theme->share('ogImage', $community->present()->getLogo());
            } else {
                $this->theme->share('ogImage', $community->present()->getLogoAvatar());
            }

            $this->theme->share('site_description', $community->title);

            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            $category = $this->communityCategoryRepository()->get($competition->group_id, $this->community->id);
            if ($category and $category->allow_competitions == 1) {
                $community = $this->community;
                $hasSubmited = '';
                if (! \Auth::check()) {
                    $this->communityOutsideTheme($community);
                }

                $foods = '';
                if ($competition->show_selected == 1) {
                    $foods = $this->foodRepository()->geByCommunityCompetitionSelectedAll($this->community->id, $competition->id);
                }

                return $this->render('community.competition.competition-finalist', [
                    'competition' => $competition,
                    'community' => $community,
                    'hasSubmited' => $hasSubmited,
                    'foods' => $foods,
                ], [
                    'title' => $this->setTitle(''),
                ]);
            }
        }

        return redirect($this->community->present()->url());
    }

    public function topicApplication($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->present()->canJoinBusinessApplication() == 0) {
            return redirect($community->present()->url());
        }

        if ($val = $request->get('val')) {

            $email_address = $val['email'];
            $application_user = null;

            $captcha_code = $val['captcha_code'];
            if (! $captcha_code || ! isset($_SESSION['captcha_code'])) {
                $message = 'No captcha provided.';
                \Session::put('topic_success_message', $message);

                return redirect($community->present()->url('applybusiness'));
            }

            $created_captcha_code = $_SESSION['captcha_code'];

            if ($captcha_code != $created_captcha_code) {
                $message = 'Invalid captcha code.';
                \Session::put('topic_success_message', $message);

                return redirect($community->present()->url('applybusiness'));
            }

            $available = $this->communityCategoryRepository()->exists($community->id, $val['topic_name']);
            if ($available) {
                $message = 'Name already taken, use another name.';
                \Session::put('topic_success_message', $message);

                return redirect($community->present()->url('applybusiness'));
            }

            if (\Auth::check()) {
                $application_user = \Auth::user();
            }

            if (! \Auth::check() and $email_address) {
                $user = $this->userRepository()->findByBothEmail($email_address);

                if ($user) {
                    $application_user = $user;
                } else {
                    $community_id = $community->id;
                    $username = explode('@', $email_address);
                    if (isset($username[0])) {
                        $username = $username[0];
                    }

                    $first_name = $val['first_name'];
                    $last_name = $val['last_name'];

                    $full_name = $first_name.' '.$last_name;

                    $userVals = [
                        'username' => $username,
                        'email_address' => $email_address,
                        'fullname' => $full_name,
                        'communityId' => $community_id,
                        'type' => 'autosignup',
                        'is_active' => 0,
                        'signup_type' => 'topic_application_create',
                        'signup_type_id' => $community->id,
                    ];

                    $user = $this->userRepository()->appointmentSignup($userVals);
                    if ($user) {
                        $user->first_name = $first_name;
                        $user->last_name = $last_name;
                        $user->save();
                        $application_user = $user;
                    }
                }
            }

            $application = $this->communityCategoryApplicationsRepository()->add($val, $community->id, $application_user);

            if ($application) {

                $business_data = [
                    'title' => $val['topic_name'],
                    'description' => $val['organization_name'],
                    'website' => $val['web_url'],
                    'category' => '',
                    'business_email' => $val['email'],
                    'business_contact' => $val['contact'],
                    'country' => $val['country'],
                    'state' => $val['state'],
                    'city' => $val['city'],
                    'street' => $val['address'],
                    'zip' => $val['zip'],
                    'container_color' => '',
                    'container_transparancy' => '',
                    'community_id' => $community->id,
                    'subcategory' => '',
                    'page_type' => 0,
                    'status' => 0,
                    'full_address' => $val['address'],
                    'latitude' => $val['latitude'],
                    'longitude' => $val['longitude'],
                ];

                $this->pageRepository()->uploadBusinesses($business_data, $application_user->id, $community->id, $application_user->id);

                $message = 'Application submitted successfully. Your application will be reviewed and will updated you soon!';
                \Session::put('topic_success_message', $message);
            } else {
                $message = 'Ops! not submitted. Something went wrong,try again.';
                \Session::put('topic_success_message', $message);
            }

            return redirect($community->present()->url('applybusiness'));
        }

        $profileCompleted = 1;
        if (\Auth::check()) {
            $profileCompleted = $this->userRepository()->checkUserProfile();
        } else {
            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

        return $this->render('community.topics.application', [
            'community' => $community,
            'profileCompleted' => $profileCompleted,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function centerApplication($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($val = $request->get('val')) {

            $email_address = $val['email'];
            $application_user = null;

            $captcha_code = $val['captcha_code'];
            if (! $captcha_code || ! isset($_SESSION['captcha_code'])) {
                $message = 'No captcha provided.';
                \Session::put('center_success_message', $message);

                return redirect($community->present()->url('applycenter'));
            }

            $created_captcha_code = $_SESSION['captcha_code'];

            if ($captcha_code != $created_captcha_code) {
                $message = 'Invalid captcha code.';
                \Session::put('center_success_message', $message);

                return redirect($community->present()->url('applycenter'));
            }

            if (! \Auth::check() and $email_address) {
                $user = $this->userRepository()->findByBothEmail($email_address);

                if ($user) {
                    $application_user = $user;
                } else {
                    $community_id = $community->id;
                    $username = explode('@', $email_address);
                    if (isset($username[0])) {
                        $username = $username[0];
                    }

                    $first_name = $val['first_name'];
                    $last_name = $val['last_name'];

                    $full_name = $first_name.' '.$last_name;

                    $userVals = [
                        'username' => $username,
                        'email_address' => $email_address,
                        'fullname' => $full_name,
                        'communityId' => $community_id,
                        'type' => 'autosignup',
                        'is_active' => 0,
                        'signup_type' => 'center_application_create',
                        'signup_type_id' => $community->id,
                    ];

                    $user = $this->userRepository()->appointmentSignup($userVals);
                    if ($user) {
                        $user->first_name = $first_name;
                        $user->last_name = $last_name;
                        $user->save();
                        $application_user = $user;
                    }
                }
            }

            $application = $this->communityCategoryApplicationsRepository()->addCenter($val, $community, $application_user);

            if ($application) {
                $message = 'Application submitted successfully. Your application will be reviewed and will updated you soon!';
                \Session::put('center_success_message', $message);
            } else {
                $message = 'Ops! not submitted. Something went wrong,try again.';
                \Session::put('center_success_message', $message);
            }

            return redirect($community->present()->url('applycenter'));
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

        $profileCompleted = 1;

        return $this->render('community.center.application', [
            'community' => $community,
            'profileCompleted' => $profileCompleted,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function myTopicApplications($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $myApplications = $this->communityCategoryApplicationsRepository()->myApplications($community->id);

        return $this->render('community.topics.my-applications', [
            'community' => $community,
            'myApplications' => $myApplications,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function editTopicApplication($slug, $id, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $application = $this->communityCategoryApplicationsRepository()->getById($community->id, $id);

        if ($application->user_id !== \Auth::user()->id) {
            return redirect('home');
        }

        if ($val = $request->get('val')) {
            $application = $this->communityCategoryApplicationsRepository()->edit($val, $application, $community->id);

            if ($application) {
                $message = 'Application updated successfully.';
                \Session::flash('success_message', $message);
            } else {
                $message = 'Ops! not submitted. Something went wrong,try again.';
                \Session::flash('success_message', $message);
            }

            return redirect($community->present()->url('edittopicapplication').'/'.$id);
        }

        return $this->render('community.topics.edit-application', [
            'community' => $community,
            'application' => $application,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function checkTopicAvailability($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        $name = $request->get('name');

        $available = $this->communityCategoryRepository()->exists($community->id, $name);
        if ($available) {
            return 0;
        }

        return 1;
    }

    public function personalBranding($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community || $slug != '89') {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        $this->theme->share('ogUrl', $community->present()->url());
        $this->theme->share('ogSiteName', $community->title);
        $this->theme->share('ogTitle', $community->title);

        if ($community->present()->getLogo()) {
            $this->theme->share('ogImage', $community->present()->getLogo());
        } else {
            $this->theme->share('ogImage', $community->present()->getLogoAvatar());
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

        $this->theme->share('site_description', $community->title);

        return $this->render('community.pannel.cms.personal-branding', [
            'community' => $community,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function viewSurveyMedia($slug, $qid)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        $this->theme->share('ogUrl', $community->present()->url());
        $this->theme->share('ogSiteName', $community->title);
        $this->theme->share('ogTitle', $community->title);

        if ($community->present()->getLogo()) {
            $this->theme->share('ogImage', $community->present()->getLogo());
        } else {
            $this->theme->share('ogImage', $community->present()->getLogoAvatar());
        }

        $this->theme->share('site_description', $community->title);
        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

        $question = $this->communitySurveyQuestionsRepository()->getById($qid, $community->id);

        return $this->render('community.survey.survey-question-media', [
            'community' => $this->community,
            'question' => $question,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function getSurveyBanners()
    {
        return (string) $this->theme->section('community.pannel.cms.surveys.survey-banners');
    }

    public function checkSurveyDuplicateEmail(Request $request)
    {
        $val = $request->get('val');
        $qid = $request->get('qid');
        $sid = $request->get('sid');

        $answer = $this->communitySurveyAnswersRepository()->checkSurveyDuplicateEmail($val, $qid, $sid);

        if ($answer) {
            return 1;
        }

        return 0;
    }

    public function getPersonaEmails(Request $request)
    {
        $category = $request->get('category');

        return $emails = $this->communityMembersEmailsRepository()->getAllByUser($category);
    }

    public function communityHome($slug)
    {
        if (\Auth::check() and $this->selected_pricing_plan_category_id!=3) {
            $community = $this->communityRepository()->getBySlug($slug);

			//return $redUrl = $community->present()->hasExpiredCommunity();
			
            if ($redUrl = $community->present()->hasExpiredCommunity()) {
                /*if ($redUrl instanceof \Symfony\Component\HttpFoundation\Response) {
                    return $redUrl;
                }*/

                return redirect($redUrl);
            }

            if (! isMobile()) {
                $getCommunityDomain = $community->present()->getCommunityDomain('o/'.$community->id.'/home');
                if (\Request::url() != $getCommunityDomain) {
                    // return redirect($getCommunityDomain);
                }
            }

            \Auth::user()->present()->saveVisitingCommunity($community->id);

            if ($community->gift_app_community == 1 || $this->selected_pricing_plan_type=='giftapp') {
                return redirect($community->present()->url('gifts/overview'));
            }	

            if (($community->race_community == 1 || $this->selected_pricing_plan_type=='racing')  and \Auth::user()->present()->hasRideProfileCompleted($community->id) != 'yes' and ! \Request::ajax()) {
                $communityRideProfileRedirect = \Auth::user()->present()->hasRideProfileCompleted($community->id);
                return redirect($communityRideProfileRedirect);
            }

            if ($community->community_access == 1 and $community->owner_community_access == 1) {
                $user = \Auth::user();
                if ($user->present()->canAccessSite() || ($community->present()->canShowCompleteProfilePage() == 0 and $community->present()->canShowOrgActivationCodePage() == 0) || (\Session::has('activationVisited') and \Session::get('activationVisited') == 'yes' and $community->present()->canShowCompleteProfilePage() == 0)) {
                    return $this->render('user.home.index', ['posted_community' => $community],
                        ['title' => $this->setTitle(trans('global.home'))]
                    );
                } else {

                    $loggedInCm = \Auth::user()->present()->getNewViewsCommunity();

                    $url = \URL::route('edit-profile');
                    if ($loggedInCm and ($loggedInCm->present()->canShowOrgActivationCodePage() == 0 || $loggedInCm->user_id == $user->id)) {

                        if ($loggedInCm->present()->canShowCompleteProfilePage() == 0) {
                            $profileRedirectUrl = \Auth::user()->present()->profileRedirectUrl();

                            return redirect($profileRedirectUrl);
                        } else {
                            $url = \URL::route('edit-profile');

                            return redirect($url);
                        }
                    }

                    return redirect($url);
                }
            } else {
                if ($community->id == 146) {
                    return redirect($community->present()->url('businesses'));
                } else {
                    $rdUrl = \URL::route('user-communities');
                    return redirect($rdUrl);
                }
            }
        } else {
            return redirect('home');
        }
    }

    public function page($slug, $page_slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $this->communityOutsideTheme($community);

        $this->theme->share('ogUrl', $community->present()->url());
        $this->theme->share('ogSiteName', $community->title);
        $this->theme->share('ogTitle', $community->title);

        if ($community->present()->getLogo()) {
            $this->theme->share('ogImage', $community->present()->getLogo());
        } else {
            $this->theme->share('ogImage', $community->present()->getLogoAvatar());
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

        $this->theme->share('site_description', $community->title);

        $page = $this->communityPagesRepository()->getByCommunityIdSlug($this->community->id, $page_slug);

        if ($page->status == 0 and (! $this->community->isOwner())) {
            return redirect($this->community->present()->url());
        }

        if ($page) {
            return $this->render('community.pages.page', [
                'page' => $page,
                'community' => $community,
            ], [
                'title' => $this->setTitle(''),
            ]);
        }

        return $this->notFound();
    }

    public function getYoutubeVimeoUrl(Request $request)
    {
        $url = $request->get('url');

        return generateVideoUrl($url);
    }

    public function crmLogin($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($community->present()->canHaveCrmAccess() == 0) {
            return redirect($this->community->present()->url());
        }

        return redirect(config('community-domain.crm-url').'/crm/'.\Auth::user()->id.'/'.$community->id.'?backurl='.$this->community->present()->url('activitydashboard'));
    }

    public function getOrganizationLogo($id)
    {
        $community = $this->communityRepository()->getById($id);
        if (! empty($community)) {
            return $community->present()->getLogo();
        }

        return false;
    }

    public function getorganizationLogoSmall($id)
    {
        $community = $this->communityRepository()->getById($id);
        if (! empty($community)) {
            return $community->present()->getLogoAvatar();
        }

        return false;
    }

    public function getorganizationFevicon($id)
    {
        $community = $this->communityRepository()->getById($id);
        if (! empty($community)) {
            return $community->present()->getFeviconAvatar();
        }

        return false;
    }

    public function myCart()
    {
        $cartCommunities = $this->businessProductsCartRepository()->getMyCartCommunity();

        return $this->render('user.my-cart', ['cartCommunities' => $cartCommunities]);
    }

    public function retrievePassword($slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if (\Auth::check()) {
            return redirect($community->present()->url());
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        $hash = $request->get('hash');

        if (empty($hash)) {
            return redirect($community->present()->url());
        }

        /* if ($user = $this->userRepository()->findByHash(['code' => $hash], FALSE)) { */
        $hashFind = $this->forgotPasswordRepository()->findHash($hash, $community->id);

        $user = $this->userRepository()->getById($hashFind);

        if ($user) {
            $message = null;
            if ($val = $request->get('val')) {
                $validator = \Validator::make($val, [
                    'password' => 'required|confirmed',
                ]);

                if ($validator->fails()) {
                    $message = $validator->messages()->first();

                } else {

                    $this->userRepository()->changePassword($val, $user);

                    $this->forgotPasswordRepository()->updateHash($hash, $community->id);

                    \Auth::login($user);

                    $cmUrl = $community->present()->url();

                    \Session::put('theCommunityId', $community->id);
                    \Session::put('community_url', $cmUrl);

                    if (\Auth::check()) {
                        saveUserSession();
                    }

                    return redirect($community->present()->url());
                }
            }

            return $this->theme->view('user.login.change-password', ['user' => $user, 'message' => $message])->render();
        } else {
            return $this->theme->view('user.login.invalid-hash', ['hashFind' => $hashFind])->render();
        }
    }

    public function getVisitorUsers(Request $request)
    {
        $community_id = $request->get('community_id');
        $viewdate = $request->get('viewdate');
        $user_id = $request->get('user_id');
        $ip_address = $request->get('ip_address');

        $community = $this->communityRepository()->getById($community_id);
        if ($community and $community->user_id == \Auth::user()->id) {
            $visitedPages = $this->siteVisitorsRepository()->getVisitedPagesByUser($community_id, $viewdate, $user_id, $ip_address);

            return $this->theme->section('community.pannel.visitors.user-pages', ['visitedPages' => $visitedPages]);
        }
    }

    public function usedSpaceCheck(Request $request)
    {
        $selectedFileSize = $request->get('selectedFileSize');
        $current_url = $request->get('current_url');
        $uriArray = explode('/', $current_url);

        $community_id = getVisitingCommunityId();

        if (isset($uriArray[3]) and isset($uriArray[4])) {
            $type = $uriArray[3];
            $type_id = $uriArray[4];

            if ($type == 'o' || $type == 'c') {

                if (isset($uriArray[5]) and $uriArray[5] == 'ownevents' and isset($uriArray[6]) and $uriArray[6] == 'edit') {
                    $event = $this->postEventsRepository()->getById($uriArray[7]);
                    $community_id = $event->community_id;
                } else {
                    $community_id = $type_id;
                }
            } elseif ($type == 'ip') {
                /*$community = $this->communityRepository()->getResumeCommunity();
                if ($community) {
                    $community_id = $community->id;
                }*/
                $community_id = 0;
            } elseif ($type == 'page' || $type == 'store') {
                $page = $this->pageRepository()->getBySlug($type_id);
				if($page){
               		 $community_id = $page->community_id;
				}	 
            } elseif ($type == 'post') {
                $post = $this->postRepository()->getById($type_id);
                if ($post->community_id) {
                    $community_id = $post->community_id;
                } elseif ($post->posted_in_community != 0 and $post->type == 'user-timeline') {
                    $community_id = $post->posted_in_community;
                } elseif ($post->page_id != 0 and $post->page_id > 0) {
                    $page = $this->pageRepository()->getBySlug($post->page_id);
                    $community_id = $page->community_id;
                } elseif ($post->type == 'resume') {
                    //$community = $this->communityRepository()->getResumeCommunity();
                    //$community_id = $community->id;
					$community_id = 0;
                }
            } elseif ($type == 'postarticle') {
                $community_id = $request->get('community_id');
                if (! $community_id) {
                    $posted_in_community = $request->get('posted_in_community');
                    if ($posted_in_community) {
                        $community_id = $posted_in_community;
                    }
                }
            }
        }

        if ($community_id){
			$community = app('App\\Repositories\\CommunityRepository')->getById($community_id);
            if($community) {
                 return checkAvailableSpace($community_id, $selectedFileSize);
            }
        }

        return 1;
    }

    public function uploadEditorImage(Request $request)
    {
        $response = [
            'code' => 0,
            'message' => trans('photo.error', ['size' => formatBytes()]),
            'url' => '',
        ];
        if (! $request->get('coverImg')) {
            return $response;
        }

        $data = $request->get('coverImg');
        $id = getVisitingCommunityId();

        $user = \Auth::user();

        if (! empty($data)) {

            try {
                $originalImage = $data;
                $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
                $img_name = Str::random(32).'.jpg';
                $img_url = 'uploads/users/'.$user->id.'/community/themes';
                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('/', $originalImage)[1])[0];
                $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($id, $file_original_size) == 0) {
                    $CDNRepository->deleteThisFile(public_path().'/'.$img);

                    return json_encode([
                        'code' => 0,
                        'status' => 'error',
                        'message' => 'No sufficient space available to upload.',
                    ]);
                }

                $newFileName = $CDNRepository->upload(public_path().'/'.$img, $img);
                $CDNRepository->deleteThisFile(public_path().'/'.$img);
                $img = $newFileName;

                $upload_key = Str::random(20);
                $fileArray = [
                    'community_id' => $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' => 'editor-upload-image',
                    'type_id' => 0,
                    'sub_type_id' => 0,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository()->save($fileArray);

                return json_encode([
                    'status' => 'success',
                    'url' => \Image::url($img),
                ]);
            } catch (\Exception $e) {
                return json_encode([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                ]);
            }
        } else {
            return json_encode([
                'status' => 'error',
                'message' => 'Error things',
            ]);
        }

        return json_encode($response);
    }

    public function getorganizationUrl($id)
    {
        $community = $this->communityRepository()->getById($id);
        if (! empty($community)) {
            return $community->present()->url();
        }

        return false;
    }

    public function uploadEditorVideo(Request $request)
    {
        $response = [
            'code' => 0,
            'message' => trans('photo.error', ['size' => formatBytes()]),
            'url' => '',
        ];
        if (! $request->get('coverVideo')) {
            return $response;
        }

        $data = $request->get('coverVideo');
        $upload_type = $request->get('upload_type');
        $id = getVisitingCommunityId();

        $user = \Auth::user();

        if (! empty($data)) {

            try {
                $originalImage = $data;
                $data = base64_decode(preg_replace('#^data:video/\w+;base64,#i', '', $data));
                $img_name = Str::random(32).'.mp4';
                $img_url = 'uploads/users/'.$user->id.'/community/themes';
                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('/', $originalImage)[1])[0];
                $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($id, $file_original_size) == 0) {
                    $CDNRepository->deleteThisFile(public_path().'/'.$img);

                    return json_encode([
                        'code' => 0,
                        'status' => 'error',
                        'message' => 'No sufficient space available to upload.',
                    ]);
                }

                $file_path = $img;
                $fileName = $img_name;

                $uploadPath = 'media/appvideo/'.$user->id.'/'.$fileName;

                $newFileName = $CDNRepository->upload(public_path().'/'.$file_path, $uploadPath, 'videoUpload', '480');

                $CDNRepository->deleteThisFile(public_path().'/'.$file_path);
                $file_path = $newFileName;

                $videoUrl = $CDNRepository->getVideoOutpuLinkMp4($file_path);
                $thumbnailUrl = $CDNRepository->getVideoThumbnail($file_path);

                $videoUrl = $videoUrl;

                $upload_key = Str::random(20);
                $fileArray = [
                    'community_id' => $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' => 'editor-upload-video',
                    'type_id' => 0,
                    'sub_type_id' => 0,
                    'upload_key' => $upload_key,
                ];
                $this->communitySpaceUsedRepository()->save($fileArray);

                if ($upload_type == 'box_video') {
                    $videoUrl = $newFileName;
                }

                return json_encode([
                    'status' => 'success',
                    'url' => $videoUrl,
                    'thumbnailUrl' => $thumbnailUrl,
                ]);
            } catch (\Exception $e) {
                return json_encode([
                    'status' => 'error',
                    'message' => $e->getMessage(),
                ]);
            }
        } else {
            return json_encode([
                'status' => 'error',
                'message' => 'Error things',
            ]);
        }

        return json_encode($response);
    }

    public function giftContribute($slug, $gift_id)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
        }

        $gift = $this->giftsRepository()->getByCmId($this->community->id, $gift_id);

        if ($gift) {

            if (\Auth::check()) {
                $hasContributed = app('App\\Repositories\\GiftsRepository')->hasContributed($gift->community_gift_id);
                if (! $hasContributed) {
                    if ($this->community->gift_collection_sequence == 0) {
                        $open_gift = $this->giftsRepository()->getCurrentOpenGift($community->id, $gift->community_gift_id);
                        if ($open_gift) {
                            $openGiftUrl = $community->present()->url('gifts/giftpurchase').'?selected_gift_id='.$open_gift->id;

                            return redirect($openGiftUrl);
                        }
                    } else {
                        if ($gift->total_amt_collected < $gift->required_money and $gift->has_money_collected == 0) {
                            $currentGiftUrl = $community->present()->url('gifts/giftpurchase').'?selected_gift_id='.$gift->id;

                            return redirect($currentGiftUrl);
                        } else {
                            $gift = $this->giftsRepository()->getOpenGiftByUser($community->id, $gift->community_gift_id, $gift->user_id);
                            if ($gift->total_amt_collected < $gift->required_money and $gift->has_money_collected == 0) {
                                $currentGiftUrl = $community->present()->url('gifts/giftpurchase').'?selected_gift_id='.$gift->id;

                                return redirect($currentGiftUrl);
                            }
                        }
                    }
                }
            }

            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $community->title);
            $this->theme->share('ogTitle', $community->title);

            if ($community->present()->getLogo()) {
                $this->theme->share('ogImage', $community->present()->getLogo());
            } else {
                $this->theme->share('ogImage', $community->present()->getLogoAvatar());
            }

            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());

            $this->theme->share('site_description', $community->title);

            $user_account = '';
            if (\Auth::check()) {
                $user_id = \Auth::user()->id;
                $user_account = $this->giftsAccountRepository()->getByUserIdCmId($community->id, $user_id);
            }

            return $this->render('community.gift.view', [
                'gift' => $gift,
                'community' => $community,
                'user_account' => $user_account,
            ], [
                'title' => $this->setTitle(''),
            ]);

        } else {
            return redirect($this->community->present()->url());
        }
    }

    public function changeBackgroungColor(Request $request)
    {
        $community_id = $request->get('community_id');
        $prmColor = $request->get('prmColor');
        $type = $request->get('type');

        $community = $this->communityRepository()->getById($community_id);
        if ($community->isOwner()) {
            if ($type == 'cm_title_bg_color') {
                $community->title_bg_color = $prmColor;
            } elseif ($type == 'cm_topic_bg_color') {
                $community->topic_bg_color = $prmColor;
            } elseif ($type == 'cm_bi_bg_color') {
                $community->bi_bg_color = $prmColor;
            } elseif ($type == 'cm_setting_bg_color') {
                $community->setting_bg_color = $prmColor;
            }

            $community->save();
        }
    }

    public function categoryPublicPosts($slug, $category)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($this->community);
        }

        $category = $this->communityCategoryRepository()->get($category, $this->community->id);

        if (empty($category)) {
            return redirect($this->community->present()->url());
        }

        $relevantPosts = $this->postRepository()->randomPostByCategory(0, $this->community->id, 'community', $category->id);

		$page_header = $this->communityPagesRepository()->getByIdComIdHeader('news',$this->community->id);
		
        return $this->render('community.category.blogs', [
            'posts' => $this->postRepository()->lists('communitycategory-'.$category->id, posted_in_community: $this->community->id),
            'typeId' => $category->id,
            'category_details' => $category,
            'community' => $this->community,
            'relevantPosts' => $relevantPosts,
			'page_header'=>$page_header,
        ], ['title' => $this->setTitle($category->title)]);
        if (! $this->exists()) {
            return $this->notFound();
        }
    }

    public function createOwnRedirect()
    {
        $user = \Auth::user();
        $user->incomplete_org_redirect_count = $user->incomplete_org_redirect_count + 1;
        $user->save();

        $desUrl = \URL::route('community-createown');

        return redirect($desUrl);
    }

    public function emailVerificationSuccess($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($this->community);
        }

        return $this->render('community.email-verification-success', ['community' => $this->community]);
    }

    public function emailVerificationFailed($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }
        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($this->community);
        }

        return $this->render('community.email-verification-failed', ['community' => $this->community]);
    }

    public function accountSuspended($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (\Auth::check() and $community) {

            if ($redUrl = $community->present()->hasExpiredCommunity()) {
                return redirect($redUrl);
            }

            if ($community->present()->isAccountSuspended()) {
                return $this->render('community.gift.account-suspended', ['community' => $community]);
            } else {
                return redirect($community->present()->url());
            }
        } else {
            return redirect('home');
        }
    }

    public function documentView($slug, $categoryid, $documentid)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $category = $this->communityCategoryRepository()->get($categoryid, $community->id);
        if (! $category) {
            return $this->notFound();
        }

        $document = $this->communityDocumentsRepository()->getByCmCatId($documentid, $community->id, $category->id);

        if (! $document) {
            return $this->notFound();
        }

        if (\Auth::check()) {
            $community = $this->communityRepository()->getBySlug($slug);

            if ($community->present()->canView() and $community->present()->canViewCategory($category->id)) {
                
				$this->communityDocumentsDownloadRepository()->saveDownload($community->id, $category->id, $documentid);
				
				$allowed_files = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'mp4', 'mov', 'mpg', 'flv', 'mp3', 'wav', 'ogg', 'aif', 'wma', 'mid'];

                if (in_array(strtolower($document->document_type), $allowed_files)) {
                    return $this->render('community.documents.view-document', ['community' => $community, 'document' => $document, 'category' => $category]);
                } else {
                    $file = $community->present()->getDocumentUrl($document->document_path);
                    DownloadAnything($file);
                }
            } else {
                return $this->render('community.documents.view-document', ['community' => $community, 'document' => '', 'category' => $category]);
            }

        } else {
            return redirect($community->present()->authUrl('login', ['urltype' => 'returnurl', 'returnUrl' => $community->present()->url('viewdocument').'/'.$document->category_id.'/'.$document->id]));
        }
    }

    public function documentViewOutside($slug, $categoryid, $documentid, Request $request)
    {
        $emailid = $request->get('emailid');

        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $category = $this->communityCategoryRepository()->get($categoryid, $community->id);
        if (! $category) {
            return $this->notFound();
        }

        $document = $this->communityDocumentsRepository()->getByCmCatId($documentid, $community->id, $category->id);

        if (! $document) {
            return $this->notFound();
        }

        if (\Auth::check()) {
            $community = $this->communityRepository()->getBySlug($slug);

            $canViewOutsideDocument = $community->present()->canViewOutsideDocument($document->id);
			
            if ($canViewOutsideDocument) {
			
				$this->communityDocumentsDownloadRepository()->saveDownload($community->id, $category->id, $documentid);
			
                $allowed_files = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'mp4', 'mov', 'mpg', 'flv', 'mp3', 'wav', 'ogg', 'aif', 'wma', 'mid'];

                if (in_array(strtolower($document->document_type), $allowed_files)) {
                    return $this->render('community.documents.view-document-outside', ['community' => $community, 'document' => $document, 'category' => $category]);
                } else {
                    $file = $community->present()->getDocumentUrl($document->document_path);
                    DownloadAnything($file);
                }
            } else {
                return $this->render('community.documents.view-document-outside', ['community' => $community, 'document' => '', 'category' => $category]);
            }

        } else {
            return redirect($community->present()->authUrl('login', ['urltype' => 'returnurl', 'returnUrl' => $community->present()->url('viewdocumentoutside').'/'.$document->category_id.'/'.$document->id, 'emailid' => $emailid]));
        }
    }

    public function makeUserActivate(Request $request)
    {
        $activate = $request->get('activate');
        $userId = $request->get('userId');
        $communityId = $request->get('communityId');

        $logged_user_id = \Auth::user()->id;

        $community = $this->communityRepository()->getById($communityId);
        if ($community and $logged_user_id == $community->user_id) {
            $userData = $this->userRepository()->getById($userId);
            if ($userData and $userData->community_signup == $community->id) {
                $userData->active = $activate;
                $userData->activated = $activate;
                $userData->save();
            }
        }
    }

    public function rideBook($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        if (($community->race_community == 1 || $this->selected_pricing_plan_type=='racing') and \Auth::user()->present()->hasRideProfileCompleted($community->id) != 'yes' and ! \Request::ajax()) {
            // $communityRideProfileRedirect=\URL::route('community-ride-completeprofile',['slug'=>$community->id]);
            $communityRideProfileRedirect = \Auth::user()->present()->hasRideProfileCompleted($community->id);

            return redirect($communityRideProfileRedirect);
        }

        $slots = $this->communityRideTimeslotsRepository()->getAllSlots($community->id);

        return $this->render('user.ridebooking.index', ['posted_community' => $community, 'slots' => $slots],
            ['title' => 'Book a Ride']
        );
    }

    public function rideCompleteProfile($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $user_id = \Auth::user()->id;
        $user = \Auth::user();

        $first_name = $request->get('first_name');
        $last_name = $request->get('last_name');
        $email_address = $request->get('email_address');
        $year_of_birth = $request->get('year_of_birth');
        $weight = $request->get('weight');
        $weight_in = $request->get('weight_in');
        if (! $weight_in) {
            $weight_in = 'lb';
        }

        $height = $request->get('height');
        $height_in = $request->get('height_in');
        if (! $height_in) {
            $height_in = 'cm';
        }
        $gender = $request->get('gender');
        // $cell_no = $request->get('cell_no');
        $cell_no = $request->get('phoneNumber');
        $defaultCountry = $request->get('defaultCountry');
        $carrierCode = $request->get('carrierCode');
        $preferred_location = $request->get('preferred_location');

        if ($first_name != '' and $last_name != '') {
            $user->first_name = $first_name;
            $user->last_name = $last_name;
            $user->fullname = $first_name.' '.$last_name;
            // $user->email_address=$email_address;
            $user->birth_year = $year_of_birth;
            $user->weight = $weight;
            $user->weight_in = $weight_in;
            $user->height = $height;
            $user->height_in = $height_in;
            $user->genre = $gender;
            $user->phone_number = $cell_no;
            $user->country_iso_code = $defaultCountry;
            $user->carrier_code = $carrierCode;

            $user->ride_profile_completed = 1;

            $user->preferred_location = $preferred_location;
            $user->ride_address_completed = 1;
            $user->ride_profile_completed_on = date('Y-m-d');
            $user->save();

            $this->userRepository()->sendRideCouponCode($user, $community->id);

            $communityHome = \URL::route('community-home', ['slug' => $community->id]);

            return redirect($communityHome);
        }

        $organizationDetails = $this->usersOrganizationRepository()->getByUserId($user_id);
        $locations = $this->communityRideLocationsRepository()->getAllLocations($community->id);

        $myActivelocations = $this->communityRideLocationsRepository()->myActivelocations($community->id, $user_id);
        $mobileNumber = '';
        if ($myActivelocations) {
            $application = $this->communityCategoryApplicationsRepository()->getById($community->id, $myActivelocations->application_id);
            if ($application) {
                $mobileNumber = $application->contact;
            }
        }

        if ($user->preferred_location) {
            $myActivelocations = $this->communityRideLocationsRepository()->getById($community->id, $user->preferred_location);
        }

        return $this->render('user.ridebooking.complete-profile', ['user' => $user, 'posted_community' => $community, 'organizationDetails' => $organizationDetails, 'locations' => $locations, 'myActivelocations' => $myActivelocations, 'mobileNumber' => $mobileNumber],
            ['title' => 'Complete Profile']
        );
    }

    public function rideCompleteAddress($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $user_id = \Auth::user()->id;
        $user = \Auth::user();

        if ($user->ride_profile_completed == 0) {
            return redirect(\URL::route('community-ride-completeprofile', ['slug' => $community->id]));
        }

        $address = $request->get('address');
        $city = $request->get('city');
        $country = $request->get('country');
        $zip_code = $request->get('zip_code');
        $preferred_location = $request->get('preferred_location');
        $preferred_language = $request->get('preferred_language');

        // if($country!="" and $zip_code!="" and $preferred_location!=""){
        // if($country!="" and $city!="" and $preferred_location!=""){
        if ($preferred_location != '') {

            // Do not save language into user table; store into userselected table.
            // Save exactly one row based on visiting community.
            try {
                $lang = strtolower(trim((string) $preferred_language));
                if ($lang === '') {
                    $lang = 'en';
                }
                $this->userLanguageSelectedRepository()->upsertForUserAndCommunity((int) $user->id, (int) $community->id, $lang);
                \Session::put('lang', $lang);
                \Session::put('lang_c_' . (int) $community->id, $lang);
                \Session::put('current-language', $lang);
            } catch (\Throwable $e) {
                // ignore
            }

            $val = [
                'working_org_address' => $address,
                'working_org_city' => $city,
                'working_org_country' => $country,
                'working_org_zip' => $zip_code,
            ];

            $this->usersOrganizationRepository()->updateMyOrganization($user->id, $val);

            $user->preferred_location = $preferred_location;
            $user->ride_address_completed = 1;
            $user->ride_profile_completed_on = date('Y-m-d');
            $user->save();

            $this->userRepository()->sendRideCouponCode($user, $community->id);

            $communityHome = \URL::route('community-home', ['slug' => $community->id]);

            return redirect($communityHome);
        }

        $organizationDetails = $this->usersOrganizationRepository()->getByUserId($user_id);
        $locations = $this->communityRideLocationsRepository()->getAllLocations($community->id);

        return $this->render('user.ridebooking.complete-address', ['user' => $user, 'posted_community' => $community, 'organizationDetails' => $organizationDetails, 'locations' => $locations],
            ['title' => 'Complete Profile']
        );
    }

    // public function rideBooking($slug,$slot_id)
    public function rideBooking($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        if (($community->race_community == 1 or $this->selected_pricing_plan_type=='racing') and \Auth::user()->present()->hasRideProfileCompleted($community->id) != 'yes' and ! \Request::ajax()) {
            $communityRideProfileRedirect = \Auth::user()->present()->hasRideProfileCompleted($community->id);

            return redirect($communityRideProfileRedirect);
        }

        // $slot_id=0;
        // $slot=$this->communityRideTimeslotsRepository()->getById($community->id,$slot_id);
        $locations = $this->communityRideLocationsRepository()->getLocations($community->id);

        $slots = $this->communityRideTimeslotsRepository()->getAllSlots($community->id);

        return $this->render('user.ridebooking.booking',
            ['posted_community' => $community,
                'locations' => $locations,
                'slots' => $slots,
                'pagetype' => 'allbooking',
                'selected_location' => '',
                'location_sims' => '',
            ],
            ['title' => 'Book a Ride']
        );
    }

    public function rideBookingCenter($slug, $location_id,Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $location = $this->communityRideLocationsRepository()->getById($community->id, $location_id);
        if (! $location) {
            return redirect($community->present()->url());
        }

        if (! \Auth::check()) {
            $urltype = 'returnurl';
            $urltypeid = '';
            $currentUrl = \URL::to('/').$_SERVER['REQUEST_URI'];

            return redirect($community->present()->authUrl('login', ['urltype' => $urltype, 'urltypeid' => $urltypeid, 'returnUrl' => $currentUrl]));
        }

        if (($community->race_community == 1 or $this->selected_pricing_plan_type=='racing') and \Auth::user()->present()->hasRideProfileCompleted($community->id) != 'yes' and ! \Request::ajax()) {
            $communityRideProfileRedirect = \Auth::user()->present()->hasRideProfileCompleted($community->id);

            return redirect($communityRideProfileRedirect);
        }

        // $slot_id=0;
        // $slot=$this->communityRideTimeslotsRepository()->getById($community->id,$slot_id);

        $locations = $this->communityRideLocationsRepository()->getLocations($community->id);
        $slots = $this->communityRideTimeslotsRepository()->getAllSlots($community->id);

        $location_sims = $this->communityRideSimsRepository()->getSimsByLocationAvailable($community->id, $location_id);

        return $this->render('user.ridebooking.booking',
            [
                'posted_community' => $community,
                'locations' => $locations,
                'slots' => $slots,
                'pagetype' => 'centerbooking',
                'selected_location' => $location,
                'location_sims' => $location_sims,
            ],
            ['title' => 'Book a Ride']
        );
    }

    public function rideGetSims($slug, $location_id, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $dateselected = $request->get('dateselected');
        $ride_booking_type = $request->get('ride_booking_type');
        $timezone = $request->get('timezone');

        if ($ride_booking_type == 0) {
            $appointment = $this->appointmentRepository()->hasBookedByCorporate($community->id, $location_id, $dateselected);

            if ($appointment) {
                return json_encode([
                    'status' => 1,
                    'sims' => '',
                    'first_halfday' => '',
                    'second_halfday' => '',
                    'fullday' => '',
                    'booked' => 'booked',
                    'durations' => '',
                ]);
            }
        } else {

            $getLocation = $this->communityRideLocationsRepository()->getById($community->id, $location_id);

            $booked = '';
            $fullday = '';
            $firsthalf = '';
            $secondhalf = '';
            $durations = "<option value=''>Select a time slot</option>";

            if ($getLocation) {

                $first_halfday = $this->appointmentRepository()->hasBookedByCorporateType($community->id, $location_id, $dateselected, 'firsthalf');

                $second_halfday = $this->appointmentRepository()->hasBookedByCorporateType($community->id, $location_id, $dateselected, 'secondhalf');

                $full_day = $this->appointmentRepository()->hasBookedByCorporateType($community->id, $location_id, $dateselected, 'fullday');

                date_default_timezone_set($timezone);

                $currenntTime = date('Y-m-d h:i A');

                $first_halfdayStartTime = $getLocation->first_halfday_start;
                $second_halfdayStartTime = $getLocation->second_halfday_start;
                $fulldayStartTime = $getLocation->fullday_start;

                $dateselected.' '.$first_halfdayStartTime;

                $first_halfdayStartTime = date('Y-m-d h:i A', strtotime($dateselected.' '.$first_halfdayStartTime));
                $second_halfdayStartTime = date('Y-m-d h:i A', strtotime($dateselected.' '.$second_halfdayStartTime));
                $fulldayStartTime = date('Y-m-d h:i A', strtotime($dateselected.' '.$fulldayStartTime));

                $fullDayBooked = '';
                if ($full_day || $getLocation->available_for_fullday == 0) {
                    if ($full_day) {
                        $booked = 'booked';
                    }
                    $fullday = 'booked';

                } elseif (strtotime($currenntTime) > strtotime($fulldayStartTime)) {
                    $fullday = 'booked';
                    // $booked="booked";
                } else {
                    $fullDayBooked = "<option value='fullday'>Full Day (Starts at ".$getLocation->fullday_start.')</option>';
                }

                if ($booked == '') {
                    if ($first_halfday || $getLocation->available_for_first_halfday == 0) {
                        $firsthalf = 'booked';
                        $fullday = 'booked';
                    } else {
                        if (strtotime($currenntTime) > strtotime($first_halfdayStartTime)) {
                            $firsthalf = 'booked';
                        } else {
                            $durations .= "<option value='firsthalf'>First Half (Starts at ".$getLocation->first_halfday_start.')</option>';
                        }
                    }

                    if ($second_halfday || $getLocation->available_for_second_halfday == 0) {
                        $secondhalf = 'booked';
                        $fullday = 'booked';
                    } else {
                        if (strtotime($currenntTime) > strtotime($second_halfdayStartTime)) {
                            $secondhalf = 'booked';
                        } else {
                            $durations .= "<option value='secondhalf'>Second Half (Starts at ".$getLocation->second_halfday_start.')</option>';
                        }
                    }
                }

                if ($firsthalf == '' && $secondhalf == '') {
                    $durations .= $fullDayBooked;
                } elseif ($firsthalf == '' && $secondhalf != 'booked') {
                    $durations .= $fullDayBooked;
                } elseif ($secondhalf == '' && $firsthalf != 'booked') {
                    $durations .= $fullDayBooked;
                }

                if ($firsthalf == 'booked' and $secondhalf == 'booked' and $fullday == 'booked') {
                    $booked = 'booked';
                }
            }

            /*if($firsthalf==""){
                $durations.="<option value='firsthalf'>First Half</option>";
            }*/

            /*if($secondhalf==""){
                $durations.="<option value='secondhalf'>Second Half</option>";
            }*/

            /*if($fullday==""){
                $durations.="<option value='secondhalf'>Full day</option>";
            }*/

            return json_encode([
                'status' => 1,
                'sims' => '',
                'first_halfday' => $firsthalf,
                'second_halfday' => $secondhalf,
                'fullday' => $fullday,
                'booked' => $booked,
                'durations' => $durations,
            ]);
        }

        $sims = $this->communityRideSimsRepository()->getSimsByLocationAvailable($community->id, $location_id);

        $options = "<option value=''>Select a SIM type</option>";

        foreach ($sims as $sim) {
            $options .= '<option value='.$sim->id.'>'.$sim->sim.'</option>';
        }

        return json_encode([
            'status' => 1,
            'sims' => $options,
            'first_halfday' => '',
            'second_halfday' => '',
            'fullday' => '',
            'booked' => '',
            'durations' => '',
        ]);
    }

    public function rideGetSimCost($slug, $location_id, $sim_id, $slot_id, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $dateselected = $request->get('dateselected');
        $timezone = $request->get('timezone');

        $ride_cost = 'none';
        $slots = '';
        $booking_summary = '';

        $costing = $this->communityRideCostsRepository()->findByCmSIMSlotId($community->id, $location_id, $sim_id, $slot_id);
        if ($costing) {

            $getLocation = $this->communityRideLocationsRepository()->getById($community->id, $location_id);
            $getSIM = $this->communityRideSimsRepository()->getById($community->id, $sim_id);

            $getSlot = $this->communityRideTimeslotsRepository()->getById($community->id, $slot_id);

            if ($getSlot and $getLocation and $getSIM) {

                $booking_summary = $getSIM->sim.' on '.$dateselected.', '.$getLocation->location.", starting at <span class='ride_selected_location_sim_time'></span> for ".$getSlot->times.' '.$getSlot->name;

                $isStudentApproved = $this->communityRideStudentVerificationRepository()->isStudentVerified($community->id, \Auth::user()->id, $location_id);
                if ($isStudentApproved and $costing->student_cost) {
                    $ride_cost = number_format($costing->student_cost, 2);
                } else {
                    $ride_cost = number_format($costing->cost, 2);
                }

                $totalmins = $getSlot->times;

                $slot1 = [];
                $slot2 = [];
                $slot3 = [];

                $totalmins_last = $totalmins;

                $timeSettings = $this->appointmentAvailabilityRepository()->getByRideCommunitySim($community->id, $location_id, $sim_id);

                $master_time_zone = $community->timezone;

                $noticeTimeDay = date('Y-m-d H:i:s');
                $noticeTimeCalDay = date('M j, Y');
                $bufferTime = 0;
                if ($timeSettings) {
                    // $master_time_zone=$timeSettings->timezone;
                    date_default_timezone_set($timezone);

                    // $totalmins_last=$this->getSlotTimes($community->id,$location_id,$sim_id);
                    $noticeTimeDay = $timeSettings->notice_time;
                    $noticeTimeDay = date('Y-m-d H:i:s', strtotime(' +'.$noticeTimeDay, strtotime(date('Y-m-d H:i:s'))));
                    $noticeTimeCalDay = date('M j, Y', strtotime($noticeTimeDay));
                    $bufferTime = $timeSettings->buffer_time;
                }

                $currentTime = date('H:i:s');
                $checkDateCompare = date('Y-m-d', strtotime($dateselected));

                $dateselected = $dateselected.' '.$currentTime;
                $checkDate = date('Y-m-d H:i:s', strtotime($noticeTimeDay));
                $day = date('D', strtotime($dateselected));
                $dateselected = date('Y-m-d', strtotime($dateselected));

                $timeSlots = $this->getTimeSlots($timezone, 15, $day, $dateselected, $checkDate, $totalmins_last, $master_time_zone, $bufferTime, $checkDateCompare, $community->id, $location_id, $sim_id);
                if ($timeSlots) {
                    $slot1 = $timeSlots;
                }

                $tomorrowsDay = date('D', strtotime(' +1 day', strtotime($dateselected)));
                $tomorrowsDate = date('Y-m-d', strtotime(' +1 day', strtotime($dateselected)));
                $tomorrowsSlots = $this->getTimeSlots($timezone, 15, $tomorrowsDay, $tomorrowsDate, $checkDate, $totalmins_last, $master_time_zone, $bufferTime, $checkDateCompare, $community->id, $location_id, $sim_id);
                if ($tomorrowsSlots) {
                    $slot2 = $tomorrowsSlots;
                }

                $yesterdaysDay = date('D', strtotime(' -1 day', strtotime($dateselected)));
                $yesterdaysDate = date('Y-m-d', strtotime(' -1 day', strtotime($dateselected)));
                $yesterdaysSlots = $this->getTimeSlots($timezone, 15, $yesterdaysDay, $yesterdaysDate, $checkDate, $totalmins_last, $master_time_zone, $bufferTime, $checkDateCompare, $community->id, $location_id, $sim_id);

                if ($yesterdaysSlots) {
                    $slot3 = $yesterdaysSlots;
                }

                $availableslots = array_merge($slot1, $slot2, $slot3);

                $slots = '';
                if (! empty($availableslots)) {
                    // $slots=$this->theme->section('user.ridebooking.available-slots', ['timeSlots' => $availableslots]);

                    foreach ($availableslots as $times) {
                        if ($this->isSlotAvailable($availableslots, $times, $totalmins_last)) {
                            $slots .= "<div class='ride-times' data-value='".date('H:i', strtotime($times))."'>".date('h:i A', strtotime($times)).'</div>';
                        }
                    }
                }
            }
        }

        if ($slots == '') {
            $ride_cost = 'none';
        }

        return json_encode([
            'ride_cost' => $ride_cost,
            'available_slots' => $slots,
            'booking_summary' => $booking_summary,
        ]);
    }

    public function isSlotAvailable($timesArray, $checkTime, $slotTime)
    {
        if ($slotTime == 15) {
            return true;
        } else {

            $endTime = date('Y-m-d H:i:s', strtotime('+'.$slotTime.'minutes', strtotime($checkTime)));

            $slots = $this->getBufferredSlotsList(15, $checkTime, $endTime);

            $found = 'no';
            if (! empty($slots)) {
                $found = 'yes';
                foreach ($slots as $slot) {
                    if (! in_array($slot, $timesArray)) {
                        $found = 'no';
                        break;
                    }
                }
            }
            if ($found == 'no') {
                return false;
            }

            return true;
        }
    }

    public function getTimeSlots($timezone, $totalmins, $day, $date, $checkDate, $totalmins_last, $master_time_zone, $bufferTime, $checkDateCompare, $community_id, $location_id, $sim_id)
    {
        $timeSettings = $this->appointmentAvailabilityRepository()->getByRideCommunitySim($community_id, $location_id, $sim_id);
        if ($timeSettings) {
            $startTime = '';
            $endTime = '';
            if ($day == 'Sun') {
                $startTime = $timeSettings->sun_start;
                $endTime = $timeSettings->sun_end;

                if ($timeSettings->sun == 0) {
                    return [];
                }
            } elseif ($day == 'Mon') {
                $startTime = $timeSettings->mon_start;
                $endTime = $timeSettings->mon_end;

                if ($timeSettings->mon == 0) {
                    return [];
                }
            } elseif ($day == 'Tue') {
                $startTime = $timeSettings->tue_start;
                $endTime = $timeSettings->tue_end;

                if ($timeSettings->tue == 0) {
                    return [];
                }
            } elseif ($day == 'Wed') {
                $startTime = $timeSettings->wed_start;
                $endTime = $timeSettings->wed_end;

                if ($timeSettings->wed == 0) {
                    return [];
                }
            } elseif ($day == 'Thu') {
                $startTime = $timeSettings->thus_start;
                $endTime = $timeSettings->thus_end;

                if ($timeSettings->thu == 0) {
                    return [];
                }
            } elseif ($day == 'Fri') {
                $startTime = $timeSettings->fri_start;
                $endTime = $timeSettings->fri_end;

                if ($timeSettings->fri == 0) {
                    return [];
                }
            } elseif ($day == 'Sat') {
                $startTime = $timeSettings->sat_start;
                $endTime = $timeSettings->sat_end;

                if ($timeSettings->sat == 0) {
                    return [];
                }
            }

            if ($startTime and $endTime) {
                $appointmentStartHrs = $startTime;
                $appointmentEndHrs = $endTime;

                // $appointmentStartHrsList=convertToNewTimeDateZone($date." ".$appointmentStartHrs,$timeSettings->timezone,$timezone);

                // $appointmentEndHrsList=convertToNewTimeDateZone($date." ".$appointmentEndHrs,$timeSettings->timezone,$timezone);

                $appointmentStartHrsList = convertToNewTimeDateZone($date.' '.$appointmentStartHrs, $master_time_zone, $timezone);

                $appointmentEndHrsList = convertToNewTimeDateZone($date.' '.$appointmentEndHrs, $master_time_zone, $timezone);

                $hrsArray = $this->getHrsList($appointmentStartHrsList, $appointmentEndHrsList, $totalmins, $date, $checkDate, $totalmins_last, $timezone, $master_time_zone, $bufferTime, $checkDateCompare, $community_id, $location_id, $sim_id);

                return $hrsArray;
            }
        }

        return [];
    }

    public function getHrsList($appointmentStartHrsList, $appointmentEndHrsList, $totalmins, $date, $checkDate, $totalmins_last, $timezone, $master_time_zone, $bufferTime, $checkDateCompare, $community_id, $location_id, $sim_id)
    {

        return $this->slotsList($totalmins, $appointmentStartHrsList, $appointmentEndHrsList, $date, $checkDate, $totalmins_last, $timezone, $master_time_zone, $bufferTime, $checkDateCompare, $community_id, $location_id, $sim_id);
    }

    public function slotsList($duration, $startTime, $endTime, $date, $checkDate, $totalmins_last, $timezone, $master_time_zone, $bufferTime, $checkDateCompare, $community_id, $location_id, $sim_id)
    {
        $timeSettings = $this->appointmentAvailabilityRepository()->getByRideCommunitySim($community_id, $location_id, $sim_id);

        $community = $this->communityRepository()->getBySlug($community_id);

        $meeting_end = '';
        if ($timeSettings and $timeSettings->schedule_for == 1 and $timeSettings->schedule_end != '0000-00-00') {
            $meeting_end = $timeSettings->schedule_end;
        }

        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $interval = new \DateInterval('PT'.$duration.'M');
        $period = new \DatePeriod($start, $interval, $end);
        $periods = [];
        $slots = [];
        $slot_counter = 0;

        foreach ($period as $dt) {
            $slots[] = $dt;
        }

        foreach ($slots as $key => $dt) {
            $slot_counter++;
            if ($slot_counter == count($slots)) {
                $current = $end;
            } elseif ($slot_counter <= count($slots)) {
                $current = $slots[$key + 1];
            }
            $previous = $slots[$key];

            date_default_timezone_set($timezone);

            $slotDateTime = $previous->format('Y-m-d H:i:s');
            $myDate = strtotime($slotDateTime);

            $checkDateFull = date('Y-m-d', strtotime($checkDate));
            $curDateTime = strtotime($checkDate);

            if (($checkDateCompare == $previous->format('Y-m-d')) and ($myDate > $curDateTime)) {
                if ($meeting_end != '') {
                    if (strtotime($meeting_end) >= strtotime($previous->format('Y-m-d'))) {
                        $periods[] = $previous->format('Y-m-d H:i:s');
                    }
                } else {
                    $periods[] = $previous->format('Y-m-d H:i:s');
                }
            }
        }

        $bufferedSlotsArray = [];

        if ($bufferTime > 0) {

            $bookedArrays = [];
            $bookedTime = $this->appointmentBookingRepository()->getBookingListBySimLocation($community_id, $location_id, $sim_id, $date);

            foreach ($bookedTime as $apt) {
                $latestTime = $this->appointmentBookingRepository()->getByAppointmentIdSIMLocation($community_id, $location_id, $sim_id, $apt->appointment_id);

                $takenTime = '';
                foreach ($latestTime as $ltTime) {
                    $takenTime = $ltTime->appointment_slot;
                }
                array_push($bookedArrays, $takenTime);
            }

            if (! empty($bookedArrays)) {
                foreach ($bookedArrays as $array_time) {
                    $array_time_end = date('Y-m-d h:i A', strtotime('+ 15 minutes', strtotime($array_time)));
                    $bufferEnd = date('Y-m-d h:i A', strtotime('+'.$bufferTime.'minutes', strtotime($array_time_end)));
                    $bufferedSlots = $this->getBufferredSlotsList(15, $array_time_end, $bufferEnd);
                    foreach ($bufferedSlots as $bSlots) {
                        $bufferTimeClient = convertToNewTimeDateZoneClient($bSlots, $master_time_zone, $timezone);
                        array_push($bufferedSlotsArray, $bufferTimeClient);
                    }
                }
            }
        }

        $breakSlots = [];

        if ($timeSettings->break_start != '' and $timeSettings->break_end != '') {
            $breakStart = $timeSettings->break_start;
            $breakEnd = $timeSettings->break_end;
            // $breakStart1=convertToNewTimeDateZone($date." ".$breakStart,$timeSettings->timezone,$timezone);
            $breakStart1 = convertToNewTimeDateZone($date.' '.$breakStart, $master_time_zone, $timezone);
            // $breakEnd1=convertToNewTimeDateZone($date." ".$breakEnd,$timeSettings->timezone,$timezone);
            $breakEnd1 = convertToNewTimeDateZone($date.' '.$breakEnd, $master_time_zone, $timezone);

            $breakSlots = $this->getBreakSlots(15, $breakStart1, $breakEnd1, $master_time_zone, $checkDate);
        }

        // $newPeriods = array();
        $newPeriods = $periods;
        $availableSpots = [];
        if (! empty($newPeriods)) {
            foreach ($newPeriods as $times) {
                $actualTime = convertToNewTimeDateZoneMaster($times, $timezone, $master_time_zone);
                $hasBooked = $this->appointmentBookingRepository()->findBookingBySimLocation($community_id, $location_id, $sim_id, $actualTime);

                if (! $hasBooked and ! in_array($times, $breakSlots)) {
                    if (! empty($bufferedSlotsArray)) {
                        if (! in_array($times, $bufferedSlotsArray)) {
                            $availableSpots[] = $times;
                        }
                    } else {
                        $availableSpots[] = $times;
                    }
                }
            }
        }

        return $availableSpots;
    }

    public function getBreakSlots($duration, $startTime, $endTime, $timezone)
    {
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $interval = new \DateInterval('PT'.$duration.'M');
        $period = new \DatePeriod($start, $interval, $end);
        $periods = [];
        $slots = [];
        $slot_counter = 0;

        foreach ($period as $dt) {
            $slots[] = $dt;
        }

        foreach ($slots as $key => $dt) {
            $slot_counter++;
            if ($slot_counter == count($slots)) {
                $current = $end;
            } elseif ($slot_counter <= count($slots)) {
                $current = $slots[$key + 1];
            }
            $previous = $slots[$key];
            $periods[] = $previous->format('Y-m-d H:i:s');
        }

        return $periods;
    }

    public function getBufferredSlotsList($duration, $startTime, $endTime)
    {
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $interval = new \DateInterval('PT'.$duration.'M');
        $period = new \DatePeriod($start, $interval, $end);
        $periods = [];
        $slots = [];
        $slot_counter = 0;

        foreach ($period as $dt) {
            $slots[] = $dt;
        }

        foreach ($slots as $key => $dt) {
            $slot_counter++;
            if ($slot_counter == count($slots)) {
                $current = $end;
            } elseif ($slot_counter <= count($slots)) {
                $current = $slots[$key + 1];
            }
            $previous = $slots[$key];
            $periods[] = $previous->format('Y-m-d H:i:s');
        }

        return $periods;
    }

    public function getTimesSlotsList($duration, $startTime, $endTime)
    {
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $interval = new \DateInterval('PT'.$duration.'M');
        $period = new \DatePeriod($start, $interval, $end);
        $periods = [];
        $slots = [];
        $slot_counter = 0;

        foreach ($period as $dt) {
            $slots[] = $dt;
        }

        foreach ($slots as $key => $dt) {
            $slot_counter++;
            if ($slot_counter == count($slots)) {
                $current = $end;
            } elseif ($slot_counter <= count($slots)) {
                $current = $slots[$key + 1];
            }
            $previous = $slots[$key];
            $periods[] = $previous->format('Y-m-d h:i A');
        }

        return $periods;
    }

    public function getOnlyTimesSlotsList($duration, $startTime, $endTime)
    {
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $interval = new \DateInterval('PT'.$duration.'M');
        $period = new \DatePeriod($start, $interval, $end);
        $periods = [];
        $slots = [];
        $slot_counter = 0;

        foreach ($period as $dt) {
            $slots[] = $dt;
        }

        foreach ($slots as $key => $dt) {
            $slot_counter++;
            if ($slot_counter == count($slots)) {
                $current = $end;
            } elseif ($slot_counter <= count($slots)) {
                $current = $slots[$key + 1];
            }
            $previous = $slots[$key];
            $periods[] = $previous->format('h:i A');
        }

        return $periods;
    }

    public function getSlotTimes($community_id, $location_id, $sim_id)
    {

        $slot_15 = $this->communityRideTimeslotsRepository()->getSlotByNameValue($community_id, '15', 'minutes');
        $slot_30 = $this->communityRideTimeslotsRepository()->getSlotByNameValue($community_id, '30', 'minutes');
        $slot_60 = $this->communityRideTimeslotsRepository()->getSlotByNameValue($community_id, '60', 'minutes');

        if ($slot_15) {
            $mins_15 = $this->communityRideCostsRepository()->getTimeSlotById($community_id, $slot_15->id, $location_id, $sim_id);
            if ($mins_15) {
                return 15;
            }
        }

        if ($slot_30) {
            $mins_30 = $this->communityRideCostsRepository()->getTimeSlotById($community_id, $slot_30->id, $location_id, $sim_id);
            if ($mins_30) {
                return 30;
            }
        }

        if ($slot_60) {
            $mins_60 = $this->communityRideCostsRepository()->getTimeSlotById($community_id, $slot_60->id, $location_id, $sim_id);
            if ($mins_60) {
                return 30;
            }
        }
    }

    public function bookingMyRideFailed($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }
		
		$planAmount = $request->get('planAmount');
        $customerName = $request->get('customerName');
        $customerEmail = $request->get('emailAddress');
        $customerAddress = $request->get('customerAddress');
        $customerCity = $request->get('customerCity');
        $customerZipcode = $request->get('customerZipcode');
        $customerState = $request->get('customerState');
        $customerCountry = $request->get('customerCountry');
        $cardNumber = $request->get('cardNumber');
        $cardCVC = $request->get('cardCVC');
        $cardExpMonth = $request->get('cardExpMonth');
        $cardExpYear = $request->get('cardExpYear');
        $selected_location_id = $request->get('selected_location_id');
        $selected_sim_id = $request->get('selected_sim_id');
        $selected_slot_id = $request->get('selected_slot_id');
        $itemName = $request->get('item_details');
        $itemNumber = $request->get('item_number');
        $currency = $request->get('currency_code');
        $orderNumber = $request->get('order_number');
        $plan = $request->get('plan');
        $address_unit = $request->get('address_unit');

        $itemPrice = $planAmount;

        $payment_for = 'ridebooking';
        $paymentDate = date('Y-m-d');
        $user_id = \Auth::user()->id;$paymentData = $this->communityPricingPlanPaymentRepository()->addFailedPayment(
            $community,
            $user_id,
            $customerName,
            $customerEmail,
            $cardNumber,
            $cardCVC,
            $cardExpMonth,
            $cardExpYear,
            $itemName,
            $itemNumber,
            $itemPrice,
            $currency,
            $itemPrice,
            '',
            'Failed',
            $paymentDate,
            $payment_for,
            'ridebooking',
            '',
            $community->id,
            $plan,
            'ridebooking');

        if ($paymentData) {
            $paymentData->slot_id = $selected_slot_id;
            $paymentData->location_id = $selected_location_id;
            $paymentData->sim_id = $selected_sim_id;

            $paymentData->address_1 = $customerAddress;
            $paymentData->address_2 = $address_unit;
            $paymentData->zip_code = $customerZipcode;
            $paymentData->city = $customerCity;
            $paymentData->state = $customerState;
            $paymentData->country = $customerCountry;

            $paymentData->save();
        }

        return $paymentData;
    }

    public function bookingMyRide($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $planAmount = $request->get('planAmount');

        if (! empty($request->get('stripeToken')) || $planAmount == '0.00') {$plan = $request->get('plan');
            $payment_type = $request->get('payment_type');
            $stripeToken = $request->get('stripeToken');
            $customerName = $request->get('customerName');
            $customerEmail = $request->get('emailAddress');
            $customerAddress = $request->get('customerAddress');
            $customerCity = $request->get('customerCity');
            $customerZipcode = $request->get('customerZipcode');
            $customerState = $request->get('customerState');
            $customerCountry = $request->get('customerCountry');
            $cardNumber = $request->get('cardNumber');
            $cardCVC = $request->get('cardCVC');
            $cardExpMonth = $request->get('cardExpMonth');
            $cardExpYear = $request->get('cardExpYear');

            $selected_location_id = $request->get('selected_location_id');
            $selected_sim_id = $request->get('selected_sim_id');
            $selected_slot_id = $request->get('selected_slot_id');
            $address_unit = $request->get('address_unit');

            $has_coupon_redeemed = $request->get('has_coupon_redeemed');

            $payment_for = 'ridebooking';
            $plan = $request->get('ride_booking_type');
            $user_id = \Auth::user()->id;

            $itemName = $request->get('item_details');
            $itemNumber = $request->get('item_number');
            $itemPrice = $request->get('price');
            $totalAmount = $request->get('total_amount');
            $currency = $request->get('currency_code');
            $orderNumber = $request->get('order_number');
            $transaction_payment_type = 'ridebooking';

            $use_my_ride_balance = $request->get('use_my_ride_balance');
            $balance_to_deduct = $request->get('balance_to_deduct');
            $amount_before_use_balance = $request->get('amount_before_use_balance');

            $user_data = \Auth::user();

            $dateselected = $request->get('dateselected');
            $ride_start_time = $request->get('ride_start_time');

            $all_slots = '';

            $ride_booking_type = $request->get('ride_booking_type');
            $corporate_booking_duarion = $request->get('corporate_booking_duarion');
            $corporate_booking_note = $request->get('corporate_booking_note');

            $getLocation = $this->communityRideLocationsRepository()->getById($community->id, $selected_location_id);
            $getCorporateSims = [];

            $bookingtotalmins = '';

            if ($ride_booking_type == 0) {
                $slot = $this->communityRideTimeslotsRepository()->getById($community->id, $selected_slot_id);

                $actualTime = $dateselected.' '.$ride_start_time;
                $next_time = $slot->times.' '.$slot->name;
                $array_time_end = date('Y-m-d h:i A', strtotime('+ '.$next_time, strtotime($actualTime)));
                $bufferedSlots = $this->getTimesSlotsList(15, $actualTime, $array_time_end);

                foreach ($bufferedSlots as $bSlots) {
                    $hasBooked = $this->appointmentBookingRepository()->findBookingBySimLocation($community->id, $selected_location_id, $selected_sim_id, $bSlots);

                    if ($hasBooked) {
                        \Session::flash('purchasemessage', 'This slot is not available now for '.$next_time.', try with another slot.');
                        $communityHome = \URL::route('community-home', ['slug' => $community->id]);

                        return $communityHome;
                    }
                }

                $getOnlyTimesSlotsList = $bufferedSlots;
                $bookingtotalmins = $slot->times;
            } else {
                $duration = $corporate_booking_duarion;

                if ($duration == 'firsthalf') {
                    $ride_cost = number_format($getLocation->first_halfday_price, 2);
                    $day = 'A half day - first half ';
                    $actualTime = $dateselected.' '.$getLocation->first_halfday_start;
                    $array_time_end = $dateselected.' '.$getLocation->first_halfday_end;
                } elseif ($duration == 'secondhalf') {
                    $ride_cost = number_format($getLocation->second_halfday_price, 2);
                    $day = 'A half day - second half ';
                    $actualTime = $dateselected.' '.$getLocation->second_halfday_start;
                    $array_time_end = $dateselected.' '.$getLocation->second_halfday_end;
                } else {
                    $ride_cost = number_format($getLocation->fullday_price, 2);
                    $day = 'A full day ';
                    $actualTime = $dateselected.' '.$getLocation->fullday_start;
                    $array_time_end = $dateselected.' '.$getLocation->fullday_end;
                }

                $bufferedSlots = $this->getTimesSlotsList(15, $actualTime, $array_time_end);

                $location_id = $selected_location_id;

                $getCorporateSims = $this->communityRideSimsRepository()->getCorporateAvailableSims($community->id, $location_id);

                if ($getCorporateSims) {
                    foreach ($getCorporateSims as $sm) {
                        foreach ($bufferedSlots as $bSlots) {
                            $hasBooked = $this->appointmentBookingRepository()->findBookingBySimLocation($community->id, $selected_location_id, $sm->id, $bSlots);

                            if ($hasBooked) {
                                $hasBooked->cancelled_booking = 1;
                                $hasBooked->save();

                                $aptdtls = $this->appointmentRepository()->getById($hasBooked->appointment_id);
                                if ($aptdtls and $aptdtls->cancelled_booking == 0) {
                                    $aptdtls->cancelled_booking = 1;
                                    $aptdtls->save();

                                    $user_dt = $aptdtls->user;

                                    $subject = 'Your booking has been cancelled.';

                                    try {
                                        $this->mailer->send('emails.community.booking-ride-cancelled', [
                                            'fullname' => $user_dt->fullname,
                                            'email_address' => $user_dt->email_address,
                                            'community_id' => $community->id,
                                            'appointment_id' => $appointment_id,
                                        ], function ($mail) use ($subject, $user_dt, $mail_from_email, $community) {
                                            $mail->to($user_dt->email_address, $user_dt->fullname)
                                                ->subject($subject)
                                                ->from($mail_from_email, $community->title);
                                        });
                                    } catch (\Exception $e) {
                                        // return $e;
                                    }
                                }
                            }
                        }
                    }

                    $getOnlyTimesSlotsList = $bufferedSlots;
                } else {
                    \Session::flash('purchasemessage', 'No sims available for now, try with another date.');
                    $communityHome = \URL::route('community-home', ['slug' => $community->id]);

                    return $communityHome;
                }
            }

            $owner = $community->user;
            $master_time_zone = $community->timezone;

            $val = [
                'fullname' => \Auth::user()->fullname,
                'email' => \Auth::user()->email_address,
                'totalmins' => $bookingtotalmins,
                'appointmentstarttime' => $actualTime,
                'appointmentendtime' => $array_time_end,
                'dateselected' => $dateselected,
                'time_zone' => $community->timezone,
                'description' => 'Ride booked',
                'location' => $getLocation->location,
                'ride_booking_type' => $ride_booking_type,
                'corporate_booking_duarion' => $corporate_booking_duarion,
                'corporate_booking_note' => $corporate_booking_note,
            ];

            if ($planAmount == '0.00') {
                $cardNumber = '';
                $cardCVC = '';
                $cardExpMonth = '';
                $cardExpYear = '';
                $itemPrice = '';
                $paidCurrency = '';

                $amountPaidNew = '0.00';
                $balanceTransaction = $orderNumber;
                $paymentStatus = 'Completed';
                $paymentDate = date('Y-m-d');
                $customer_id = '';

                if ($use_my_ride_balance) {
                    $amountPaidNew = $balance_to_deduct;
                }

                $paymentData = $this->communityPricingPlanPaymentRepository()->addPayment('', $user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, 0, 'ridebooking');

                if ($paymentData) {
                    $appointment = $this->appointmentRepository()->bookAppointmentRiding($owner, $val, $master_time_zone, null, 0, $community, $selected_location_id, $selected_sim_id, $getOnlyTimesSlotsList, $getCorporateSims);

                    $appointment_id = '';
                    if ($appointment) {
                        $appointment->ride_payment_id = $paymentData->id;
                        $appointment->slot_id = $selected_slot_id;
                        $appointment->booking_id = rand(1111111111, 9999999999);
                        $appointment->save();

                        $appointment_id = $appointment->id;
                    }

                    $paymentData->slot_id = $selected_slot_id;
                    $paymentData->location_id = $selected_location_id;
                    $paymentData->sim_id = $selected_sim_id;

                    $paymentData->address_1 = $customerAddress;
                    $paymentData->address_2 = $address_unit;
                    $paymentData->zip_code = $customerZipcode;
                    $paymentData->city = $customerCity;
                    $paymentData->state = $customerState;
                    $paymentData->country = $customerCountry;
                    $paymentData->plan_id = $plan;
                    $paymentData->save();

                    $full_date = date('Y-m-d H:i:s');

                    if ($has_coupon_redeemed == 1) {
                        $user_data->ride_coupon_redeemed = 1;
                        $user_data->save();
                        $paymentData->coupon_payment = 1;
                        $paymentData->save();

                        $this->communityRideTransactionsRepository()->doTransaction($community->id, $user_id, 0, 0, $full_date, 'ride_coupon_used', $paymentData->id, $user_id);
                    }

                    if ($use_my_ride_balance) {
                        $this->communityRideTransactionsRepository()->doTransaction($community->id, $user_id, $amountPaidNew, $amountPaidNew, $full_date, 'balance_used', $paymentData->id, $user_id);

                        $this->communityRideAccountRepository()->fundAccount($community->id, $user_id, $amountPaidNew, $amountPaidNew, $full_date, 'use_amount');
                    }

                    $mail_from_email = $community->present()->getFromEmailAddress();
                    $subject = 'Booking successfully done.';

                    try {
                        $this->mailer->send('emails.community.booking-ride-coupon', [
                            'fullname' => $user_data->fullname,
                            'email_address' => $user_data->email_address,
                            'transaction_id' => $balanceTransaction,
                            'item_name' => $itemName,
                            'payment_type' => $transaction_payment_type,
                            'amount' => $amountPaidNew,
                            'community_id' => $community->id,
                            'actualTime' => $actualTime,
                            'appointment_id' => $appointment_id,
                            'has_coupon_redeemed' => $has_coupon_redeemed,
                            'use_my_ride_balance' => $use_my_ride_balance,
                        ], function ($mail) use ($user_data, $subject, $mail_from_email, $community) {
                            $mail->to($user_data->email_address, $user_data->fullname)
                                ->subject($subject)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {
                        // return $e;
                    }

                    $communityUser = $community->user;
                    try {
                        $this->mailer->send('emails.community.booking-ride-admin-coupon', [
                            'fullname' => $communityUser->fullname,
                            'email_address' => $communityUser->email_address,
                            'transaction_id' => $balanceTransaction,
                            'item_name' => $itemName,
                            'payment_type' => $transaction_payment_type,
                            'amount' => $amountPaidNew,
                            'community_id' => $community->id,
                            'actualTime' => $actualTime,
                            'appointment_id' => $appointment_id,
                            'has_coupon_redeemed' => $has_coupon_redeemed,
                            'use_my_ride_balance' => $use_my_ride_balance,
                        ], function ($mail) use ($communityUser, $subject, $mail_from_email, $community) {
                            $mail->to($communityUser->email_address, $communityUser->fullname)
                                ->subject($subject)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {
                        // return $e;
                    }

                    $purchasemessage = 'You have successfully booked your ride. <br><br> Your transaction id is - '.$balanceTransaction;
                } else {
                    $purchasemessage = 'Something went wrong, try after sometime.';
                }
            } else {

                // require_once app_path('library/stripe-php/init.php');

                $stripe = [
                    'secret_key' => config('stripe_secret_key'),
                    'publishable_key' => config('stripe_publishable_key'),
                ];

                if (config('stripe_mode') == 'test') {
                    $source_token = 'tok_visa';
                } else {
                    $source_token = $stripeToken;
                }

                \Stripe\Stripe::setApiKey($stripe['secret_key']);

                $customer = \Stripe\Customer::create([
                    'name' => $customerName,
                    'description' => 'Ride Booking',
                    'email' => $customerEmail,
                    'source' => $source_token, // This is for test
                    'address' => ['city' => $customerCity, 'country' => $customerCountry, 'line1' => $customerAddress, 'line2' => '', 'postal_code' => $customerZipcode, 'state' => $customerState],
                ]);

                $payDetails = \Stripe\Charge::create([
                    'customer' => $customer->id,
                    'amount' => $totalAmount,
                    'currency' => $currency,
                    'description' => $itemName,
                    'metadata' => [
                        'order_id' => $orderNumber,
                    ],
                ]);

                $customer_id = $customer->id;
                $paymenyResponse = $payDetails->jsonSerialize();

                if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {

                    $amountPaid = $paymenyResponse['amount'];
                    $balanceTransaction = $paymenyResponse['balance_transaction'];
                    $paidCurrency = $paymenyResponse['currency'];
                    $paymentStatus = $paymenyResponse['status'];
                    $paymentDate = date('Y-m-d H:i:s');
                    $amountPaidNew = $amountPaid / 100;
                    $itemPrice = $itemPrice / 100;

                    $paymentData = $this->communityPricingPlanPaymentRepository()->addPayment('', $user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, 0, 'ridebooking');

                    if ($paymentData) {

                        $appointment = $this->appointmentRepository()->bookAppointmentRiding($owner, $val, $master_time_zone, null, 0, $community, $selected_location_id, $selected_sim_id, $getOnlyTimesSlotsList, $getCorporateSims);
                        $appointment_id = '';
                        if ($appointment) {
                            $appointment->ride_payment_id = $paymentData->id;
                            $appointment->slot_id = $selected_slot_id;
                            $appointment->booking_id = rand(1111111111, 9999999999);
                            $appointment->save();

                            $appointment_id = $appointment->id;
                        }

                        $paymentData->slot_id = $selected_slot_id;
                        $paymentData->location_id = $selected_location_id;
                        $paymentData->sim_id = $selected_sim_id;

                        $paymentData->address_1 = $customerAddress;
                        $paymentData->address_2 = $address_unit;
                        $paymentData->zip_code = $customerZipcode;
                        $paymentData->city = $customerCity;
                        $paymentData->state = $customerState;
                        $paymentData->country = $customerCountry;
                        $paymentData->plan_id = $plan;

                        $paymentData->save();

                        $full_date = date('Y-m-d H:i:s');

                        if ($use_my_ride_balance) {
                            $this->communityRideTransactionsRepository()->doTransaction($community->id, $user_id, $balance_to_deduct, $balance_to_deduct, $full_date, 'balance_used', $paymentData->id, $user_id);

                            $this->communityRideAccountRepository()->fundAccount($community->id, $user_id, $balance_to_deduct, $balance_to_deduct, $full_date, 'use_amount');
                        }

                        if ($has_coupon_redeemed == 1) {
                            $user_data->ride_coupon_redeemed = 1;
                            $user_data->save();

                            $paymentData->coupon_payment = 1;
                            $paymentData->save();

                            $this->communityRideTransactionsRepository()->doTransaction($community->id, $user_id, 0, 0, $full_date, 'ride_coupon_used', $paymentData->id, $user_id);
                        }

                        $this->communityRideTransactionsRepository()->doTransaction($community->id, $user_id, $amountPaidNew, $amountPaidNew, $full_date, 'payment', $paymentData->id, $user_id);

                        $mail_from_email = $community->present()->getFromEmailAddress();

                        $subject = 'Booking successfully done.';

                        try {
                            $this->mailer->send('emails.community.booking-ride', [
                                'fullname' => $user_data->fullname,
                                'email_address' => $user_data->email_address,
                                'transaction_id' => $balanceTransaction,
                                'item_name' => $itemName,
                                'payment_type' => $transaction_payment_type,
                                'amount' => $amountPaidNew,
                                'community_id' => $community->id,
                                'actualTime' => $actualTime,
                                'appointment_id' => $appointment_id,
                                'has_coupon_redeemed' => $has_coupon_redeemed,
                                'use_my_ride_balance' => $use_my_ride_balance,
                            ], function ($mail) use ($user_data, $subject, $mail_from_email, $community) {
                                $mail->to($user_data->email_address, $user_data->fullname)
                                    ->subject($subject)
                                    ->from($mail_from_email, $community->title);
                            });
                        } catch (\Exception $e) {
                            // return $e;
                        }

                        $communityUser = $community->user;
                        try {
                            $this->mailer->send('emails.community.booking-ride-admin', [
                                'fullname' => $communityUser->fullname,
                                'email_address' => $communityUser->email_address,
                                'transaction_id' => $balanceTransaction,
                                'item_name' => $itemName,
                                'payment_type' => $transaction_payment_type,
                                'amount' => $amountPaidNew,
                                'community_id' => $community->id,
                                'actualTime' => $actualTime,
                                'appointment_id' => $appointment_id,
                                'has_coupon_redeemed' => $has_coupon_redeemed,
                                'use_my_ride_balance' => $use_my_ride_balance,
                            ], function ($mail) use ($communityUser, $subject, $mail_from_email, $community) {
                                $mail->to($communityUser->email_address, $communityUser->fullname)
                                    ->subject($subject)
                                    ->from($mail_from_email, $community->title);
                            });
                        } catch (\Exception $e) {
                            // return $e;
                        }
                    }

                    $purchasemessage = 'You have successfully booked your ride. <br><br> Your transaction id is - '.$balanceTransaction;
                } else {
                    $purchasemessage = 'Something went wrong, try after sometime.';
                }
            }

            \Session::flash('purchasemessage', $purchasemessage);
            $communityHome = \URL::route('community-home', ['slug' => $community->id]);

            return redirect($communityHome);
        }

        \Session::flash('purchasemessage', 'Something went wrong, try again');
        $communityHome = \URL::route('community-home', ['slug' => $community->id]);

        return redirect($communityHome);
    }

    public function validateRideCoupon($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $coupon_code = $request->get('coupon_code');
        $selected_slot_id = $request->get('selected_slot_id');
        $selected_sim_id = $request->get('selected_sim_id');
        $selected_location_id = $request->get('selected_location_id');

        $user = \Auth::user();
        if ($coupon_code and $user and $user->ride_coupon and $user->ride_coupon == $coupon_code) {
            if ($user->ride_coupon_redeemed == 0) {
                $futureDate = date('Y-m-d', strtotime('+1 year', strtotime($user->ride_profile_completed_on)));
                if (strtotime(date('Y-m-d')) < strtotime($futureDate)) {
                    $couponslot = $this->communityRideTimeslotsRepository()->free15MinsCouponSlot($community->id);
                    if ($couponslot) {

                        $freeRideCost = $this->communityRideCostsRepository()->findByCmSIMSlotId($community->id, $selected_location_id, $selected_sim_id, $couponslot->id);

                        $selectedRideCost = $this->communityRideCostsRepository()->findByCmSIMSlotId($community->id, $selected_location_id, $selected_sim_id, $selected_slot_id);

                        if ($freeRideCost and $selectedRideCost) {
                            if ($freeRideCost->cost == $selectedRideCost->cost) {
                                return 'free';
                            }

                            if ($selectedRideCost->cost > $freeRideCost->cost) {
                                $cost = $selectedRideCost->cost - $freeRideCost->cost;

                                return number_format($cost, 2);
                            }

                            if ($freeRideCost->cost > $selectedRideCost->cost) {
                                return 'free';
                            }
                        }
                    }
                } else {
                    return 'expired';
                }
            } else {
                return 'redeemed';
            }
        }

        return 'invalid';
    }

    public function bookingRideDashboard($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);
		
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
			return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        return $this->render('user.ridebooking.dashboard.dashboard', ['community' => $community],
            ['title' => 'Book a Ride']
        );
    }

    public function rideBookingTopup($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        return $this->render('user.ridebooking.topup', ['posted_community' => $community],
            ['title' => 'Book a Ride']
        );
    }

    public function rideBookingTopupProcess($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        if ($community) {
            $purchasemessage = '';

            $fundquantity = $request->get('fundquantity');
            $purchase_page_type = $request->get('purchase_page_type');
            $payment_type = $request->get('payment_type');
            $stripeToken = $request->get('stripeToken');
            $customerName = $request->get('customerName');
            $customerEmail = $request->get('emailAddress');
            $customerAddress = $request->get('customerAddress');
            $customerCity = $request->get('customerCity');
            $customerZipcode = $request->get('customerZipcode');
            $customerState = $request->get('customerState');
            $customerCountry = $request->get('customerCountry');
            $cardNumber = $request->get('cardNumber');
            $cardCVC = $request->get('cardCVC');
            $cardExpMonth = $request->get('cardExpMonth');
            $cardExpYear = $request->get('cardExpYear');

            $payment_for = 'funding';
            $transaction_payment_type = $payment_type;

            $itemName = $request->get('item_details');
            $itemNumber = $request->get('item_number');
            $itemPrice = $request->get('price');
            $totalAmount = $request->get('total_amount');
            $currency = $request->get('currency_code');
            $orderNumber = $request->get('order_number');
            $total_amount_receivable = $request->get('total_amount_receivable');

            // require_once app_path('library/stripe-php/init.php');

            $totalAmountOriginal = $totalAmount;

            $totalAmount = $totalAmount * 100;
            $stripe = [
                'secret_key' => config('stripe_secret_key'),
                'publishable_key' => config('stripe_publishable_key'),
            ];

            $source_token = $stripeToken;

            \Stripe\Stripe::setApiKey($stripe['secret_key']);

            $customer = \Stripe\Customer::create([
                'name' => $customerName,
                'description' => 'Fund Account Payment',
                'email' => $customerEmail,
                'source' => $source_token, // This is for test
                'address' => ['city' => $customerCity, 'country' => $customerCountry, 'line1' => $customerAddress, 'line2' => '', 'postal_code' => $customerZipcode, 'state' => $customerState],
            ]);

            $transfer_group = rand(111111, 999999);

            $payDetails = \Stripe\Charge::create([
                'customer' => $customer->id,
                'amount' => $totalAmount,
                'currency' => $currency,
                'description' => $itemName,
                'metadata' => [
                    'order_id' => $orderNumber,
                ],
                'transfer_group' => $transfer_group,
            ]);

            $customer_id = $customer->id;
            $paymenyResponse = $payDetails->jsonSerialize();

            if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {

                $amountPaid = $paymenyResponse['amount'];
                $balanceTransaction = $paymenyResponse['balance_transaction'];
                $paidCurrency = $paymenyResponse['currency'];
                $paymentStatus = $paymenyResponse['status'];
                $paymentDate = date('Y-m-d H:i:s');

                // $amountPaidNew=$fundquantity;
                // $itemPrice =$fundquantity;

                $amountPaidNew = $totalAmountOriginal;
                $itemPrice = $totalAmountOriginal;

                $user_id = \Auth::user()->id;

                $payment = $this->communityRideTopupRepository()->addPayment($community, $user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, $total_amount_receivable);
                $purchasemessage = 'You have successfully loaded your account. Your transaction id is - '.$balanceTransaction;

            } else {
                $purchasemessage = 'Payment failed.';
            }

            \Session::flash('purchasemessage', $purchasemessage);

            return redirect(\URL::route('community-ride-booking-dashboard', ['slug' => $community->id]));
        }
    }

    public function rideBookingsAll($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }$userid = \Auth::user()->id;

        // $myRides=$this->communityPricingPlanPaymentRepository()->getMyRidingPaymentsCM($community->id,$userid);
        $myRides = $this->appointmentRepository()->getMyRides($community->id, $userid);

        return $this->render('user.ridebooking.my-rides', ['posted_community' => $community, 'myRides' => $myRides],
            ['title' => 'Book a Ride']
        );
    }

    public function rideBookingsHighlightedDates() {}

    public function rideGetSlots($slug, $sim_id, $location_id)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $slots = $this->communityRideCostsRepository()->getAllSlotsBySimLocation($community->id, $sim_id, $location_id);
        $options = "<option value=''>Select a slot</option>";

        foreach ($slots as $slot) {
            // $options.="<option value=".$slot->id.">".$slot->sim."</option>";

            $slt = $this->communityRideTimeslotsRepository()->getById($community->id, $slot);

            if ($slt) {
                $options .= '<option value='.$slt->id.'>Book a '.$slt->times.' '.$slt->name.' ride</option>';
            }
        }

        return $options;
    }

    public function rideLocationSet($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $user = \Auth::user();

        $message = '';
        $location_id = $request->get('location_id');
        if ($location_id) {

            $user->preferred_location = $location_id;
            $user->save();
            $message = 'Location saved successfuly';
        }

        $locations = $this->communityRideLocationsRepository()->getLocations($community->id);

        return $this->render('user.ridebooking.location-set', ['posted_community' => $community, 'locations' => $locations, 'user' => $user, 'message' => $message],
            ['title' => 'Book a Ride']
        );
    }

    public function rideNewsUpdates($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $myLocationId = \Auth::user()->preferred_location;

        $location = '';
        $posts = '';
        if ($myLocationId) {
            $location = $this->communityRideLocationsRepository()->getById($community->id, $myLocationId);
        }

        return $this->render('user.ridebooking.news-updates', ['posted_community' => $community, 'location' => $location, 'myLocationId' => $myLocationId],
            ['title' => 'Book a Ride']
        );
    }

    public function rideEventsUpdates($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $myLocationId = \Auth::user()->preferred_location;

        $location = '';
        $posts = '';
        if ($myLocationId) {
            $location = $this->communityRideLocationsRepository()->getById($community->id, $myLocationId);
        }

        return $this->render('user.ridebooking.events-updates', ['posted_community' => $community, 'location' => $location, 'myLocationId' => $myLocationId],
            ['title' => 'Book a Ride']
        );
    }

    public function rideGetDurationCost($slug, $location_id, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing') {
            return redirect($community->present()->url());
        }

        $duration = $request->get('duration');

        $location = $this->communityRideLocationsRepository()->getById($community->id, $location_id);

        $day = '';
        if ($duration == 'firsthalf') {
            $ride_cost = number_format($location->first_halfday_price, 2);
            $day = 'A half day - first half ';
        } elseif ($duration == 'secondhalf') {
            $ride_cost = number_format($location->second_halfday_price, 2);
            $day = 'A half day - second half ';
        } else {
            $ride_cost = number_format($location->fullday_price, 2);
            $day = 'A full day ';
        }

        $booking_summary = $day.' at our location located at '.$location->location;

        return json_encode([
            'ride_cost' => $ride_cost,
            'booking_summary' => $booking_summary,
        ]);
    }

    public function accountVerify($slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }
		
		$redirect_url = $request->get('redirect_url');

        if (! \Auth::check()) {
            $this->communityOutsideTheme($community);
            //$return_url = $community->present()->url('login');
			
			$urltype = 'returnurl';
            $urltypeid = '';
			
			$return_url = $community->present()->authUrl('login', ['urltype' => $urltype, 'urltypeid' => $urltypeid, 'returnUrl' => $redirect_url]);
			
        } else {
			if($redirect_url){
           		 $return_url = $redirect_url;
			}else{
				$return_url = \URL::route('user-account');
			}	 
        }

        $str = $request->get('str');
        $uid = $request->get('uid');
        $eml = $request->get('eml');

        $email = base64_decode($eml);

        $userData = $this->userRepository()->getById($uid);

        $message = 'Invalid link.';
        $status = 'fail';
        if ($userData) {
            if ($userData and $userData->is_email_verified == 1) {
                $message = 'Your email address alredy verified.';
            } elseif ($userData and $userData->email_address == $email and $userData->is_email_verified == 0 and $userData->email_verification_code == $str) {
                $message = 'Your email has been verified successfully. Thank you!';

                $userData->is_email_verified = 1;
                $userData->save();

                $status = 'success';
            }
        }

        return $this->render('user.verify-email', [
            'message' => $message,
            'return_url' => $return_url,
            'status' => $status,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function userAccountVerify(Request $request)
    {
        if (! \Auth::check()) {
            $return_url = \URL::route('user-home');
        } else {
            $return_url = \URL::route('user-account');
        }
		
		$redirect_url = $request->get('redirect_url');
		if($redirect_url){
			 $return_url = $redirect_url;
		}	

        $str = $request->get('str');
        $uid = $request->get('uid');
        $eml = $request->get('eml');

        $email = base64_decode($eml);

        $userData = $this->userRepository()->getById($uid);

        $message = 'Invalid link.';
        $status = 'fail';
        if ($userData) {
            if ($userData and $userData->is_email_verified == 1) {
                $message = 'Your email address alredy verified.';
            } elseif ($userData and $userData->email_address == $email and $userData->is_email_verified == 0 and $userData->email_verification_code == $str) {
                $message = 'Your email has been verified successfully. Thank you!';

                $userData->is_email_verified = 1;
                $userData->save();

                $status = 'success';
            }
        }

        return $this->render('user.verify-email', [
            'message' => $message,
            'return_url' => $return_url,
            'status' => $status,
        ], [
            'title' => $this->setTitle(''),
        ]);
    }

    public function communitySubscriptionPendingPayment($slug, $id)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);

        if (! $this->community) {
            return $this->notFound();
        }
        $community = $this->community;

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (\Auth::user()->isAdmin() || \Auth::user()->id == $community->user_id) {
            $result = $this->communityPricingPlanRepository()->doCommunitySubscriptionPendingPayment($community, $id);

            \Session::flash('message', 'Something went wrong, try again later.');
            if ($result) {
                \Session::flash('message', 'Payment successfully done, your transaction id is '.$result);
            }

            if (\Auth::user()->id == $community->user_id) {
                return redirect($community->present()->url('communitypaymenthistory'));
            }
        }

        return redirect($community->present()->url());
    }

    public function notFound()
    {
        return $this->theme->section('error-page');
    }

    public function rideStudentVerification($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);

        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $urltype = 'returnurl';
            $urltypeid = '';
            $currentUrl = \URL::to('/').$_SERVER['REQUEST_URI'];

            return redirect($community->present()->authUrl('login', ['urltype' => $urltype, 'urltypeid' => $urltypeid, 'returnUrl' => $currentUrl]));
        }

        if ($val = $request->get('val')) {
            $application = $this->communityRideStudentVerificationRepository()->submitApplication($community, $val);

            \Session::flash('message', $application);
            $verificationUrl = \URL::route('community-ride-student-verification', ['slug' => $community->id]);

            return redirect($verificationUrl);
        }

        $locations = $this->communityRideLocationsRepository()->getLocations($community->id);

        return $this->render('user.ridebooking.student-verification', ['posted_community' => $community, 'locations' => $locations],
            ['title' => 'Book a Ride']
        );
    }

    public function rideStudentVerificationEmail($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community || ($community->race_community == 0 and $this->selected_pricing_plan_type!='racing')) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $location_id = $request->get('location_id');
        $institute_email_id = $request->get('institute_email_id');

        $location = $this->communityRideLocationsRepository()->getById($community->id, $location_id);
        if ($location) {
            return $this->communityRideStudentVerificationRepository()->sendCode($community, $location, $institute_email_id);
        }
    }

    public function emailEventLogin($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $code = $request->get('code');
        $uid = $request->get('uid');
        $eml = $request->get('eml');

        $uid = base64_decode($uid);
        $eml = base64_decode($eml);

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
        $homecontents = $community->present()->getHomeContents();
        if ($homecontents) {
            if ($homecontents->website_title) {
                $this->theme->share('title', $homecontents->website_title);
                \Config::set('site_title', $homecontents->website_title);
            }
        } else {
            $this->theme->share('title', $community->title);
            \Config::set('site_title', $homecontents->website_title);
        }

        $this->theme->share('ogImage', $community->present()->getEventAppLogo());
        $this->theme->share('site_description', $community->title);

        $user = $this->userRepository()->findByBothEmail($eml);
        if ($user->active == 1 and $user->activated == 1 and $user->id == $uid and $user->email_login_code == $code) {

            if ($login = $this->userRepository()->loginUsingId($user->id)) {
                \Session::put('loginFromApp', 'loginFromApp');
                \Session::put('event_app_login', 'event_app_login');
                \Session::put('event_login_user_id', $uid);
                \Session::put('event_login_community_id', $community->id);
                \Session::put('event_app_login_url', $community->present()->url('eventaccesstickettrans'));

                $cmUrl = $community->present()->url();
                \Session::put('theCommunityId', $community->id);
                \Session::put('community_url', $cmUrl);

                if (\Auth::check()) {
                    saveUserSession();

                    \Auth::user()->present()->saveVisitingCommunity($community->id);
                }

                return redirect($community->present()->url('appevents'));
            } else {
                return $this->render('eventemaillogin.failed', ['community' => $community]);
            }
        } else {
            return $this->render('eventemaillogin.failed', ['community' => $community]);
        }
    }

    public function eventAccessTicket($slug, $post_id)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (\Auth::check()) {
            return redirect($community->present()->url('appevents'));
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
        $homecontents = $community->present()->getHomeContents();
        if ($homecontents) {
            if ($homecontents->website_title) {
                $this->theme->share('title', $homecontents->website_title);
                \Config::set('site_title', $homecontents->website_title);
            }
        } else {
            $this->theme->share('title', $community->title);
            \Config::set('site_title', $homecontents->website_title);
        }

        $this->theme->share('ogImage', $community->present()->getEventAppLogo());
        $this->theme->share('site_description', $community->title);

        $post = $this->postRepository()->getById($post_id);
        if ($post and $post->community_id == $community->id) {
            return $this->render('eventemaillogin.login', ['community' => $community, 'post' => $post]);
        }

        return $this->notFound();
    }

    public function eventAccessTicketTrans($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (\Auth::check()) {
            return redirect($community->present()->url('appevents'));
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
        $homecontents = $community->present()->getHomeContents();
        if ($homecontents) {
            if ($homecontents->website_title) {
                $this->theme->share('title', $homecontents->website_title);
                \Config::set('site_title', $homecontents->website_title);
            }
        } else {
            $this->theme->share('title', $community->title);
            \Config::set('site_title', $homecontents->website_title);
        }

        $this->theme->share('ogImage', $community->present()->getEventAppLogo());
        $this->theme->share('site_description', $community->title);

        return $this->render('eventemaillogin.login-transaction', ['community' => $community]);
    }

    public function eventAccessTicketLogin($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (\Auth::check()) {
            return redirect($community->present()->url('appevents'));
        }

        $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
        $homecontents = $community->present()->getHomeContents();
        if ($homecontents) {
            if ($homecontents->website_title) {
                $this->theme->share('title', $homecontents->website_title);
                \Config::set('site_title', $homecontents->website_title);
            }
        } else {
            $this->theme->share('title', $community->title);
            \Config::set('site_title', $homecontents->website_title);
        }

        $this->theme->share('ogImage', $community->present()->getEventAppLogo());
        $this->theme->share('site_description', $community->title);

        return $this->render('eventemaillogin.login', ['community' => $community]);
    }

    public function getEentTiketAccess($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return 'Invalid community.';
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        $email_address = $request->get('email_address');
        $access_type = $request->get('access_type');
        $url_type = $request->get('url_type');

        $emailLoginUrl = $community->present()->url('eventaccessticketlogin');

        if ($access_type == 'email') {
            $message = 'Invalid Request: provide the valid email address.';
        } else {
            $message = "Invalid Request: provide the valid transaction id or <a href='".$emailLoginUrl."' style='text-decoration: underline; color:#f00; font-weight:bold;'>click here</a> to request your event access with your registered email id";
        }

        $url = '';
        $status = 0;

        if ($email_address) {
            $user = '';

            if ($access_type == 'email' and preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/', $email_address)) {
                $user = $this->userRepository()->findByBothEmail($email_address);
                if ($user and $user->active == 0) {
                    $user->active = 1;
                    $user->activated = 1;
                    $user->save();
                }
            } else {
                $transaction = $this->postEventsPaymentRepository()->check_txnid($email_address);
                if ($transaction) {
                    $event = $this->postEventsRepository()->getById($transaction->event_id);
                    if ($event and $event->community_id == $community->id) {
                        $user = $this->userRepository()->findById($transaction->user_id);
                        if ($user and $user->active == 0) {
                            $user->active = 1;
                            $user->activated = 1;
                            $user->save();
                        }
                    }
                }
            }

            if ($user) {
                if ($user->active == 1 and $user->activated == 1) {
                    if ($access_type == 'email') {
                        $sendLink = $this->userRepository()->sendEmailLoginLink($user, $community);
                        $message = 'Please check your email, including your junk folder! In rare cases, it may take up to 10 minutes for the email to arrive.';
                        $status = 0;
                    } else {
                        if ($login = $this->userRepository()->loginUsingId($user->id)) {
                            \Session::put('loginFromApp', 'loginFromApp');
                            \Session::put('event_app_login', 'event_app_login');
                            \Session::put('event_login_user_id', $user->id);
                            \Session::put('event_login_community_id', $community->id);
                            \Session::put('event_app_login_url', $community->present()->url('eventaccesstickettrans'));

                            $cmUrl = $community->present()->url();
                            \Session::put('theCommunityId', $community->id);
                            \Session::put('community_url', $cmUrl);

                            if (\Auth::check()) {
                                saveUserSession();
                                \Auth::user()->present()->saveVisitingCommunity($community->id);
                            }

                            $url = $community->present()->url('appevents');
                            $message = 'Login successfull.';
                            $status = 1;
                        }
                    }
                } else {
                    $message = 'Your account is not yet activated';
                    $status = 0;
                }
            }
        }

        if ($url_type == 'redirect' and $status == 1) {
            return redirect($url);
        } else {
            return json_encode([
                'message' => $message,
                'url' => $url,
                'status' => $status,
            ]);
        }
    }

    public function appEvents($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            return redirect($community->present()->url('eventaccessticketlogin'));
        }

        $timeZone = 'America/New_York';
        if ($community->timezone) {
            $timeZone = $community->timezone;
        }

        date_default_timezone_set($timeZone);

        $events = $this->postEventsRepository()->getCommunityEventsApp($community->id);

        return $this->render('eventemaillogin.events', ['community' => $community, 'events' => $events]);
    }

    public function eventAccessTicketDetails($slug, $post_id)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            return redirect($community->present()->url('eventaccessticketlogin'));
        }

        $event = $this->postEventsRepository()->getByPostId($post_id);
        $post = $this->postRepository()->getById($post_id);

        return $this->render('eventemaillogin.event-details', ['community' => $community, 'evt' => $event, 'post' => $post]);
    }

    public function appEventsNews($slug, $post_id)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            return redirect($community->present()->url('eventaccessticketlogin'));
        }

        $event = $this->postEventsRepository()->getByPostId($post_id);
        $newsIds = $this->postEventsNewsRepository()->getPostIds($post_id);
        $posts = $this->postRepository()->getEventsNewsPosts($newsIds);
        $post = $this->postRepository()->getById($post_id);

        return $this->render('eventemaillogin.event-news', ['community' => $community, 'evt' => $event, 'event_post' => $post, 'posts' => $posts]);
    }

    public function appEventShareProfile($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            return redirect($community->present()->url('eventaccessticketlogin'));
        }

        $email = $request->get('email');
        $ipUrl = $request->get('ipUrl');

        $mail_from_email = $community->present()->getFromEmailAddress();

        $subject = 'Visit My Website';

        $user_data = \Auth::user();

        try {
            $this->mailer->send('emails.community.visit-my-profile', [
                'fullname' => $user_data->fullname,
                'email_address' => $user_data->email_address,
                'community_id' => $community->id,
                'receiver_email' => $email,
                'user_url' => $user_data->present()->url(),
                'ipUrl' => $ipUrl,
            ], function ($mail) use ($email, $subject, $mail_from_email, $community) {
                $mail->to($email, $email)
                    ->subject($subject)
                    ->from($mail_from_email, $community->title);
            });
        } catch (\Exception $e) {
            // return $e;
        }

        return 'Profile shared successfully!';
    }   

    public function liveMarketplace()
    {
        $token = 'eyJ0b2tlbkNvbnRlbnQiOnsiaXNzdWVkRm9yIjoidGVzdCIsInNjb3BlIjoiIiwiaXNzdWVkQXQiOjE3MzQ5MzQwMjEyMzEsImV4cGlyZXNBdCI6MTczNjIzMDAyMTIzMSwidG9rZW5fdHlwZSI6IlVTRVIifSwiYV90IjoiZXlKbGJtTWlPaUpCTVRJNFEwSkRMVWhUTWpVMklpd2lZV3huSWpvaVJVTkVTQzFGVXlJc0ltdHBaQ0k2SW1WdVl5SXNJbVZ3YXlJNmV5SnJkSGtpT2lKRlF5SXNJbU55ZGlJNklsQXRNalUySWl3aWVDSTZJalYwUjJSV2JYUmlORmhDT1VveU0weFhSa3h3TUZnNFlrNVdOREZYYVdSRk5XWjJUR2xJU0ZaaGFXc2lMQ0o1SWpvaWNHMWllRVZ2WmxkRlVGOXViSGQwYWxOdGJtTmZkek56UmtGelprcElOalJvVlU5d2NFUnplRzk1VFNKOWZRLi5lWEg2TkFQNzJOV2RVeE56VUdGRlVRLlhyTnJoZzBNajFUODQ5SHRKTTBHNlMxQmdQWVUyWDRrOVZ1RjB3WXI4M3J4SVhIdnFwb1Yxb2dhdkF1Xzk0MHI0SjBqUVhLTGRfOFlEbDVISkE4S284Zl9qNTNTbm9oZkhrU0lnS2RzeU5lRUkxZ3B4VV9fTjlwV1B0QXpjU0xSak5GaEtabjFUQjhQN0ZxSFpSNUNwa3VSczJtSURBTVlpWWxEZ3lWdm41MHhIOHNiN0FWQWZNUFV3WDlBamh1Y2pyeWxUTnhxVzk2M1Fpc2hSSTJWNzBtdDhQU1U4cUxKX19WcnJYSmg2QUZLUllVRGJYZnR6QlczbGtmZDIzZkt6UGZSVm9VQUE0al9aRE5ET0JlRmVORUxZdzBMWjFwOE5PSTVNTnpmRWkwZUhKeVgxVWdTZndGMEV2VUI2dkdZTElsRE96eXp4eVc3MDZ0TkI2Z1hNQlMxU2NpckpER3F1cnJJNFBCc1YzTkZ3WURTN1dxMk5IMEl5NWNyek1RcDBiQ1V0UEgzeVlMSUhLenhySXJlV0JrejF6RExyaVN4RnZmWFIzMWdrc0x4SHpZdHQ5dk1BeDRrVEZUdjU1ZVdSRnUxYUNCVklKNU1MMzBqSUhrenI2MkNmTVFSY0NfT1BZbTE5d1dJVENWLTJkWU5iZVh0eU1zcm1EVmotSTNRaGRvbUtVanNSTkU3UzZNcFAtWWxHRllObGthZlNkdDFXb0V1ZDhlSmdVcEtxNmhmYVJPX3dIVDlGc21zd0d3aF9aUFFSX1UzdUVTWGJUYzVpM05TcVFfTlNCQ0pJWjZoZHVnMm5FYnFCa0hhQnRTNzBISjh6WFFkVmFibUVsMFhMbTVHSXdHNnRERTFjbjhBZVJ3NDBwaFdHZHBuR1psdElDZWlOMmtkaDdLQjBfaU11M3Y0UVA4SGxzVjhacmFPSVNKLTVQVW1SdlJBeFhoQzVEYXlxcGdybV9qMnVOU00yZlRJTDJOcHpSMXhjc2VrWmRuWUdudFBYWWpWUDVIdnlqbE11NjIzUDlzMWdQUm0zSUNVZlZYMmNWbjVlcW5MbFpkMktldkp5UmZ4QmNKSWxNc1I3YWk3amZ0bWxEcXotY0lsaUtCQndaTUJPWUZIRnNsd29SYmQzTmRhVXhWbXZoT1puSnhvZTdBRV96NU9QaWpvYlZ0T1FPbkd6UWpBVTRsYkhEMmxoR0NnclQ5RVBQV2I0US5FM1ZFSGdQM2pSSDRfVWF4MHN6QzZBIn0=';

        $client = new \GuzzleHttp\Client;
        // Get Balance API

        try {
            $response = $client->request('POST', 'https://canvas.xoxoday.com/chef/v1/oauth/api/', [
                'body' => '{"query":"plumProAPI.query.getBalance","tag":"plumProAPI","variables":{"data":{}}}',
                'headers' => [
                    'accept' => 'application/json',
                    'authorization' => 'Bearer '.$token,
                    'content-type' => 'application/json',
                ],
            ]);

            return $response->getBody();
        } catch (\Exception $e) {
            $message = $e->getMessage();

            return $message;
        }

        // Get vouchers API

        /*try {
            $response = $client->request('POST', 'https://canvas.xoxoday.com/chef/v1/oauth/api/', [
              'body' => '{"query":"plumProAPI.mutation.getVouchers","tag":"plumProAPI","variables":{"data":{"limit":10,"page":1,"exchangeRate":1,"sort":{"field":"name","order":"ASC"}}}}',
              'headers' => [
                'accept' => 'application/json',
                'authorization' => 'Bearer '.$token,
                'content-type' => 'application/json',
              ],
            ]);

            $result=$response->getBody();

            return $result;
        } catch(\Exception $e) {
            $message=$e->getMessage();

            return $message;
        }*/
    }

    public function communityOuterPayment($slug)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if (! ($community->isOwner())) {
            redirect('home')->send();
        }

        $this->theme->share('community', $community);

        $cards = $this->communityPricingPlanPaymentCardsRepository()->getAllCards($community->id, $community->user_id, 'community_plan');
        $planDetails = $this->communityPricingPlanRepository()->getByCommunityId($community->id);
        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

		$allPlans=$this->pricingPlansRepository()->getPlans();
		$planIds = [];
        foreach ($allPlans as $plan) {
            $planIds[] = $plan->plan_id;
        }
        if ($community->special_plan_access == 1) {
            $planIds[] = 4;
        }

        $planFeaturesByPlanId = $this->plansFeaturesSelectedRepository()->getSelectedFeaturesForPlans($planIds);
		
        return $this->render('user.community-plan-payment', ['community' => $community, 'cards' => $cards, 'planDetails' => $planDetails, 'default_card' => $default_card,'allPlans'=>$allPlans,'planFeaturesByPlanId'=>$planFeaturesByPlanId], [
            'title' => $this->setTitle('Community Payment'),
        ]);
    }

    public function makePlanPaymentOuter($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        if (! ($community->isOwner())) {
            redirect('home')->send();
        }

        $type = $request->get('type');
        $plan_id = $request->get('plan_id');

        if ($plan_id == 4) {
            if ($community->special_plan_access == 0) {
                return redirect($community->present()->url('communitypayment'));
            }
        }

        $planDetails = $community->present()->getPlanDetails();

        $cmPlanDetails = $community->present()->getPricingPlan($plan_id);
        if ($cmPlanDetails and $cmPlanDetails->is_plan_free == 1) {
            $this->communityPricingPlanRepository()->savePlan($community->id, $community->user_id, $plan_id, $type);
            \Session::flash('message', 'Your plan changed successfully ');

            return redirect($community->present()->url('communitypayment'));
        }

        $pay_amount = '';

        if ($cmPlanDetails) {
            $purchased_space = $community->purchased_space_in_mb;
            $space_charges = config('community-space-monthly-charges-per-mb');
            $purchased_space_charges = '';

            if ($type == 'yearly') {
                $pay_amount = $cmPlanDetails->price_yearly;

               /* $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan_id, $cmPlanDetails);
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                $column_name = 'increased_member_limit';
                $increasedLimit = $community->$column_name;

                if ($extraMembers > 0) {
                    $increasedLimit = $increasedLimit + $extraMembers;
                }

                if ($increasedLimit and $cmPlanDetails->monthly_price_per_extra_user) {
                    $increasedAmount = $increasedLimit * 12 * $cmPlanDetails->monthly_price_per_extra_user;
                    $pay_amount = $pay_amount + $increasedAmount;
                }

                if ($purchased_space and $space_charges) {
                    $purchased_space_charges = $purchased_space * 12 * $space_charges;
                    $pay_amount = $pay_amount + $purchased_space_charges;
                }*/
				
            } else {
                $pay_amount = $cmPlanDetails->price_monthly;

                /*$getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan_id);
                $communityMembers = $community->countMembers();
                $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                $column_name = 'increased_member_limit';
                $increasedLimit = $community->$column_name;
                if ($extraMembers > 0) {
                    $increasedLimit = $increasedLimit + $extraMembers;
                }

                if ($increasedLimit and $cmPlanDetails->monthly_price_per_extra_user) {
                    $increasedAmount = $increasedLimit * 1 * $cmPlanDetails->monthly_price_per_extra_user;
                    $pay_amount = $pay_amount + $increasedAmount;
                }

                if ($purchased_space and $space_charges) {
                    $purchased_space_charges = $purchased_space * 1 * $space_charges;
                    $pay_amount = $pay_amount + $purchased_space_charges;
                }*/
            }
        }

        $this->theme->share('community', $community);

        if ($type == 'yearly' || $type == 'monthly') {
            return $this->render('community.pannel.plan.make-payment', ['type' => $type, 'plan_id' => $plan_id, 'purchasemessage' => '', 'pay_amount' => $pay_amount], [
                'title' => $this->setTitle('Pages'),
            ]);
        }
    }

    public function payingForPlan($slug, Request $request)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        $this->community = $community;

        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        if (! empty($request->get('stripeToken'))) {

            $plan = $request->get('plan');
            $payment_type = $request->get('payment_type');
            $stripeToken = $request->get('stripeToken');
            $customerName = $request->get('customerName');
            $customerEmail = $request->get('emailAddress');
            $customerAddress = $request->get('customerAddress');
            $customerCity = $request->get('customerCity');
            $customerZipcode = $request->get('customerZipcode');
            $customerState = $request->get('customerState');
            $customerCountry = $request->get('customerCountry');
            $cardNumber = $request->get('cardNumber');
            $cardCVC = $request->get('cardCVC');
            $cardExpMonth = $request->get('cardExpMonth');
            $cardExpYear = $request->get('cardExpYear');

            $payment_for = 'plan';
            $transaction_payment_type = $payment_type;

            // require_once app_path('library/stripe-php/init.php');

            $stripe = [
                'secret_key' => config('stripe_secret_key'),
                'publishable_key' => config('stripe_publishable_key'),
            ];

            if (config('stripe_mode') == 'test') {
                $source_token = 'tok_visa';
            } else {
                $source_token = $stripeToken;
            }

            $itemName = $request->get('item_details');
            $itemNumber = $request->get('item_number');
            $itemPrice = $request->get('price');
            $totalAmount = $request->get('total_amount');
            $currency = $request->get('currency_code');
            $orderNumber = $request->get('order_number');

            $actual_amount = $itemPrice;

            $plan_data = $community->present()->getPricingPlan($plan);

            $purchased_space = $community->purchased_space_in_mb;
            $space_charges = config('community-space-monthly-charges-per-mb');
            $purchased_space_charges = '';

            if ($plan_data) {
                if ($payment_type == 'yearly') {
                    $pay_amount = $plan_data->price_yearly;

                    /*$getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan, $plan_data);
                    $communityMembers = $community->countMembers();
                    $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                    $column_name = 'increased_member_limit';
                    $increasedLimit = $community->$column_name;

                    if ($extraMembers > 0) {
                        $increasedLimit = $increasedLimit + $extraMembers;
                    }

                    if ($increasedLimit and $plan_data->monthly_price_per_extra_user) {
                        $increasedAmount = $increasedLimit * 12 * $plan_data->monthly_price_per_extra_user;
                        $pay_amount = $pay_amount + $increasedAmount;
                    }

                    if ($purchased_space and $space_charges) {
                        $purchased_space_charges = $purchased_space * 12 * $space_charges;
                        $pay_amount = $pay_amount + $purchased_space_charges;
                    }*/
                } else {
                    $pay_amount = $plan_data->price_monthly;

                   /* $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($plan, $plan_data);
                    $communityMembers = $community->countMembers();
                    $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                    $column_name = 'increased_member_limit';
                    $increasedLimit = $community->$column_name;
                    if ($extraMembers > 0) {
                        $increasedLimit = $increasedLimit + $extraMembers;
                    }

                    if ($increasedLimit and $plan_data->monthly_price_per_extra_user) {
                        $increasedAmount = $increasedLimit * 1 * $plan_data->monthly_price_per_extra_user;
                        $pay_amount = $pay_amount + $increasedAmount;
                    }

                    if ($purchased_space and $space_charges) {
                        $purchased_space_charges = $purchased_space * 1 * $space_charges;
                        $pay_amount = $pay_amount + $purchased_space_charges;
                    }*/
                }

                $totalAmount = $pay_amount * 100;
                $actual_amount = $pay_amount;
            }

            $coupon_applied = $request->get('coupon_applied');
            $coupon_code = $request->get('coupon_code_applied');
            $coupon_code_type = $request->get('coupon_code_type');

            $discount_percentage = 0;
            $new_amount = 0;
            $discounted_amount = 0;

            if ($coupon_applied == 1 and $coupon_code) {
                $coupon_result = $this->communityCouponsRepository()->getByCodeActive($coupon_code);
                if ($coupon_result) {
                    $from_date = $coupon_result->valid_from;
                    $valid_to = $coupon_result->valid_to;
                    $todays_date = date('Y-m-d');
                    if ($todays_date >= $from_date and $todays_date <= $valid_to) {
					
						if($coupon_result->coupon_type==1){
							 $discount_percentage = $coupon_result->discount_percentage;
							 if ($coupon_result->discount_percentage > 0) {
								if ($coupon_result->discount_percentage > 100) {
									$discount_percentage = 100;
								}
								$discounted_amount = ($actual_amount / 100) * $discount_percentage;
								$new_amount = $actual_amount - $discounted_amount;
								$discounted_amount = $discounted_amount;
								$discount_percentage = $discount_percentage;
								$new_amount = round($new_amount, 2);
								$totalAmount = $new_amount * 100;
							}
						}else{
							$discount_percentage = "";
							if ($coupon_result->amount > 0) {
								$discount_percentage = $coupon_result->amount;
								$discounted_amount = $coupon_result->amount;
								$new_amount = $actual_amount - $discounted_amount;
								$discounted_amount = $discounted_amount;
								$discount_percentage = $discount_percentage;
								$new_amount = round($new_amount, 2);
								$totalAmount = $new_amount * 100;
							}
						}
                       
                    }
                }
            }

            if ((int) $totalAmount <= 0 && (int) $coupon_applied === 1) {
                $user_id = \Auth::user()->id;
                $paymentDate = date('Y-m-d H:i:s');
                $transactionId = 'COUPON-' . date('YmdHis') . '-' . rand(1000, 9999);
                $paidCurrency = strtoupper((string) ($currency ?: 'USD'));
                $amountPaidNew = 0;
                $itemPrice = 0;
                $customer_id = '';

                $payment = $this->communityPricingPlanPaymentRepository()->addPayment($community, $user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $transactionId, 'succeeded', $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, $plan);
                if ($payment) {
                    $payment->coupon_applied = $coupon_applied;
                    $payment->coupon_code = $coupon_code;
                    $payment->discount_percentage = $discount_percentage;
                    $payment->actual_amount = $actual_amount;
                    $payment->save();

                    if($coupon_applied==1){
                        $this->communityCouponsRepository()->updateCouponStatus($coupon_code,$payment->user_id,'community_plan_purchase',$payment->id);
                    }

                    $invoiceData = $this->communityInvoiceRepository()->getSubscriptionInvoice($community->id, $payment->id);
                    if ($invoiceData) {
                        $invoiceData->total_amount = $actual_amount;
                        $invoiceData->coupon_applied = $coupon_applied;
                        $invoiceData->coupon_code = $coupon_code;
                        $invoiceData->discount_percentage = $discount_percentage;
                        $invoiceData->actual_amount = $amountPaidNew;
                        $invoiceData->save();
                    }
                }

                $purchasemessage = 'You have successfully purchased the plan. Your transaction id is - '.$transactionId;
                $this->theme->share('community', $community);

                return $this->render('community.pannel.plan.make-payment', ['type' => $payment_type, 'plan_id' => '', 'purchasemessage' => $purchasemessage, 'pay_amount' => ''], [
                    'title' => $this->setTitle('Pages'),
                ]);
            }

            if (empty($stripeToken)) {
                $purchasemessage = 'Payment failed.';
                $this->theme->share('community', $community);

                return $this->render('community.pannel.plan.make-payment', ['type' => $payment_type, 'plan_id' => '', 'purchasemessage' => $purchasemessage, 'pay_amount' => ''], [
                    'title' => $this->setTitle('Pages'),
                ]);
            }

            \Stripe\Stripe::setApiKey($stripe['secret_key']);

            $customer = \Stripe\Customer::create([
                'name' => $customerName,
                'description' => 'Plan Payment',
                'email' => $customerEmail,
                'source' => $source_token, // This is for test
                'address' => ['city' => $customerCity, 'country' => $customerCountry, 'line1' => $customerAddress, 'line2' => '', 'postal_code' => $customerZipcode, 'state' => $customerState],
            ]);

            // return $totalAmount;

            $payDetails = \Stripe\Charge::create([
                'customer' => $customer->id,
                'amount' => $totalAmount,
                'currency' => $currency,
                'description' => $itemName,
                'metadata' => [
                    'order_id' => $orderNumber,
                ],
            ]);

            $customer_id = $customer->id;
            $paymenyResponse = $payDetails->jsonSerialize();

            if ($paymenyResponse['amount_refunded'] == 0 && empty($paymenyResponse['failure_code']) && $paymenyResponse['paid'] == 1 && $paymenyResponse['captured'] == 1) {

                $amountPaid = $paymenyResponse['amount'];
                $balanceTransaction = $paymenyResponse['balance_transaction'];
                $paidCurrency = $paymenyResponse['currency'];
                $paymentStatus = $paymenyResponse['status'];
                $paymentDate = date('Y-m-d H:i:s');
                $amountPaidNew = $amountPaid / 100;
                $itemPrice = $amountPaid / 100;

                $user_id = \Auth::user()->id;

                $payment = $this->communityPricingPlanPaymentRepository()->addPayment($community, $user_id, $customerName, $customerEmail, $cardNumber, $cardCVC, $cardExpMonth, $cardExpYear, $itemName, $itemNumber, $itemPrice, $paidCurrency, $amountPaidNew, $balanceTransaction, $paymentStatus, $paymentDate, $payment_for, $transaction_payment_type, $customer_id, $community->id, $plan);
                if ($payment) {
                    $payment->coupon_applied = $coupon_applied;
                    $payment->coupon_code = $coupon_code;
                    $payment->discount_percentage = $discount_percentage;
                    $payment->actual_amount = $actual_amount;
                    $payment->save();
					
					if($coupon_applied==1){
						$this->communityCouponsRepository()->updateCouponStatus($coupon_code,$payment->user_id,'community_plan_purchase',$payment->id);
					}

                    $invoiceData = $this->communityInvoiceRepository()->getSubscriptionInvoice($community->id, $payment->id);
                    if ($invoiceData) {
                        $invoiceData->total_amount = $actual_amount;
                        $invoiceData->coupon_applied = $coupon_applied;
                        $invoiceData->coupon_code = $coupon_code;
                        $invoiceData->discount_percentage = $discount_percentage;
                        $invoiceData->actual_amount = $amountPaidNew;
                        $invoiceData->save();
                    }
                }

                $purchasemessage = 'You have successfully purchased the plan. Your transaction id is - '.$balanceTransaction;
            } else {
                $purchasemessage = 'Payment failed.';
            }

            $this->theme->share('community', $community);

            return $this->render('community.pannel.plan.make-payment', ['type' => $payment_type, 'plan_id' => '', 'purchasemessage' => $purchasemessage, 'pay_amount' => ''], [
                'title' => $this->setTitle('Pages'),
            ]);
        }
    }

    public function communityPaymentRedirect($slug, $uid)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        $this->community = $community;
        if ($community) {
            $uid = base64_decode($uid);
            if ($community->user_id == $uid) {
                $user = $community->user;
                $community_subscription_url=$this->community->present()->url('communitypayment');
				
				return redirect($community_subscription_url);
				
                //$community_subscription_url = $this->community->present()->url('communitypaymenttransactions');
               // $domainUrl = $community->present()->getCommunityDomainUrl();
               // $getUrlHostname = getUrlHostnameScheme($domainUrl);
                //$domainUrlNew = $getUrlHostname.'/cmownpage?lgkey='.$user->login_key.'&lgurl='.$community_subscription_url;

               // return redirect($domainUrlNew);
            }
        }

        return redirect('home')->send();
    }

    public function couponValidate(Request $request)
    {
        $type = $request->get('type');
        $coupon_code = $request->get('coupon_code');
        $amount = $request->get('amount');
        $paytype = $request->get('paytype');
        $payid = $request->get('payid');
        $cmid = $request->get('cmid');
		$apply_type = $request->get('apply_type'); 
		$apply_type_id = $request->get('apply_type_id'); 
		
        $status = 0;
        $message = 'Invalid coupon.';
        $discount_percentage = 0;
        $new_amount = 0;
        $discounted_amount = 0;

        $increasedAmount = 0;

        $purchased_space_charges = 0;

        /*if ($type == 1 and $cmid) {
            $community = $this->communityRepository()->getBySlug($cmid);
            if ($community) {
                $plan_data = $community->present()->getPricingPlan($payid);

                $purchased_space = $community->purchased_space_in_mb;
                $space_charges = config('community-space-monthly-charges-per-mb');

                if ($plan_data) {
                    if ($paytype == 'yearly') {

                        $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($payid, $plan_data);
                        $communityMembers = $community->countMembers();
                        $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                        $column_name = 'increased_member_limit';
                        $increasedLimit = $community->$column_name;

                        if ($extraMembers > 0) {
                            $increasedLimit = $increasedLimit + $extraMembers;
                        }

                        if ($increasedLimit and $plan_data->monthly_price_per_extra_user) {
                            $increasedAmount = $increasedLimit * 12 * $plan_data->monthly_price_per_extra_user;
                        }

                        if ($purchased_space and $space_charges) {
                            $purchased_space_charges = $purchased_space * 12 * $space_charges;
                        }
                    } else {
                        $getAllowedMembersInPlan = $community->present()->getAllowedMembersInPlan($payid, $plan_data);
                        $communityMembers = $community->countMembers();
                        $extraMembers = $communityMembers - $getAllowedMembersInPlan;

                        $column_name = 'increased_member_limit';

                        $increasedLimit = $community->$column_name;
                        if ($extraMembers > 0) {
                            $increasedLimit = $increasedLimit + $extraMembers;
                        }

                        if ($increasedLimit and $plan_data->monthly_price_per_extra_user) {
                            $increasedAmount = $increasedLimit * 1 * $plan_data->monthly_price_per_extra_user;
                        }

                        if ($purchased_space and $space_charges) {
                            $purchased_space_charges = $purchased_space * 1 * $space_charges;
                        }
                    }
                }
            }
        }*/
		
		
        $planAmount = $amount;
        $discount_percentage_value = '';

        if ($increasedAmount) {
            $amount = $amount + $increasedAmount;
        }

        if ($purchased_space_charges) {
            $amount = $amount + $purchased_space_charges;
        }
		
		$coupon = $this->communityCouponsRepository()->getByCodeActive($coupon_code);
		if(!$coupon){
			$message='Invalid coupon code';
		}else{
       
            $from_date = $coupon->valid_from;
            $valid_to = $coupon->valid_to;

            $todays_date = date('Y-m-d');
            if ($todays_date >= $from_date and $todays_date <= $valid_to) {
				
				if($coupon->community_id==0){
					if($coupon->coupon_type==1){
						$status = 1;
						$message = 'Coupon applied successfully.';
						$discount_percentage = $coupon->discount_percentage;
						if ($coupon->discount_percentage > 0) {
							if ($coupon->discount_percentage > 100) {
								$discount_percentage = 100;
							}
		
							$discounted_amount = ($amount / 100) * $discount_percentage;
							$new_amount = $amount - $discounted_amount;
							$discounted_amount = number_format($discounted_amount, 2, '.', ',');
							$discount_percentage_value = $discount_percentage;
							$discount_percentage = $discount_percentage.'%';
						}
					}else{
						$status = 1;
						$message = 'Coupon applied successfully.';
						//$discount_percentage = $coupon->amount;
						$discount_percentage ="";
						if ($coupon->amount > 0) {
							
							$discounted_amount = $coupon->amount;
							$new_amount = $amount - $discounted_amount;
							$discounted_amount = number_format($discounted_amount, 2, '.', ',');
							$discount_percentage_value = $discount_percentage;
							$discount_percentage = "Flat".$discount_percentage;
						}
					}
				}else{
					if($apply_type=='socila_media_products'){
						 $product=$this->businessProductsRepository()->getById($apply_type_id);
						 if($product and $product->post_id){
							$post=$this->postRepository()->getById($product->post_id);
							if($post){
								if($post->posted_in_community==$coupon->community_id){
									if($coupon->coupon_type==1){
										$status = 1;
										$message = 'Coupon applied successfully.';
										$discount_percentage = $coupon->discount_percentage;
										if ($coupon->discount_percentage > 0) {
											if ($coupon->discount_percentage > 100) {
												$discount_percentage = 100;
											}
						
											$discounted_amount = ($amount / 100) * $discount_percentage;
											$new_amount = $amount - $discounted_amount;
											$discounted_amount = number_format($discounted_amount, 2, '.', ',');
											$discount_percentage_value = $discount_percentage;
											$discount_percentage = $discount_percentage.'%';
										}
									}else{
										$status = 1;
										$message = 'Coupon applied successfully.';
										//$discount_percentage = $coupon->discount_percentage;
										$discount_percentage ="";
										if ($coupon->amount > 0) {
											
											$discounted_amount = $coupon->amount;
											$new_amount = $amount - $discounted_amount;
											$discounted_amount = number_format($discounted_amount, 2, '.', ',');
											$discount_percentage_value = $discount_percentage;
											$discount_percentage = "Flat".$discount_percentage;
										}
									}
								}
							}
						 }
					}elseif($apply_type=='store_products' || $apply_type=='page_topup'){
						$page=$this->pageRepository()->getById($apply_type_id);
						if($page->community_id==$coupon->community_id){
							if($coupon->coupon_type==1){
								$status = 1;
								$message = 'Coupon applied successfully.';
								$discount_percentage = $coupon->discount_percentage;
								if ($coupon->discount_percentage > 0) {
									if ($coupon->discount_percentage > 100) {
										$discount_percentage = 100;
									}
				
									$discounted_amount = ($amount / 100) * $discount_percentage;
									$new_amount = $amount - $discounted_amount;
									$discounted_amount = number_format($discounted_amount, 2, '.', ',');
									$discount_percentage_value = $discount_percentage;
									$discount_percentage = $discount_percentage.'%';
								}
							}else{
								$status = 1;
								$message = 'Coupon applied successfully.';
								//$discount_percentage = $coupon->discount_percentage;
								$discount_percentage ="";
								if ($coupon->amount > 0) {
									
									$discounted_amount = $coupon->amount;
									$new_amount = $amount - $discounted_amount;
									$discounted_amount = number_format($discounted_amount, 2, '.', ',');
									$discount_percentage_value = $discount_percentage;
									$discount_percentage = "Flat".$discount_percentage;
								}
							}
						}
					}elseif($apply_type=='user_topup'){
						$user=$this->userRepository()->getById($apply_type_id);
						if($user->external_community==$coupon->community_id){
							if($coupon->coupon_type==1){
								$status = 1;
								$message = 'Coupon applied successfully.';
								$discount_percentage = $coupon->discount_percentage;
								if ($coupon->discount_percentage > 0) {
									if ($coupon->discount_percentage > 100) {
										$discount_percentage = 100;
									}
				
									$discounted_amount = ($amount / 100) * $discount_percentage;
									$new_amount = $amount - $discounted_amount;
									$discounted_amount = number_format($discounted_amount, 2, '.', ',');
									$discount_percentage_value = $discount_percentage;
									$discount_percentage = $discount_percentage.'%';
								}
							}else{
								$status = 1;
								$message = 'Coupon applied successfully.';
								//$discount_percentage = $coupon->discount_percentage;
								$discount_percentage ="";
								if ($coupon->amount > 0) {
									
									$discounted_amount = $coupon->amount;
									$new_amount = $amount - $discounted_amount;
									$discounted_amount = number_format($discounted_amount, 2, '.', ',');
									$discount_percentage_value = $discount_percentage;
									$discount_percentage = "Flat".$discount_percentage;
								}
							}
						}	
                    }elseif($apply_type=='community_subadmin_limit'){
                       /* if((int)$apply_type_id==(int)$coupon->community_id){
                            if($coupon->coupon_type==1){
                                $status = 1;
                                $message = 'Coupon applied successfully.';
                                $discount_percentage = $coupon->discount_percentage;
                                if ($coupon->discount_percentage > 0) {
                                    if ($coupon->discount_percentage > 100) {
                                        $discount_percentage = 100;
                                    }

                                    $discounted_amount = ($amount / 100) * $discount_percentage;
                                    $new_amount = $amount - $discounted_amount;
                                    $discounted_amount = number_format($discounted_amount, 2, '.', ',');
                                    $discount_percentage_value = $discount_percentage;
                                    $discount_percentage = $discount_percentage.'%';
                                }
                            }else{
                                $status = 1;
                                $message = 'Coupon applied successfully.';
                                $discount_percentage ="";
                                if ($coupon->amount > 0) {

                                    $discounted_amount = $coupon->amount;
                                    $new_amount = $amount - $discounted_amount;
                                    $discounted_amount = number_format($discounted_amount, 2, '.', ',');
                                    $discount_percentage_value = $discount_percentage;
                                    $discount_percentage = "Flat".$discount_percentage;
                                }
                            }
                        }*/
					}elseif($apply_type=='events_ticket' || $apply_type=='events_donate'){
						$post=$this->postRepository()->getById($apply_type_id);
						if($post){
							if($post->posted_in_community==$coupon->community_id || $post->community_id==$coupon->community_id){
								if($coupon->coupon_type==1){
									$status = 1;
									$message = 'Coupon applied successfully.';
									$discount_percentage = $coupon->discount_percentage;
									if ($coupon->discount_percentage > 0) {
										if ($coupon->discount_percentage > 100) {
											$discount_percentage = 100;
										}
					
										$discounted_amount = ($amount / 100) * $discount_percentage;
										$new_amount = $amount - $discounted_amount;
										$discounted_amount = number_format($discounted_amount, 2, '.', ',');
										$discount_percentage_value = $discount_percentage;
										$discount_percentage = $discount_percentage.'%';
									}
								}else{
									$status = 1;
									$message = 'Coupon applied successfully.';
									//$discount_percentage = $coupon->discount_percentage;
									$discount_percentage ="";
									if ($coupon->amount > 0) {
										
										$discounted_amount = $coupon->amount;
										$new_amount = $amount - $discounted_amount;
										$discounted_amount = number_format($discounted_amount, 2, '.', ',');
										$discount_percentage_value = $discount_percentage;
										$discount_percentage = "Flat".$discount_percentage;
									}
								}
							}
						}
                    }elseif($apply_type=='invoice_payment'){
                       /* $invoice = $this->communityInvoiceRepository()->getByCmPrId((int) $apply_type_id, 0);
                        $invoice_community_id = 0;
                        if ($invoice) {
                            $invoice_community_id = (int) ($invoice->community_id ?? 0);
                            if ($invoice_community_id <= 0) {
                                $invoice_community_id = (int) ($invoice->to_community_id ?? 0);
                            }
                        }

                        if($invoice && $invoice_community_id == (int) $coupon->community_id){
                            if($coupon->coupon_type==1){
                                $status = 1;
                                $message = 'Coupon applied successfully.';
                                $discount_percentage = $coupon->discount_percentage;
                                if ($coupon->discount_percentage > 0) {
                                    if ($coupon->discount_percentage > 100) {
                                        $discount_percentage = 100;
                                    }

                                    $discounted_amount = ($amount / 100) * $discount_percentage;
                                    $new_amount = $amount - $discounted_amount;
                                    $discounted_amount = number_format($discounted_amount, 2, '.', ',');
                                    $discount_percentage_value = $discount_percentage;
                                    $discount_percentage = $discount_percentage.'%';
                                }
                            }else{
                                $status = 1;
                                $message = 'Coupon applied successfully.';
                                $discount_percentage ="";
                                if ($coupon->amount > 0) {
                                    $discounted_amount = $coupon->amount;
                                    $new_amount = $amount - $discounted_amount;
                                    $discounted_amount = number_format($discounted_amount, 2, '.', ',');
                                    $discount_percentage_value = $discount_percentage;
                                    $discount_percentage = "Flat".$discount_percentage;
                                }
                            }
                        }*/
					}
				}
				
            }
        }

        if ($apply_type == 'invoice_payment') {
            $invoiceId = (int) $apply_type_id;
            $userId = (int) \Auth::id();
            $sessionKey = 'invoice_coupon_apply_'.$userId.'_'.$invoiceId;

            if ($status == 1 && $invoiceId > 0 && $coupon_code) {
                \Session::put($sessionKey, [
                    'invoice_id' => $invoiceId,
                    'coupon_code' => (string) $coupon_code,
                    'applied' => 1,
                    'updated_at' => time(),
                ]);
            } else {
                \Session::forget($sessionKey);
            }
        }

        $amount = round((float) $amount, 2);
        $new_amount = round((float) $new_amount, 2);
        $discounted_amount_value = round((float) str_replace(',', '', (string) $discounted_amount), 2);

        if ($discounted_amount_value < 0) {
            $discounted_amount_value = 0;
        }

        if ($status == 1) {
            if ($discounted_amount_value > $amount) {
                $discounted_amount_value = $amount;
            }
            $new_amount = round($amount - $discounted_amount_value, 2);
        }

        if ($new_amount < 0) {
            $new_amount = 0;
        }

        $discounted_amount = number_format($discounted_amount_value, 2, '.', ',');

        return json_encode([
            'message' => $message,
            'discount_percentage' => $discount_percentage,
            'discount_percentage_value' => $discount_percentage_value,
            'new_amount' => number_format($new_amount, 2, '.', ','),
            'new_amount_original' => $new_amount,
            'discounted_amount' => $discounted_amount,
            'actual_amount' => number_format($amount, 2, '.', ','),
            'plan_cost' => number_format($planAmount, 2, '.', ','),
            //'additional_user_cost' => number_format($increasedAmount, 2, '.', ','),
            //'purchased_space_charges' => number_format($purchased_space_charges, 2, '.', ','),
            'status' => $status,
        ]);
    }

    public function checkTaxAmount(Request $request)
    {
        $amount = $request->get('amount');
        $address = $request->get('address');
        $city = $request->get('city');
        $state = $request->get('state');
        $postal_code = $request->get('postal_code');
        $country = $request->get('country');
        $currency = $request->get('currency');

        return $this->communityRepository()->checkTaxAmount($amount, $address, $city, $state, $postal_code, $country, $currency);
    }

    public function subscriptionInvoice($slug, $type, $type_id)
    {
        $community = $this->communityRepository()->getBySlug($slug);
        if (! $community) {
            return $this->notFound();
        }

        $this->community = $community;

        if (! ($this->community->isOwner())) {
            redirect('home')->send();
        }

        $record = '';
        if ($type == 'plans_payments') {
            $record = $this->communityPricingPlanPaymentRepository()->getById($type_id);
        } elseif ($type == 'plans_invoice') {
            $record = $this->communityInvoiceRepository()->communitySubscriptionInvoiceById($type_id, $community->id);
        }

        $default_card = $this->communityPricingPlanPaymentCardsRepository()->defaultCard($community->id, $community->user_id, 'community_plan');

        $cards = $this->communityPricingPlanPaymentCardsRepository()->getAllCards($community->id, $community->user_id, 'community_plan');

        return $this->render('community.pannel.plan.view-invoice', [
            'type' => $type,
            'type_id' => $type_id,
            'record' => $record,
            'default_card' => $default_card,
            'community' => $community,
            'cards' => $cards,
        ], [
            'title' => $this->setTitle('View Invoice'),
        ]);
    }

    public function makeSubCardDefault(Request $request)
    {
        $cm_id = $request->get('cm_id');
        $card_id = $request->get('card_id');

        $community = $this->communityRepository()->getBySlug($cm_id);
        if (! $community) {
            return $this->notFound();
        }

        if (! ($community->isOwner())) {
            return false;
        }

        $card = $this->communityPricingPlanPaymentCardsRepository()->getById($card_id);
        if ($card and $card->community_id == $community->id) {

            $this->communityPricingPlanPaymentCardsRepository()->removeOtherDefault($community);

            $card->is_default = 1;
            $card->save();
        }
    }

    public function eventsCalendar($slug)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }
        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }

        if (! \Auth::check()) {
            $this->communityOutsideTheme($this->community);
        }

        $event_posts = $this->postRepository()->getAllEvents($community->id);

        $calendarEventsList = [];
        if ($event_posts) {
            foreach ($event_posts as $post) {
                if ($post->present()->canViewPagePost() and $post->present()->canShow()) {
                    $event = $post->present()->getEvent();
                    if ($event and $event->fund_nature == 0) {
                        $color = '#000';
                        $startTime = $event->starttime;
                        $endTime = $event->endtime;

                        $startTimeFormated = date('Y-m-d H:i', strtotime($startTime));
                        $endTimeFormated = date('Y-m-d H:i', strtotime($endTime));

                        $calendarEventsList[] = [
                            'title' => $event->subject,
                            'start' => $startTimeFormated,
                            'end' => $endTimeFormated,
                            'color' => $color,
                            'url' => $post->present()->communityPostUrl(),
                        ];

                    }
                }
            }
        }

        $datesEvent = json_encode($calendarEventsList, true);

        return $this->render('community.events.events-calendar', ['community' => $this->community, 'datesEvent' => $datesEvent]);
    }

    public function getChatBoatMsg()
    {
        $paramsFetch = json_decode(
            file_get_contents('php://input'),
            true
        );

        $community_id = $paramsFetch['community_id'];
        $file_url = '';

        if ($community_id) {
            $community = $this->communityRepository()->getBySlug($community_id);
            $contents = $this->communityHomeContentsRepository()->getByCommunityId($community_id);
            if ($contents and $contents->show_ai_chatbot == 1 and $contents->ai_chatbot_file) {
                $file_url = \Image::url($contents->ai_chatbot_file);
            }
        } elseif ($community_id == 0) {
            $file_url = \Image::url(config('ai_chatbot_file'));
        }

        $quest = $paramsFetch['message'];
        $ai_chatbot_key = $request->get('ai_chatbot_key');

        if ($file_url != '') {
            $resMessage = $this->sendChatbotMessage($paramsFetch['message'], $file_url);
        } else {
            $resMessage = 'Sorry! No result found for '.'"'.$quest.'"';
        }

        $this->aiChatbotTrackingRepository()->addData($community_id, $quest, $resMessage, 0, 0, $ai_chatbot_key);

        $jsonResponse = json_encode(['responseMessage' => $resMessage]);

        return $jsonResponse;
    }

    public function sendChatbotMessage(string $message, $file_url)
    {
        $this->authorization = config('chatgpt.chagpt_api_key');
        $this->endpoint = 'https://api.openai.com/v1/chat/completions';

        $jsonSampleData = file_get_contents($file_url);

        $data = [
            'messages' => [
                [
                    'role' => 'system',
                    'content' => 'Summarize the following and provide in HTML format and given links and display youtube videos in iframe from and remove extra line br. Remove unnecessary Page link to a description unless there is a specific purposely linked call to action (CTA)'.$jsonSampleData,
                ],
                [
                    'role' => 'user',
                    'content' => $message,
                ],
            ],
            'model' => 'gpt-3.5-turbo',
        ];

        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer '.$this->authorization,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->endpoint);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception('Error sending the message: '.$error);
        }

        curl_close($ch);

        $arrResult = json_decode($response, true);
        $resultMessage = $arrResult['choices'][0]['message']['content'];

        // $breaks = array("<br />","<br>","<br/>","<br />");
        // $output_formated = str_ireplace($breaks, "\r\n", $resultMessage);

        // return nl2br($resultMessage);
        $breaks = ['<br />', '<br>', '<br/>', '<br />'];
        $output_formated = str_ireplace($breaks, '', $resultMessage);

        return $output_formated;
    }

    public function getDefaultChatBoatMsg(Request $request)
    {
        $community_id = $request->get('community_id');

        $can_show_form = 'no';
        $show_lastname_mondatory = 'no';
        $show_phonenumber_mondatory = 'no';

        $chatAdmnbotLogo = \Image::url(config('ai_chatbot_logo'));

        if ($community_id == 0) {
            if (config('show_form_on_ai_chat') == 1) {
                $can_show_form = 'yes';
            }

            if (config('show_lastname_mondatory')) {
                $show_lastname_mondatory = 'yes';
            }

            if (config('show_phonenumber_mondatory')) {
                $show_phonenumber_mondatory = 'yes';
            }
        } else {
            $contents = $this->communityHomeContentsRepository()->getByCommunityId($community_id);
            if ($contents) {
                if ($contents->show_form_on_ai_chat == 1) {
                    $can_show_form = 'yes';
                }

                if ($contents->show_lastname_mondatory == 1) {
                    $show_lastname_mondatory = 'yes';
                }

                if ($contents->show_phonenumber_mondatory == 1) {
                    $show_phonenumber_mondatory = 'yes';
                }

                if ($contents->ai_chatbot_logo) {
                    $chatAdmnbotLogo = $contents->ai_chatbot_logo;
                    $chatAdmnbotLogo = \Image::url($chatAdmnbotLogo);
                }
            }
        }

        $questions = $this->aiDefaultQuestionsRepository()->getActiveMainQuestionsInformal($community_id);
        $buttons = $this->aiDefaultQuestionsRepository()->getActiveMainButtonsInformal($community_id);

        $resMessage1 = (string) $this->theme->section('messages.ai-default-chatbot', ['questions' => $questions, 'ai_msg_type' => 'default-chat-msg-informal', 'chatAdmnbotLogo' => $chatAdmnbotLogo]);

        $resMessage2 = (string) $this->theme->section('messages.ai-default-chatbot', ['questions' => $buttons, 'hide_usr_admn' => 'yes', 'ai_msg_type' => 'default-chat-msg-informal', 'chatAdmnbotLogo' => $chatAdmnbotLogo]);

        $resMessage3 = (string) $this->theme->section('messages.ai-default-chatbot-form', ['community_id' => $community_id, 'can_show_form' => $can_show_form, 'ai_msg_type' => 'default-chat-msg-informal', 'show_lastname_mondatory' => $show_lastname_mondatory, 'show_phonenumber_mondatory' => $show_phonenumber_mondatory]);

        $resMessage = $resMessage1.$resMessage2.$resMessage3;

        $jsonResponse = json_encode(['responseMessage' => $resMessage]);

        return $jsonResponse;
    }

    public function storeInformationChatBotMsg(Request $request)
    {
        $community_id = $request->get('chat_community_id');
        $chat_first_name = $request->get('chat_first_name');
        $chat_last_name = $request->get('chat_last_name');
        $chat_email_address = $request->get('chat_email_address');
        $phoneNumber = $request->get('phoneNumber');
        $defaultCountry = $request->get('defaultCountry');
        $carrierCode = $request->get('carrierCode');
        $ai_chatbot_key = $request->get('ai_chatbot_key');

        $chatAdmnbotLogo = \Image::url(config('ai_chatbot_logo'));
        if ($community_id > 0) {
            $contents = $this->communityHomeContentsRepository()->getByCommunityId($community_id);
            if ($contents) {
                if ($contents->ai_chatbot_logo) {
                    $chatAdmnbotLogo = $contents->ai_chatbot_logo;
                    $chatAdmnbotLogo = \Image::url($chatAdmnbotLogo);
                }
            }
        }

        $this->aiChatbotTrackingRepository()->addFormData($community_id, 'Information Form', '', 0, 2, $ai_chatbot_key, $chat_first_name, $chat_last_name, $chat_email_address, $phoneNumber, $defaultCountry, $carrierCode);

        $questions = $this->aiDefaultQuestionsRepository()->getActiveMainQuestionsFormal($community_id);
        $buttons = $this->aiDefaultQuestionsRepository()->getActiveMainButtonsFormal($community_id);
        $resMessage1 = (string) $this->theme->section('messages.ai-default-chatbot', ['questions' => $questions, 'chat_first_name' => $chat_first_name, 'chatAdmnbotLogo' => $chatAdmnbotLogo]);
        $resMessage2 = (string) $this->theme->section('messages.ai-default-chatbot', ['questions' => $buttons, 'hide_usr_admn' => 'yes', 'chatAdmnbotLogo' => $chatAdmnbotLogo]);

        $resMessage = $resMessage1.$resMessage2;

        $jsonResponse = json_encode(['responseMessage' => $resMessage]);

        return $jsonResponse;
    }

    public function getSubChatBoatMsg(Request $request)
    {
        $community_id = $request->get('community_id');
        $question_id = $request->get('question_id');
        $quest_type = $request->get('quest_type');
        $ai_chatbot_key = $request->get('ai_chatbot_key');
        $resMessage = '';

        $chatAdmnbotLogo = \Image::url(config('ai_chatbot_logo'));
        if ($community_id > 0) {
            $contents = $this->communityHomeContentsRepository()->getByCommunityId($community_id);
            if ($contents) {
                if ($contents->ai_chatbot_logo) {
                    $chatAdmnbotLogo = $contents->ai_chatbot_logo;
                    $chatAdmnbotLogo = \Image::url($chatAdmnbotLogo);
                }
            }
        }

        $question = $this->aiDefaultQuestionsRepository()->getActiveByCmId($question_id, $community_id);
        if ($question) {

            $this->aiChatbotTrackingRepository()->addData($community_id, $question->question, '', $question_id, 1, $ai_chatbot_key);

            if ($quest_type == 'subquest') {
                $questions = $this->aiDefaultQuestionsRepository()->getActiveSubQuestions($community_id, $question_id);
                $resMessage = (string) $this->theme->section('messages.ai-default-chatbot', ['questions' => $questions, 'chatAdmnbotLogo' => $chatAdmnbotLogo]);
            }
        }

        $jsonResponse = json_encode(['responseMessage' => $resMessage]);

        return $jsonResponse;
    }

    public function storeChatBotMsg(Request $request)
    {
        $community_id = $request->get('community_id');
        $question_id = $request->get('question_id');
        $ai_chatbot_key = $request->get('ai_chatbot_key');

        $question = $this->aiDefaultQuestionsRepository()->getActiveByCmId($question_id, $community_id);
        if ($question) {

            $this->aiChatbotTrackingRepository()->addData($community_id, $question->question, '', $question_id, 1, $ai_chatbot_key);
        }
    }

    public function saveChatbotHtml($chatBotUniqueId)
    {
        /*$cookie_name = 'chatBotUniqueId';

        $domainData = explode('.', \Request::getHost());
        $expireTime = time() + (86400 * 30);
        $cookie_value = $chatBotUniqueId;

        if(isset($domainData[2]) and $domainData[0]!='www' and \Request::getHost()!="dev.wakhal.com" and \Request::getHost()!="new.wakhal.com"){
            setcookie($cookie_name, $cookie_value, $expireTime);
        }else{
            setcookie($cookie_name, $cookie_value, $expireTime);
        }*/

        \Session::put('chatBotUniqueId', $chatBotUniqueId);

        // $_SESSION['chatBotUniqueId']=$chatBotUniqueId;

        // return $this->theme->section('messages.chatbot-html',['chatBotHTML'=>'Hello there']);

    }

    public function storeChatbotData(Request $request)
    {
        $chatBotUniqueId = $request->get('chatBotUniqueId');
        $chatBotHTML = $request->get('chatBotHTML');

        \Session::put('chatBotUniqueId', $chatBotUniqueId);

        $this->aiChatbotDataRepository()->addData($chatBotUniqueId, $chatBotHTML);

        /*$listedDomains=config('show_default_chatbot_domains');
        $imageString="";
        if($listedDomains){
            $domains=explode(",",$listedDomains);
            foreach($domains as $domain){
                $domain=trim($domain);
                $imageString=$imageString.'<img src="'.$domain.'/cm/savechatbothtml/'.$chatBotUniqueId.'" />';
            }
        }

        return $imageString;*/

        // return $this->theme->section('messages.chatbot-html');
    }

    public function getStoreChatbotData(Request $request)
    {
        $chatBotUniqueId = $request->get('chatBotUniqueId');
        $data = $this->aiChatbotDataRepository()->getData($chatBotUniqueId);
        if ($data) {
            return $data->html_data;
        }
    }

    public function deteteStoreChatbotData(Request $request)
    {
        $chatBotUniqueId = $request->get('chatBotUniqueId');
        $data = $this->aiChatbotDataRepository()->deteteStoreChatbotData($chatBotUniqueId);
        setcookie('chatBotUniqueId', '', time() - 7000000, '/', \Request::getHost());
    }

    public function getConversationBox(Request $request)
    {
        $community_id = $request->get('community_id');

        $can_show_form = 'yes';
        $show_lastname_mondatory = 'no';
        $show_phonenumber_mondatory = 'no';

        $chatAdmnbotLogo = \Image::url(config('ai_chatbot_logo'));

        if ($community_id == 0) {
            if (config('show_lastname_mondatory')) {
                $show_lastname_mondatory = 'yes';
            }

            if (config('show_phonenumber_mondatory')) {
                $show_phonenumber_mondatory = 'yes';
            }
        } else {
            $contents = $this->communityHomeContentsRepository()->getByCommunityId($community_id);
            if ($contents) {
                if ($contents->show_lastname_mondatory == 1) {
                    $show_lastname_mondatory = 'yes';
                }

                if ($contents->show_phonenumber_mondatory == 1) {
                    $show_phonenumber_mondatory = 'yes';
                }

                if ($contents->ai_chatbot_logo) {
                    $chatAdmnbotLogo = $contents->ai_chatbot_logo;
                    $chatAdmnbotLogo = \Image::url($chatAdmnbotLogo);
                }
            }
        }

        $resMessage3 = (string) $this->theme->section('messages.ai-default-chatbot-form', ['community_id' => $community_id, 'can_show_form' => $can_show_form, 'ai_msg_type' => 'default-chat-msg-informal', 'show_lastname_mondatory' => $show_lastname_mondatory, 'show_phonenumber_mondatory' => $show_phonenumber_mondatory]);

        $resMessage = $resMessage3;

        $jsonResponse = json_encode(['responseMessage' => $resMessage]);

        return $jsonResponse;
    }

    public function getConversationBoxBtn(Request $request)
    {
        $community_id = $request->get('community_id');

        $can_show_form = 'yes';
        $show_lastname_mondatory = 'no';
        $show_phonenumber_mondatory = 'no';

        $chatAdmnbotLogo = \Image::url(config('ai_chatbot_logo'));

        if ($community_id == 0) {
            if (config('show_form_on_ai_chat') == 2) {
                // $can_show_form='yes';
            }

            if (config('show_lastname_mondatory')) {
                $show_lastname_mondatory = 'yes';
            }

            if (config('show_phonenumber_mondatory')) {
                $show_phonenumber_mondatory = 'yes';
            }
        } else {
            $contents = $this->communityHomeContentsRepository()->getByCommunityId($community_id);
            if ($contents) {
                if ($contents->show_form_on_ai_chat == 2) {
                    // $can_show_form='yes';
                }

                if ($contents->show_lastname_mondatory == 1) {
                    $show_lastname_mondatory = 'yes';
                }

                if ($contents->show_phonenumber_mondatory == 1) {
                    $show_phonenumber_mondatory = 'yes';
                }

                if ($contents->ai_chatbot_logo) {
                    $chatAdmnbotLogo = $contents->ai_chatbot_logo;
                    $chatAdmnbotLogo = \Image::url($chatAdmnbotLogo);
                }
            }
        }

        // $resMessage="";
        // if($can_show_form=="yes"){
        $resMessage3 = (string) $this->theme->section('messages.ai-default-chatbot-form', ['community_id' => $community_id, 'can_show_form' => $can_show_form, 'ai_msg_type' => 'default-chat-msg-informal', 'show_lastname_mondatory' => $show_lastname_mondatory, 'show_phonenumber_mondatory' => $show_phonenumber_mondatory]);
        $resMessage = $resMessage3;
        // }

        $jsonResponse = json_encode(['responseMessage' => $resMessage]);

        return $jsonResponse;
    }

    public function changeAwardCategoryColor(Request $request)
    {
        $catid = $request->get('catid');
        $form_id = $request->get('form_id');
        $type = $request->get('type');
        $prmColor = $request->get('prmColor');

        $user_id = \Auth::user()->id;

        $form = $this->communityFormsRepository()->getById($form_id);
        if ($form and $form->user_id == $user_id) {
            $category = $this->communityFormsCategoryRepository()->getById($catid, $form->community_id);
            if ($category) {
                if ($type == 'bg_color') {
                    $category->background_color = $prmColor;
                    $category->save();
                }

                if ($type == 'texts_color') {
                    $category->texts_color = $prmColor;
                    $category->save();
                }
            }

            return $category;
        }

        return 'false';
    }

    public function changeAwardCategoryFontsize(Request $request)
    {
        $catid = $request->get('catid');
        $form_id = $request->get('form_id');
        $value = $request->get('value');

        $user_id = \Auth::user()->id;

        $form = $this->communityFormsRepository()->getById($form_id);
        if ($form and $form->user_id == $user_id) {
            $category = $this->communityFormsCategoryRepository()->getById($catid, $form->community_id);
            if ($category) {
                $category->font_size = $value;
                $category->save();
            }

            return $category;
        }

        return 'false';
    }

    public function changeAwardFormColors(Request $request)
    {
        $form_id = $request->get('form_id');
        $type = $request->get('type');
        $prmColor = $request->get('prmColor');

        $user_id = \Auth::user()->id;

        $form = $this->communityFormsRepository()->getById($form_id);
        if ($form and $form->user_id == $user_id) {
            if ($type == 'title_bg') {
                $form->title_background_color = $prmColor;
                $form->save();
            } elseif ($type == 'title_text') {
                $form->title_texts_color = $prmColor;
                $form->save();
            }

            return $form;
        }

        return 'false';
    }
	
	public function chmberBusinessRegistration($slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }
		
        if($community->present()->isChamberCommunity()){

            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }

            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $community->title);
            $this->theme->share('ogTitle', $community->title);
            $this->theme->share('ogImage', $community->present()->getLogo());
            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
            $this->theme->share('site_description', $community->title);


            if ($request->isMethod('post') && $request->get('val')) {
                $val = (array) $request->get('val');

                $validator = \Validator::make($val, [
                    'organization_name' => 'required|string|max:255',
                    'organization_email' => 'required|email|max:255',
                    'admin_name' => 'required|string|max:255',
                    'admin_email' => 'required|email|max:255',
                    //'contact' => 'nullable|string|max:255',
                    'website' => 'nullable|string|max:255',
                    'organization_address' => 'nullable|string',
                    'about_organization' => 'nullable|string',
                    'number_of_emp' => 'nullable|integer|min:0',
					'category' => 'nullable|integer|min:1',
					'x_link' => 'nullable|string|max:255',
					'linkedin_link' => 'nullable|string|max:255',
					'facebook_link' => 'nullable|string|max:255',
					'instagram_link' => 'nullable|string|max:255',
					'tiktok_link' => 'nullable|string|max:255',
					'youtube_link' => 'nullable|string|max:255',
                ]);

                if ($validator->fails()) {
                    return redirect()->back()->withErrors($validator)->withInput();
                }
				
				$cell_no = $request->get('phoneNumber');
           	    $defaultCountry = $request->get('defaultCountry');
            	$carrierCode = $request->get('carrierCode');
				
				$user = $this->userRepository()->findByBothEmail($val['admin_email']);
				$userId=0;
				
				if ($user) {
                    $userId = $user->id;
                } else {
					$username=$val['admin_name'];

					$signup_type_id = $community->id;
                    $signup_type = 'chamber-business-registration';
					
                    $userVals=[
                        'username'=>$username,
                        'email_address'=>$val['admin_email'],
                        'fullname'=>$username,
                        'communityId'=>$community->id,
                        'type'=>"autosignup",
                        'is_active'=>1,
                        'signup_type'=>$signup_type,
                        'signup_type_id'=>$signup_type_id,
						'postUrl'=>''
                    ];

                    $user=$this->userRepository()->appointmentSignup($userVals);
                    if($user){
                         $userId = $user->id;
                    }
				}
				
				if($userId){
                    $data=$this->communityChamberBusinessRepository()->add($community, $val, (int) $userId, $request);
					if($data){
						$data->contact = $cell_no;
						$data->country_iso_code = $defaultCountry;
						$data->carrier_code = $carrierCode;
						$data->save();
					}
					
					return redirect()->back()->with('success', 'Business registration submitted successfully.');
				}else{
					return redirect()->back()->with('danger', 'Something went wrong, try again later.');
				}	
            }

			$page_header = $this->communityPagesRepository()->getByIdComIdHeader('chamber_registration',$this->community->id);
			
            return $this->render('community.chamber.registration', [
                'community' => $community,
				'page_header'=>$page_header,
				'categories' => $this->pageCategoryRepository()->listAll(),
            ], [
                'title' => $this->setTitle(''),
            ]);
        } else {
            return redirect($this->community->present()->url());
        }
	}
	
	public function chamberBusinessList($slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }
		
        if($community->present()->isChamberCommunity()){

            if (! \Auth::check()) {
                $this->communityOutsideTheme($community);
            }

            $this->theme->share('ogUrl', $community->present()->url());
            $this->theme->share('ogSiteName', $community->title);
            $this->theme->share('ogTitle', $community->title);
            $this->theme->share('ogImage', $community->present()->getLogo());
            $this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
            $this->theme->share('site_description', $community->title);

            $businesses = $this->communityChamberBusinessRepository()->getByCommunityStatus($this->community->id, 1);

			$page_header = $this->communityPagesRepository()->getByIdComIdHeader('chamber_directory',$this->community->id);
			
            return $this->render('community.chamber.listing', [
                'community' => $community,
				'page_header'=>$page_header,
				'businesses' => $businesses,
            ], [
                'title' => $this->setTitle(''),
            ]);
        } else {
            return redirect($this->community->present()->url());
        }
	}
	
	public function chamberBusiness($slug,$biz_slug, Request $request)
    {
        $this->community = $this->communityRepository()->getBySlug($slug);
        if (! $this->community) {
            return $this->notFound();
        }

        $community = $this->community;
        if ($redUrl = $community->present()->hasExpiredCommunity()) {
            return redirect($redUrl);
        }
		
        if($community->present()->isChamberCommunity()){
            $business = $this->communityChamberBusinessRepository()->getBySlug($biz_slug);

			if($business and $business->community_id==$this->community->id and $business->status==1){
				
				if (! \Auth::check()) {
					$this->communityOutsideTheme($community);
				}
	
				$this->theme->share('ogUrl', $community->present()->url('biz/'.$business->slug));
				$this->theme->share('ogSiteName', $business->organization_name);
				$this->theme->share('ogTitle', $business->organization_name);
				$this->theme->share('ogImage', $community->present()->getLogo());
				$this->theme->share('feviconImage', $community->present()->getFeviconAvatar());
				$this->theme->share('site_description', $business->organization_name);

				$page_header = $this->communityPagesRepository()->getByIdComIdHeader('chamber_profile',$this->community->id);
				
				$businessDays = $this->chamberBusinessdaysRepository()->getByChamberBusinessId($business->id);
				
				return $this->render('community.chamber.business', [
					'community' => $community,
					'page_header'=>$page_header,
					'business' => $business,
					'businessDays'=>$businessDays,
                    'categories' => $this->pageCategoryRepository()->listAll(),
				], [
					'title' => $this->setTitle(''),
				]);
			}	
        } 
        
		return redirect($this->community->present()->url());
	}
}